AsyncMethodToStateMachineRewriter.cs 24.3 KB
Newer Older
1 2 3 4 5 6 7
// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Runtime.CompilerServices;
8
using Microsoft.CodeAnalysis.CodeGen;
9 10
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
11
using Microsoft.CodeAnalysis.Symbols;
12 13 14 15
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp
{
16
    internal sealed class AsyncMethodToStateMachineRewriter : MethodToStateMachineRewriter
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
    {
        /// <summary>
        /// The method being rewritten.
        /// </summary>
        private readonly MethodSymbol method;

        /// <summary>
        /// The field of the generated async class used to store the async method builder: an instance of
        /// <see cref="AsyncVoidMethodBuilder"/>, <see cref="AsyncTaskMethodBuilder"/>, or <see cref="AsyncTaskMethodBuilder{TResult}"/> depending on the
        /// return type of the async method.
        /// </summary>
        private readonly FieldSymbol asyncMethodBuilderField;

        /// <summary>
        /// A collection of well-known members for the current async method builder.
        /// </summary>
        private readonly AsyncMethodBuilderMemberCollection asyncMethodBuilderMemberCollection;

        /// <summary>
        /// The exprReturnLabel is used to label the return handling code at the end of the async state-machine
        /// method. Return expressions are rewritten as unconditional branches to exprReturnLabel.
        /// </summary>
        private readonly LabelSymbol exprReturnLabel;

        /// <summary>
        /// The label containing a return from the method when the async method has not completed.
        /// </summary>
        private readonly LabelSymbol exitLabel;

        /// <summary>
        /// The field of the generated async class used in generic task returning async methods to store the value
        /// of rewritten return expressions. The return-handling code then uses <c>SetResult</c> on the async method builder
        /// to make the result available to the caller.
        /// </summary>
        private readonly LocalSymbol exprRetValue;

        private readonly LoweredDynamicOperationFactory dynamicFactory;

55
        private readonly Dictionary<TypeSymbol, FieldSymbol> awaiterFields;
56
        private int nextAwaiterId;
57 58 59

        internal AsyncMethodToStateMachineRewriter(
            MethodSymbol method,
60
            int methodOrdinal,
61 62 63 64
            AsyncMethodBuilderMemberCollection asyncMethodBuilderMemberCollection,
            SyntheticBoundNodeFactory F,
            FieldSymbol state,
            FieldSymbol builder,
65
            IReadOnlySet<Symbol> hoistedVariables,
66
            IReadOnlyDictionary<Symbol, CapturedSymbolReplacement> nonReusableLocalProxies,
67 68 69
            SynthesizedLocalOrdinalsDispenser synthesizedLocalOrdinals,
            VariableSlotAllocator slotAllocatorOpt,
            int nextFreeHoistedLocalSlot,
70
            DiagnosticBag diagnostics)
71
            : base(F, method, state, hoistedVariables, nonReusableLocalProxies, synthesizedLocalOrdinals, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics, useFinalizerBookkeeping: false)
72 73 74 75 76 77 78 79
        {
            this.method = method;
            this.asyncMethodBuilderMemberCollection = asyncMethodBuilderMemberCollection;
            this.asyncMethodBuilderField = builder;
            this.exprReturnLabel = F.GenerateLabel("exprReturn");
            this.exitLabel = F.GenerateLabel("exitLabel");

            this.exprRetValue = method.IsGenericTaskReturningAsync(F.Compilation)
80
                ? F.SynthesizedLocal(asyncMethodBuilderMemberCollection.ResultType, syntax: F.Syntax, kind: SynthesizedLocalKind.AsyncMethodReturnValue)
81 82
                : null;

83
            this.dynamicFactory = new LoweredDynamicOperationFactory(F, methodOrdinal);
84
            this.awaiterFields = new Dictionary<TypeSymbol, FieldSymbol>(TypeSymbol.EqualsIgnoringDynamicComparer);
85
            this.nextAwaiterId = slotAllocatorOpt?.PreviousAwaiterSlotCount ?? 0;
86 87 88 89 90
        }

        private FieldSymbol GetAwaiterField(TypeSymbol awaiterType)
        {
            FieldSymbol result;
91 92 93 94 95

            // Awaiters of the same type always share the same slot, regardless of what await expressions they belong to.
            // Even in case of nested await expressions only one awaiter is active.
            // So we don't need to tie the awaiter variable to a particular await expression and only use its type 
            // to find the previous awaiter field.
96 97
            if (!awaiterFields.TryGetValue(awaiterType, out result))
            {
98 99 100 101 102
                int slotIndex = -1;
                if (slotAllocatorOpt != null)
                {
                    slotIndex = slotAllocatorOpt.GetPreviousAwaiterSlotIndex((Cci.ITypeReference)awaiterType);
                }
103

104
                if (slotIndex == -1)
105
                {
106
                    slotIndex = nextAwaiterId++;
107 108
                }

109 110
                string fieldName = GeneratedNames.AsyncAwaiterFieldName(slotIndex);
                result = F.StateMachineField(awaiterType, fieldName, SynthesizedLocalKind.AwaiterField, slotIndex);
111 112
                awaiterFields.Add(awaiterType, result);
            }
113

114 115 116 117 118 119 120 121 122 123
            return result;
        }

        /// <summary>
        /// Generate the body for <c>MoveNext()</c>.
        /// </summary>
        internal void GenerateMoveNext(BoundStatement body, MethodSymbol moveNextMethod)
        {
            F.CurrentMethod = moveNextMethod;

124
            BoundStatement rewrittenBody = (BoundStatement)Visit(body);
125 126 127

            var bodyBuilder = ArrayBuilder<BoundStatement>.GetInstance();

T
TomasMatousek 已提交
128 129
            bodyBuilder.Add(F.HiddenSequencePoint());
            bodyBuilder.Add(F.Assignment(F.Local(cachedState), F.Field(F.This(), stateField)));
130

131
            var exceptionLocal = F.SynthesizedLocal(F.WellKnownType(WellKnownType.System_Exception));
132 133
            bodyBuilder.Add(
                F.Try(
T
TomasMatousek 已提交
134 135 136
                    F.Block(ImmutableArray<LocalSymbol>.Empty,
                        // switch (state) ...
                        F.HiddenSequencePoint(),
137
                        Dispatch(),
T
TomasMatousek 已提交
138 139
                        // [body]
                        rewrittenBody
140 141 142 143 144 145
                    ),
                    F.CatchBlocks(
                        F.Catch(
                            exceptionLocal,
                            F.Block(
                                F.NoOp(method.ReturnsVoid ? NoOpStatementFlavor.AsyncMethodCatchHandler : NoOpStatementFlavor.Default),
T
TomasMatousek 已提交
146 147 148 149
                                // this.state = finishedState
                                F.Assignment(F.Field(F.This(), stateField), F.Literal(StateMachineStates.FinishedStateMachine)),
                                // builder.SetException(ex)
                                F.ExpressionStatement(
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
                                    F.Call(
                                        F.Field(F.This(), asyncMethodBuilderField),
                                        asyncMethodBuilderMemberCollection.SetException,
                                        F.Local(exceptionLocal))),
                                GenerateReturn(false)
                            )
                        )
                    )
                ));

            // ReturnLabel (for the rewritten return expressions in the user's method body)
            bodyBuilder.Add(F.Label(exprReturnLabel));

            // this.state = finishedState
            var stateDone = F.Assignment(F.Field(F.This(), stateField), F.Literal(StateMachineStates.FinishedStateMachine));
            var block = body.Syntax as BlockSyntax;
            if (block == null)
            {
                // this happens, for example, in (async () => await e) where there is no block syntax
                bodyBuilder.Add(stateDone);
            }
            else
            {
                bodyBuilder.Add(F.SequencePointWithSpan(block, block.CloseBraceToken.Span, stateDone));
                bodyBuilder.Add(F.HiddenSequencePoint());
                // The remaining code is hidden to hide the fact that it can run concurrently with the task's continuation
            }

            // builder.SetResult([RetVal])
            bodyBuilder.Add(
                F.ExpressionStatement(
                    F.Call(
                        F.Field(F.This(), asyncMethodBuilderField),
                        asyncMethodBuilderMemberCollection.SetResult,
                        method.IsGenericTaskReturningAsync(F.Compilation)
                            ? ImmutableArray.Create<BoundExpression>(F.Local(exprRetValue))
                            : ImmutableArray<BoundExpression>.Empty)));

            // this code is hidden behind a hidden sequence point.
            bodyBuilder.Add(F.Label(this.exitLabel));
            bodyBuilder.Add(F.Return());

            var newBody = bodyBuilder.ToImmutableAndFree();

            var locals = ArrayBuilder<LocalSymbol>.GetInstance();
            locals.Add(cachedState);
            if ((object)exprRetValue != null) locals.Add(exprRetValue);

            F.CloseMethod(
                F.SequencePoint(
                    body.Syntax,
                    F.Block(
                        locals.ToImmutableAndFree(),
                        newBody)));
        }

        protected override BoundStatement GenerateReturn(bool finished)
        {
            return F.Goto(this.exitLabel);
        }

        #region Visitors

        private enum AwaitableDynamism
        {
            None,
            DynamicTask,
            FullDynamic
        }

        public override BoundNode VisitExpressionStatement(BoundExpressionStatement node)
        {
            if (node.Expression.Kind == BoundKind.AwaitExpression)
            {
                return VisitAwaitExpression((BoundAwaitExpression)node.Expression, resultPlace: null);
            }

            else if (node.Expression.Kind == BoundKind.AssignmentOperator)
            {
                var expression = (BoundAssignmentOperator)node.Expression;
                if (expression.Right.Kind == BoundKind.AwaitExpression)
                {
                    return VisitAwaitExpression((BoundAwaitExpression)expression.Right, resultPlace: expression.Left);
                }
            }

            BoundExpression expr = (BoundExpression)this.Visit(node.Expression);
            return (expr != null) ? node.Update(expr) : (BoundStatement)F.Block();
        }

        public override BoundNode VisitAwaitExpression(BoundAwaitExpression node)
        {
            // await expressions must, by now, have been moved to the top level.
            throw ExceptionUtilities.Unreachable;
        }

        public override BoundNode VisitBadExpression(BoundBadExpression node)
        {
            // Cannot recurse into BadExpression
            return node;
        }

        private BoundBlock VisitAwaitExpression(BoundAwaitExpression node, BoundExpression resultPlace)
        {
            var expression = (BoundExpression)Visit(node.Expression);
            resultPlace = (BoundExpression)Visit(resultPlace);
            MethodSymbol getAwaiter = VisitMethodSymbol(node.GetAwaiter);
            MethodSymbol getResult = VisitMethodSymbol(node.GetResult);
            MethodSymbol isCompletedMethod = ((object)node.IsCompleted != null) ? VisitMethodSymbol(node.IsCompleted.GetMethod) : null;
            TypeSymbol type = VisitType(node.Type);

261
            // The lifespan of awaiter temp doesn't cross sequence points (user code in between awaits), so it doesn't need to be named.
262 263
            TypeSymbol awaiterType = node.IsDynamic ? DynamicTypeSymbol.Instance : getAwaiter.ReturnType;
            var awaiterTemp = F.SynthesizedLocal(awaiterType);
264 265

            var awaitIfIncomplete = F.Block(
266 267
                    // temp $awaiterTemp = <expr>.GetAwaiter();
                    F.Assignment(
268 269
                        F.Local(awaiterTemp),
                        MakeCallMaybeDynamic(expression, getAwaiter, WellKnownMemberNames.GetAwaiter)),
270

271 272
                    // if(!($awaiterTemp.IsCompleted)) { ... }
                    F.If(
273 274
                        condition: F.Not(GenerateGetIsCompleted(awaiterTemp, isCompletedMethod)),
                        thenClause: GenerateAwaitForIncompleteTask(awaiterTemp)));
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289

            BoundExpression getResultCall = MakeCallMaybeDynamic(
                F.Local(awaiterTemp),
                getResult,
                WellKnownMemberNames.GetResult,
                resultsDiscarded: resultPlace == null);

            var nullAwaiter = F.AssignmentExpression(F.Local(awaiterTemp), F.NullOrDefault(awaiterTemp.Type));
            if (resultPlace != null && type.SpecialType != SpecialType.System_Void)
            {
                // $resultTemp = $awaiterTemp.GetResult();
                // $awaiterTemp = null;
                // $resultTemp
                LocalSymbol resultTemp = F.SynthesizedLocal(type);
                return F.Block(
290 291 292 293 294
                    ImmutableArray.Create(awaiterTemp, resultTemp),
                        awaitIfIncomplete,
                        F.Assignment(F.Local(resultTemp), getResultCall),
                        F.ExpressionStatement(nullAwaiter),
                        F.Assignment(resultPlace, F.Local(resultTemp)));
295 296 297 298 299 300
            }
            else
            {
                // $awaiterTemp.GetResult();
                // $awaiterTemp = null;
                return F.Block(
301 302 303 304
                    ImmutableArray.Create(awaiterTemp),
                        awaitIfIncomplete,
                        F.ExpressionStatement(getResultCall),
                        F.ExpressionStatement(nullAwaiter));
305 306 307 308 309 310
            }
        }

        private BoundExpression MakeCallMaybeDynamic(
            BoundExpression receiver,
            MethodSymbol methodSymbol = null,
311
            string methodName = null,
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
            bool resultsDiscarded = false)
        {
            if ((object)methodSymbol != null)
            {
                // non-dynamic:
                Debug.Assert(receiver != null);

                return methodSymbol.IsStatic
                    ? F.StaticCall(methodSymbol.ContainingType, methodSymbol, receiver)
                    : F.Call(receiver, methodSymbol);
            }

            // dynamic:
            Debug.Assert(methodName != null);
            return dynamicFactory.MakeDynamicMemberInvocation(
                methodName,
                receiver,
                typeArguments: ImmutableArray<TypeSymbol>.Empty,
                loweredArguments: ImmutableArray<BoundExpression>.Empty,
331
                argumentNames: ImmutableArray<string>.Empty,
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369
                refKinds: ImmutableArray<RefKind>.Empty,
                hasImplicitReceiver: false,
                resultDiscarded: resultsDiscarded).ToExpression();
        }

        private BoundExpression GenerateGetIsCompleted(LocalSymbol awaiterTemp, MethodSymbol getIsCompletedMethod)
        {
            if (awaiterTemp.Type.IsDynamic())
            {
                return dynamicFactory.MakeDynamicConversion(
                    dynamicFactory.MakeDynamicGetMember(
                        F.Local(awaiterTemp),
                        WellKnownMemberNames.IsCompleted,
                        false).ToExpression(),
                    isExplicit: true,
                    isArrayIndex: false,
                    isChecked: false,
                    resultType: F.SpecialType(SpecialType.System_Boolean)).ToExpression();
            }

            return F.Call(F.Local(awaiterTemp), getIsCompletedMethod);
        }

        private BoundBlock GenerateAwaitForIncompleteTask(LocalSymbol awaiterTemp)
        {
            int stateNumber;
            GeneratedLabelSymbol resumeLabel;
            AddState(out stateNumber, out resumeLabel);

            TypeSymbol awaiterFieldType = awaiterTemp.Type.IsVerifierReference()
                ? F.SpecialType(SpecialType.System_Object)
                : awaiterTemp.Type;

            FieldSymbol awaiterField = GetAwaiterField(awaiterFieldType);

            var blockBuilder = ArrayBuilder<BoundStatement>.GetInstance();

            blockBuilder.Add(
370 371
                    // this.state = cachedState = stateForLabel
                    F.Assignment(F.Field(F.This(), stateField), F.AssignmentExpression(F.Local(cachedState), F.Literal(stateNumber))));
372 373

            blockBuilder.Add(
374 375
                    // Emit await yield point to be injected into PDB
                    F.NoOp(NoOpStatementFlavor.AwaitYieldPoint));
376 377

            blockBuilder.Add(
378 379
                    // this.<>t__awaiter = $awaiterTemp
                    F.Assignment(
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395
                    F.Field(F.This(), awaiterField),
                    (awaiterField.Type == awaiterTemp.Type)
                        ? F.Local(awaiterTemp)
                        : F.Convert(awaiterFieldType, F.Local(awaiterTemp))));

            blockBuilder.Add(awaiterTemp.Type.IsDynamic()
                ? GenerateAwaitOnCompletedDynamic(awaiterTemp)
                : GenerateAwaitOnCompleted(awaiterTemp.Type, awaiterTemp));

            blockBuilder.Add(
                GenerateReturn(false));

            blockBuilder.Add(
                F.Label(resumeLabel));

            blockBuilder.Add(
396 397
                    // Emit await resume point to be injected into PDB
                    F.NoOp(NoOpStatementFlavor.AwaitResumePoint));
398 399

            blockBuilder.Add(
400 401 402
                    // $awaiterTemp = this.<>t__awaiter   or   $awaiterTemp = (AwaiterType)this.<>t__awaiter
                    // $this.<>t__awaiter = null;
                    F.Assignment(
403 404 405 406 407 408 409 410 411
                    F.Local(awaiterTemp),
                    awaiterTemp.Type == awaiterField.Type
                        ? F.Field(F.This(), awaiterField)
                        : F.Convert(awaiterTemp.Type, F.Field(F.This(), awaiterField))));

            blockBuilder.Add(
                F.Assignment(F.Field(F.This(), awaiterField), F.NullOrDefault(awaiterField.Type)));

            blockBuilder.Add(
412 413
                    // this.state = cachedState = NotStartedStateMachine
                    F.Assignment(F.Field(F.This(), stateField), F.AssignmentExpression(F.Local(cachedState), F.Literal(StateMachineStates.NotStartedStateMachine))));
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442

            return F.Block(blockBuilder.ToImmutableAndFree());
        }

        private BoundStatement GenerateAwaitOnCompletedDynamic(LocalSymbol awaiterTemp)
        {
            //  temp $criticalNotifyCompletedTemp = $awaiterTemp as ICriticalNotifyCompletion
            //  if ($criticalNotifyCompletedTemp != null) 
            //  {
            //    this.builder.AwaitUnsafeOnCompleted<ICriticalNotifyCompletion,TSM>(
            //      ref $criticalNotifyCompletedTemp, 
            //      ref this)
            //  } 
            //  else 
            //  {
            //    temp $notifyCompletionTemp = (INotifyCompletion)$awaiterTemp
            //    this.builder.AwaitOnCompleted<INotifyCompletion,TSM>(ref $notifyCompletionTemp, ref this)
            //    free $notifyCompletionTemp
            //  }
            //  free $criticalNotifyCompletedTemp

            var criticalNotifyCompletedTemp = F.SynthesizedLocal(
                F.WellKnownType(WellKnownType.System_Runtime_CompilerServices_ICriticalNotifyCompletion),
                null);

            var notifyCompletionTemp = F.SynthesizedLocal(
                F.WellKnownType(WellKnownType.System_Runtime_CompilerServices_INotifyCompletion),
                null);

443
            LocalSymbol thisTemp = (F.CurrentType.TypeKind == TypeKind.Class) ? F.SynthesizedLocal(F.CurrentType) : null;
444

445 446 447
            var blockBuilder = ArrayBuilder<BoundStatement>.GetInstance();

            blockBuilder.Add(
448 449
                F.Assignment(
                    F.Local(criticalNotifyCompletedTemp),
450 451 452 453 454 455 456
                        // Use reference conversion rather than dynamic conversion:
                        F.As(F.Local(awaiterTemp), criticalNotifyCompletedTemp.Type)));

            if (thisTemp != null)
            {
                blockBuilder.Add(F.Assignment(F.Local(thisTemp), F.This()));
            }
457

458
            blockBuilder.Add(
459 460 461 462 463 464 465
                F.If(
                    condition: F.ObjectEqual(F.Local(criticalNotifyCompletedTemp), F.Null(criticalNotifyCompletedTemp.Type)),

                    thenClause: F.Block(
                        ImmutableArray.Create(notifyCompletionTemp),
                        F.Assignment(
                            F.Local(notifyCompletionTemp),
466 467
                                // Use reference conversion rather than dynamic conversion:
                                F.Convert(notifyCompletionTemp.Type, F.Local(awaiterTemp), ConversionKind.ExplicitReference)),
468 469 470 471 472 473
                        F.ExpressionStatement(
                            F.Call(
                                F.Field(F.This(), asyncMethodBuilderField),
                                asyncMethodBuilderMemberCollection.AwaitOnCompleted.Construct(
                                    notifyCompletionTemp.Type,
                                    F.This().Type),
474
                                F.Local(notifyCompletionTemp), F.This(thisTemp))),
475 476 477 478
                        F.Assignment(
                            F.Local(notifyCompletionTemp),
                            F.NullOrDefault(notifyCompletionTemp.Type))),

479
                    elseClauseOpt: F.Block(
480 481 482 483 484 485
                        F.ExpressionStatement(
                            F.Call(
                                F.Field(F.This(), asyncMethodBuilderField),
                                asyncMethodBuilderMemberCollection.AwaitUnsafeOnCompleted.Construct(
                                    criticalNotifyCompletedTemp.Type,
                                    F.This().Type),
486
                                F.Local(criticalNotifyCompletedTemp), F.This(thisTemp))))));
487

488
            blockBuilder.Add(
489 490 491
                F.Assignment(
                    F.Local(criticalNotifyCompletedTemp),
                    F.NullOrDefault(criticalNotifyCompletedTemp.Type)));
492 493 494 495

            return F.Block(
                SingletonOrPair(criticalNotifyCompletedTemp, thisTemp), 
                blockBuilder.ToImmutableAndFree());
496 497
        }

498
        private BoundStatement GenerateAwaitOnCompleted(TypeSymbol loweredAwaiterType, LocalSymbol awaiterTemp)
499 500 501 502 503
        {
            // this.builder.AwaitOnCompleted<TAwaiter,TSM>(ref $awaiterTemp, ref this)
            //    or
            // this.builder.AwaitOnCompleted<TAwaiter,TSM>(ref $awaiterArrayTemp[0], ref this)

504
            LocalSymbol thisTemp = (F.CurrentType.TypeKind == TypeKind.Class) ? F.SynthesizedLocal(F.CurrentType) : null;
505

506 507 508 509 510
            HashSet<DiagnosticInfo> useSiteDiagnostics = null;
            var useUnsafeOnCompleted = F.Compilation.Conversions.ClassifyImplicitConversion(
                loweredAwaiterType,
                F.Compilation.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_ICriticalNotifyCompletion),
                ref useSiteDiagnostics).IsImplicit;
511

512 513 514
            var onCompleted = (useUnsafeOnCompleted ?
                asyncMethodBuilderMemberCollection.AwaitUnsafeOnCompleted :
                asyncMethodBuilderMemberCollection.AwaitOnCompleted).Construct(loweredAwaiterType, F.This().Type);
515 516

            BoundExpression result = 
517 518 519
                F.Call(
                    F.Field(F.This(), asyncMethodBuilderField),
                    onCompleted,
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
                    F.Local(awaiterTemp), F.This(thisTemp));

            if (thisTemp != null)
            {
                result = F.Sequence(
                    ImmutableArray.Create(thisTemp), 
                    ImmutableArray.Create<BoundExpression>(F.AssignmentExpression(F.Local(thisTemp), F.This())), 
                    result); 
            }

            return F.ExpressionStatement(result);
        }

        private static ImmutableArray<LocalSymbol> SingletonOrPair(LocalSymbol first, LocalSymbol secondOpt)
        {
            return (secondOpt == null) ? ImmutableArray.Create(first) : ImmutableArray.Create(first, secondOpt);
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
        }

        public override BoundNode VisitReturnStatement(BoundReturnStatement node)
        {
            if (node.ExpressionOpt != null)
            {
                Debug.Assert(method.IsGenericTaskReturningAsync(F.Compilation));
                return F.Block(
                    F.Assignment(F.Local(exprRetValue), (BoundExpression)Visit(node.ExpressionOpt)),
                    F.Goto(exprReturnLabel));
            }

            return F.Goto(exprReturnLabel);
        }

        #endregion Visitors
    }
553
}