EmitExpression.cs 133.2 KB
Newer Older
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
P
Pilchie 已提交
2

3
using System;
P
Pilchie 已提交
4 5
using System.Collections.Immutable;
using System.Diagnostics;
T
Tomas Matousek 已提交
6
using System.Reflection.Metadata;
P
Pilchie 已提交
7 8
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
9
using Microsoft.CodeAnalysis.PooledObjects;
P
Pilchie 已提交
10 11 12 13
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp.CodeGen
{
14
    internal partial class CodeGenerator
P
Pilchie 已提交
15
    {
16 17 18 19 20
        private int _recursionDepth;

        private class EmitCancelledException : Exception
        { }

21 22 23 24 25 26 27
        private enum UseKind
        {
            Unused,
            UsedAsValue,
            UsedAsAddress
        }

P
Pilchie 已提交
28 29 30 31 32 33 34 35 36 37 38 39
        private void EmitExpression(BoundExpression expression, bool used)
        {
            if (expression == null)
            {
                return;
            }

            var constantValue = expression.ConstantValue;
            if (constantValue != null)
            {
                if (!used)
                {
40
                    // unused constants have no side-effects.
P
Pilchie 已提交
41 42 43 44 45 46 47 48 49 50
                    return;
                }

                if ((object)expression.Type == null || expression.Type.SpecialType != SpecialType.System_Decimal)
                {
                    EmitConstantExpression(expression.Type, constantValue, used, expression.Syntax);
                    return;
                }
            }

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
            _recursionDepth++;

            if (_recursionDepth > 1)
            {
                StackGuard.EnsureSufficientExecutionStack(_recursionDepth);

                EmitExpressionCore(expression, used);
            }
            else
            {
                EmitExpressionCoreWithStackGuard(expression, used);
            }

            _recursionDepth--;
        }

        private void EmitExpressionCoreWithStackGuard(BoundExpression expression, bool used)
        {
            Debug.Assert(_recursionDepth == 1);

            try
            {
                EmitExpressionCore(expression, used);
                Debug.Assert(_recursionDepth == 1);
            }
            catch (Exception ex) when (StackGuard.IsInsufficientExecutionStackException(ex))
            {
C
CyrusNajmabadi 已提交
78
                _diagnostics.Add(ErrorCode.ERR_InsufficientStack,
79 80 81 82 83 84 85
                                 BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(expression));
                throw new EmitCancelledException();
            }
        }

        private void EmitExpressionCore(BoundExpression expression, bool used)
        {
P
Pilchie 已提交
86 87 88
            switch (expression.Kind)
            {
                case BoundKind.AssignmentOperator:
89
                    EmitAssignmentExpression((BoundAssignmentOperator)expression, used ? UseKind.UsedAsValue : UseKind.Unused);
P
Pilchie 已提交
90 91 92
                    break;

                case BoundKind.Call:
93
                    EmitCallExpression((BoundCall)expression, used ? UseKind.UsedAsValue : UseKind.Unused);
P
Pilchie 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107
                    break;

                case BoundKind.ObjectCreationExpression:
                    EmitObjectCreationExpression((BoundObjectCreationExpression)expression, used);
                    break;

                case BoundKind.DelegateCreationExpression:
                    EmitDelegateCreationExpression((BoundDelegateCreationExpression)expression, used);
                    break;

                case BoundKind.ArrayCreation:
                    EmitArrayCreationExpression((BoundArrayCreation)expression, used);
                    break;

108 109
                case BoundKind.ConvertedStackAllocExpression:
                    EmitConvertedStackAllocExpression((BoundConvertedStackAllocExpression)expression, used);
P
Pilchie 已提交
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
                    break;

                case BoundKind.Conversion:
                    EmitConversionExpression((BoundConversion)expression, used);
                    break;

                case BoundKind.Local:
                    EmitLocalLoad((BoundLocal)expression, used);
                    break;

                case BoundKind.Dup:
                    EmitDupExpression((BoundDup)expression, used);
                    break;

                case BoundKind.Parameter:
125
                    if (used)  // unused parameter has no side-effects
P
Pilchie 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
                    {
                        EmitParameterLoad((BoundParameter)expression);
                    }
                    break;

                case BoundKind.FieldAccess:
                    EmitFieldLoad((BoundFieldAccess)expression, used);
                    break;

                case BoundKind.ArrayAccess:
                    EmitArrayElementLoad((BoundArrayAccess)expression, used);
                    break;

                case BoundKind.ArrayLength:
                    EmitArrayLength((BoundArrayLength)expression, used);
                    break;

                case BoundKind.ThisReference:
144
                    if (used) // unused this has no side-effects
P
Pilchie 已提交
145 146 147 148 149 150 151 152 153 154
                    {
                        EmitThisReferenceExpression((BoundThisReference)expression);
                    }
                    break;

                case BoundKind.PreviousSubmissionReference:
                    // Script references are lowered to a this reference and a field access.
                    throw ExceptionUtilities.UnexpectedValue(expression.Kind);

                case BoundKind.BaseReference:
155
                    if (used) // unused base has no side-effects
P
Pilchie 已提交
156
                    {
157 158
                        var thisType = _method.ContainingType;
                        _builder.EmitOpCode(ILOpCode.Ldarg_0);
P
Pilchie 已提交
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
                        if (thisType.IsValueType)
                        {
                            EmitLoadIndirect(thisType, expression.Syntax);
                            EmitBox(thisType, expression.Syntax);
                        }
                    }
                    break;

                case BoundKind.Sequence:
                    EmitSequenceExpression((BoundSequence)expression, used);
                    break;

                case BoundKind.SequencePointExpression:
                    EmitSequencePointExpression((BoundSequencePointExpression)expression, used);
                    break;

                case BoundKind.UnaryOperator:
                    EmitUnaryOperatorExpression((BoundUnaryOperator)expression, used);
                    break;

                case BoundKind.BinaryOperator:
                    EmitBinaryOperatorExpression((BoundBinaryOperator)expression, used);
                    break;

                case BoundKind.NullCoalescingOperator:
                    EmitNullCoalescingOperator((BoundNullCoalescingOperator)expression, used);
                    break;

                case BoundKind.IsOperator:
                    EmitIsExpression((BoundIsOperator)expression, used);
                    break;

                case BoundKind.AsOperator:
                    EmitAsExpression((BoundAsOperator)expression, used);
                    break;

195 196
                case BoundKind.DefaultExpression:
                    EmitDefaultExpression((BoundDefaultExpression)expression, used);
P
Pilchie 已提交
197 198 199
                    break;

                case BoundKind.TypeOfOperator:
200
                    if (used) // unused typeof has no side-effects
P
Pilchie 已提交
201 202 203 204 205 206
                    {
                        EmitTypeOfExpression((BoundTypeOfOperator)expression);
                    }
                    break;

                case BoundKind.SizeOfOperator:
207
                    if (used) // unused sizeof has no side-effects
P
Pilchie 已提交
208 209 210 211 212
                    {
                        EmitSizeOfExpression((BoundSizeOfOperator)expression);
                    }
                    break;

213
                case BoundKind.ModuleVersionId:
J
John Hamby 已提交
214 215
                    Debug.Assert(used);
                    EmitModuleVersionIdLoad((BoundModuleVersionId)expression);
216 217
                    break;

J
More.  
John Hamby 已提交
218 219 220 221 222
                case BoundKind.ModuleVersionIdString:
                    Debug.Assert(used);
                    EmitModuleVersionIdStringLoad((BoundModuleVersionIdString)expression);
                    break;

J
John Hamby 已提交
223
                case BoundKind.InstrumentationPayloadRoot:
J
John Hamby 已提交
224
                    Debug.Assert(used);
J
John Hamby 已提交
225
                    EmitInstrumentationPayloadRootLoad((BoundInstrumentationPayloadRoot)expression);
J
John Hamby 已提交
226 227
                    break;

J
John Hamby 已提交
228 229 230
                case BoundKind.MethodDefIndex:
                    Debug.Assert(used);
                    EmitMethodDefIndexExpression((BoundMethodDefIndex)expression);
J
More  
John Hamby 已提交
231 232
                    break;

J
John Hamby 已提交
233
                case BoundKind.MaximumMethodDefIndex:
J
John Hamby 已提交
234
                    Debug.Assert(used);
J
John Hamby 已提交
235
                    EmitMaximumMethodDefIndexExpression((BoundMaximumMethodDefIndex)expression);
J
John Hamby 已提交
236 237
                    break;

238 239 240 241 242
                case BoundKind.SourceDocumentIndex:
                    Debug.Assert(used);
                    EmitSourceDocumentIndex((BoundSourceDocumentIndex)expression);
                    break;

P
Pilchie 已提交
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
                case BoundKind.MethodInfo:
                    if (used)
                    {
                        EmitMethodInfoExpression((BoundMethodInfo)expression);
                    }
                    break;

                case BoundKind.FieldInfo:
                    if (used)
                    {
                        EmitFieldInfoExpression((BoundFieldInfo)expression);
                    }
                    break;

                case BoundKind.ConditionalOperator:
                    EmitConditionalOperator((BoundConditionalOperator)expression, used);
                    break;

                case BoundKind.AddressOfOperator:
                    EmitAddressOfExpression((BoundAddressOfOperator)expression, used);
                    break;

                case BoundKind.PointerIndirectionOperator:
                    EmitPointerIndirectionOperator((BoundPointerIndirectionOperator)expression, used);
                    break;

                case BoundKind.ArgList:
                    EmitArgList(used);
                    break;

                case BoundKind.ArgListOperator:
                    Debug.Assert(used);
                    EmitArgListOperator((BoundArgListOperator)expression);
                    break;

                case BoundKind.RefTypeOperator:
                    EmitRefTypeOperator((BoundRefTypeOperator)expression, used);
                    break;

                case BoundKind.MakeRefOperator:
                    EmitMakeRefOperator((BoundMakeRefOperator)expression, used);
                    break;

                case BoundKind.RefValueOperator:
                    EmitRefValueOperator((BoundRefValueOperator)expression, used);
                    break;

290 291
                case BoundKind.LoweredConditionalAccess:
                    EmitLoweredConditionalAccessExpression((BoundLoweredConditionalAccess)expression, used);
292 293 294 295 296 297
                    break;

                case BoundKind.ConditionalReceiver:
                    EmitConditionalReceiver((BoundConditionalReceiver)expression, used);
                    break;

298 299 300 301
                case BoundKind.ComplexConditionalReceiver:
                    EmitComplexConditionalReceiver((BoundComplexConditionalReceiver)expression, used);
                    break;

302 303 304 305
                case BoundKind.PseudoVariable:
                    EmitPseudoVariableValue((BoundPseudoVariable)expression, used);
                    break;

306 307 308 309
                case BoundKind.ThrowExpression:
                    EmitThrowExpression((BoundThrowExpression)expression, used);
                    break;

P
Pilchie 已提交
310 311 312 313 314 315 316 317 318
                default:
                    // Code gen should not be invoked if there are errors.
                    Debug.Assert(expression.Kind != BoundKind.BadExpression);

                    // node should have been lowered:
                    throw ExceptionUtilities.UnexpectedValue(expression.Kind);
            }
        }

319 320
        private void EmitThrowExpression(BoundThrowExpression node, bool used)
        {
321
            this.EmitThrow(node.Expression);
322 323 324 325 326

            // to satisfy invariants, we push a default value to pretend to adjust the stack height
            EmitDefaultValue(node.Type, used, node.Syntax);
        }

327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
        private void EmitComplexConditionalReceiver(BoundComplexConditionalReceiver expression, bool used)
        {
            Debug.Assert(!expression.Type.IsReferenceType);
            Debug.Assert(!expression.Type.IsValueType);

            var receiverType = expression.Type;

            var whenValueTypeLabel = new object();
            var doneLabel = new object();

            EmitInitObj(receiverType, true, expression.Syntax);
            EmitBox(receiverType, expression.Syntax);
            _builder.EmitBranch(ILOpCode.Brtrue, whenValueTypeLabel);

            EmitExpression(expression.ReferenceTypeReceiver, used);
            _builder.EmitBranch(ILOpCode.Br, doneLabel);
            _builder.AdjustStack(-1);

            _builder.MarkLabel(whenValueTypeLabel);
            EmitExpression(expression.ValueTypeReceiver, used);

            _builder.MarkLabel(doneLabel);
        }

351
        private void EmitLoweredConditionalAccessExpression(BoundLoweredConditionalAccess expression, bool used)
352 353 354
        {
            var receiver = expression.Receiver;

355
            var receiverType = receiver.Type;
356
            LocalDefinition receiverTemp = null;
J
Jared Parsons 已提交
357
            Debug.Assert(!receiverType.IsValueType ||
V
VSadov 已提交
358
                (receiverType.IsNullableType() && expression.HasValueMethodOpt != null), "conditional receiver cannot be a struct");
359 360 361 362

            var receiverConstant = receiver.ConstantValue;
            if (receiverConstant != null)
            {
363 364 365
                // const but not default, must be a reference type
                Debug.Assert(receiverType.IsVerifierReference());
                // receiver is a reference type, so addresskind does not matter, but we do not intend to write.
V
vsadov 已提交
366
                receiverTemp = EmitReceiverRef(receiver, AddressKind.ReadOnly);
367
                EmitExpression(expression.WhenNotNull, used);
368 369 370 371
                if (receiverTemp != null)
                {
                    FreeTemp(receiverTemp);
                }
372 373 374
                return;
            }

375 376 377
            // labels
            object whenNotNullLabel = new object();
            object doneLabel = new object();
V
VSadov 已提交
378
            LocalDefinition cloneTemp = null;
379

380
            var notConstrained = !receiverType.IsReferenceType && !receiverType.IsValueType;
381

382
            // we need a copy if we deal with nonlocal value (to capture the value)
383
            // or if we have a ref-constrained T (to do box just once) 
384
            // or if we deal with stack local (reads are destructive)
385
            // or if we have default(T) (to do box just once)
386
            var nullCheckOnCopy = LocalRewriter.CanChangeValueBetweenReads(receiver, localsMayBeAssignedOrCaptured: false) ||
387
                                   (receiverType.IsReferenceType && receiverType.TypeKind == TypeKind.TypeParameter) ||
V
rebased  
vsadov 已提交
388
                                   (receiver.Kind == BoundKind.Local && IsStackLocal(((BoundLocal)receiver).LocalSymbol));
V
VSadov 已提交
389 390

            // ===== RECEIVER
391 392
            if (nullCheckOnCopy)
            {
393
                if (notConstrained)
394
                {
395 396 397
                    // if T happens to be a value type, it could be a target of mutating calls.
                    receiverTemp = EmitReceiverRef(receiver, AddressKind.Constrained);

398 399
                    // unconstrained case needs to handle case where T is actually a struct.
                    // such values are never nulls
C
Charles Stoner 已提交
400
                    // we will emit a check for such case, but the check is really a JIT-time 
401 402 403 404 405 406 407 408 409 410 411 412 413
                    // constant since JIT will know if T is a struct or not.

                    // if ((object)default(T) != null) 
                    // {
                    //     goto whenNotNull
                    // }
                    // else
                    // {
                    //     temp = receiverRef
                    //     receiverRef = ref temp
                    // }
                    EmitDefaultValue(receiverType, true, receiver.Syntax);
                    EmitBox(receiverType, receiver.Syntax);
414
                    _builder.EmitBranch(ILOpCode.Brtrue, whenNotNullLabel);
415 416
                    EmitLoadIndirect(receiverType, receiver.Syntax);

V
VSadov 已提交
417 418 419 420
                    cloneTemp = AllocateTemp(receiverType, receiver.Syntax);
                    _builder.EmitLocalStore(cloneTemp);
                    _builder.EmitLocalAddress(cloneTemp);
                    _builder.EmitLocalLoad(cloneTemp);
421 422 423 424 425 426
                    EmitBox(receiver.Type, receiver.Syntax);

                    // here we have loaded a ref to a temp and its boxed value { &T, O }
                }
                else
                {
V
vsadov 已提交
427 428
                    // this does not need to be writeable
                    // we may call "HasValue" on this, but it is not mutating 
429
                    var addressKind = AddressKind.ReadOnly;
V
vsadov 已提交
430 431

                    receiverTemp = EmitReceiverRef(receiver, addressKind);
432
                    _builder.EmitOpCode(ILOpCode.Dup);
V
VSadov 已提交
433
                    // here we have loaded two copies of a reference   { O, O }  or  {&nub, &nub}
434 435 436
                }
            }
            else
437
            {
438 439 440 441 442
                // this does not need to be writeable.
                // we may call "HasValue" on this, but it is not mutating
                // besides, since we are not making a copy, the receiver is not a field, 
                // so it cannot be readonly, in verifier sense, anyways.
                receiverTemp = EmitReceiverRef(receiver, AddressKind.ReadOnly);
V
VSadov 已提交
443 444 445 446 447 448 449 450 451 452 453 454
                // here we have loaded just { O } or  {&nub}
                // we have the most trivial case where we can just reload receiver when needed again
            }

            // ===== CONDITION

            var hasValueOpt = expression.HasValueMethodOpt;
            if (hasValueOpt != null)
            {
                Debug.Assert(receiver.Type.IsNullableType());
                _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0);
                EmitSymbolToken(hasValueOpt, expression.Syntax, null);
455 456
            }

457
            _builder.EmitBranch(ILOpCode.Brtrue, whenNotNullLabel);
458

V
VSadov 已提交
459 460 461 462 463 464 465 466
            // no longer need the temp if we are not holding a copy
            if (receiverTemp != null && !nullCheckOnCopy)
            {
                FreeTemp(receiverTemp);
                receiverTemp = null;
            }

            // ===== WHEN NULL
467 468
            if (nullCheckOnCopy)
            {
469
                _builder.EmitOpCode(ILOpCode.Pop);
470
            }
471

472 473 474 475 476 477 478 479 480 481
            var whenNull = expression.WhenNullOpt;
            if (whenNull == null)
            {
                EmitDefaultValue(expression.Type, used, expression.Syntax);
            }
            else
            {
                EmitExpression(whenNull, used);
            }

482
            _builder.EmitBranch(ILOpCode.Br, doneLabel);
483

V
VSadov 已提交
484 485

            // ===== WHEN NOT NULL 
486
            if (nullCheckOnCopy)
487
            {
488 489 490
                // notNull branch pops copy of receiver off the stack when nullCheckOnCopy
                // however on the isNull branch we still have the stack as it was and need 
                // to adjust stack depth correspondingly.
491
                _builder.AdjustStack(+1);
492
            }
493 494 495 496 497 498

            if (used)
            {
                // notNull branch pushes default on the stack when used
                // however on the isNull branch we still have the stack as it was and need 
                // to adjust stack depth correspondingly.
499
                _builder.AdjustStack(-1);
500 501
            }

502
            _builder.MarkLabel(whenNotNullLabel);
503 504 505

            if (!nullCheckOnCopy)
            {
V
VSadov 已提交
506
                Debug.Assert(receiverTemp == null);
507 508
                // receiver may be used as target of a struct call (if T happens to be a sruct)
                receiverTemp = EmitReceiverRef(receiver, AddressKind.Constrained);
V
rebased  
vsadov 已提交
509
                Debug.Assert(receiverTemp == null || receiver.IsDefaultValue());
510 511
            }

512
            EmitExpression(expression.WhenNotNull, used);
V
VSadov 已提交
513 514

            // ===== DONE
515
            _builder.MarkLabel(doneLabel);
516

V
VSadov 已提交
517
            if (cloneTemp != null)
518
            {
V
VSadov 已提交
519
                FreeTemp(cloneTemp);
520
            }
521 522 523 524 525

            if (receiverTemp != null)
            {
                FreeTemp(receiverTemp);
            }
526 527 528 529
        }

        private void EmitConditionalReceiver(BoundConditionalReceiver expression, bool used)
        {
530 531 532 533 534 535 536
            Debug.Assert(!expression.Type.IsValueType);

            if (!expression.Type.IsReferenceType)
            {
                EmitLoadIndirect(expression.Type, expression.Syntax);
            }

537 538 539
            EmitPopIfUnused(used);
        }

P
Pilchie 已提交
540 541 542 543 544 545 546 547 548 549 550 551
        private void EmitRefValueOperator(BoundRefValueOperator expression, bool used)
        {
            EmitRefValueAddress(expression);
            EmitLoadIndirect(expression.Type, expression.Syntax);
            EmitPopIfUnused(used);
        }

        private void EmitMakeRefOperator(BoundMakeRefOperator expression, bool used)
        {
            // push address of variable
            // mkrefany [Type] -- takes address off stack, puts TypedReference on stack

552 553 554
            var temp = EmitAddress(expression.Operand, AddressKind.Writeable);
            Debug.Assert(temp == null, "makeref should not create temps");

555
            _builder.EmitOpCode(ILOpCode.Mkrefany);
P
Pilchie 已提交
556 557 558 559 560 561 562 563 564 565 566
            EmitSymbolToken(expression.Operand.Type, expression.Operand.Syntax);
            EmitPopIfUnused(used);
        }

        private void EmitRefTypeOperator(BoundRefTypeOperator expression, bool used)
        {
            // push TypedReference
            // refanytype -- takes TypedReference off stack, puts token on stack
            // call GetTypeFromHandle -- takes token off stack, puts Type on stack

            EmitExpression(expression.Operand, true);
567 568
            _builder.EmitOpCode(ILOpCode.Refanytype);
            _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0);
P
Pilchie 已提交
569 570 571 572 573 574 575 576
            var getTypeMethod = expression.GetTypeFromHandle;
            Debug.Assert((object)getTypeMethod != null);
            EmitSymbolToken(getTypeMethod, expression.Syntax, null);
            EmitPopIfUnused(used);
        }

        private void EmitArgList(bool used)
        {
577
            _builder.EmitOpCode(ILOpCode.Arglist);
P
Pilchie 已提交
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
            EmitPopIfUnused(used);
        }

        private void EmitArgListOperator(BoundArgListOperator expression)
        {
            for (int i = 0; i < expression.Arguments.Length; i++)
            {
                BoundExpression argument = expression.Arguments[i];
                RefKind refKind = expression.ArgumentRefKindsOpt.IsDefaultOrEmpty ? RefKind.None : expression.ArgumentRefKindsOpt[i];
                EmitArgument(argument, refKind);
            }
        }

        private void EmitArgument(BoundExpression argument, RefKind refKind)
        {
593
            switch (refKind)
P
Pilchie 已提交
594
            {
V
vsadov 已提交
595 596 597
                case RefKind.None:
                    EmitExpression(argument, true);
                    break;
598

599
                case RefKind.In:
V
vsadov 已提交
600
                    var temp = EmitAddress(argument, AddressKind.ReadOnly);
V
vsadov 已提交
601
                    AddExpressionTemp(temp);
V
vsadov 已提交
602 603 604
                    break;

                default:
605 606 607
                    // NOTE: passing "ReadOnlyStrict" here. 
                    //       we should not get an address of a copy if at all possible
                    var unexpectedTemp = EmitAddress(argument, refKind == RefKindExtensions.StrictIn? AddressKind.ReadOnlyStrict: AddressKind.Writeable);
V
vsadov 已提交
608 609 610 611 612 613 614
                    if (unexpectedTemp != null)
                    {
                        // interestingly enough "ref dynamic" sometimes is passed via a clone
                        Debug.Assert(argument.Type.IsDynamic(), "passing args byref should not clone them into temps");
                        AddExpressionTemp(unexpectedTemp);
                    }

V
vsadov 已提交
615
                    break;
P
Pilchie 已提交
616 617 618 619 620
            }
        }

        private void EmitAddressOfExpression(BoundAddressOfOperator expression, bool used)
        {
621 622 623
            // NOTE: passing "ReadOnlyStrict" here. 
            //       we should not get an address of a copy if at all possible
            var temp = EmitAddress(expression.Operand, AddressKind.ReadOnlyStrict);
P
Pilchie 已提交
624
            Debug.Assert(temp == null, "If the operand is addressable, then a temp shouldn't be required.");
625

626
            if (used)
P
Pilchie 已提交
627 628 629 630 631 632 633
            {
                // When computing an address to be used to initialize a fixed-statement variable, we have to be careful
                // not to convert the managed reference to an unmanaged pointer before storing it.  Otherwise the GC might
                // come along and move memory around, invalidating the pointer before it is pinned by being stored in
                // the fixed variable.  But elsewhere in the code we do use a conv.u instruction to convert the managed
                // reference to the underlying type for unmanaged pointers, which is the type "unsigned int" (see CLI
                // standard, Partition I section 12.1.1.1).
634
                _builder.EmitOpCode(ILOpCode.Conv_u);
P
Pilchie 已提交
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653
            }

            EmitPopIfUnused(used);
        }

        private void EmitPointerIndirectionOperator(BoundPointerIndirectionOperator expression, bool used)
        {
            EmitExpression(expression.Operand, used: true);
            EmitLoadIndirect(expression.Type, expression.Syntax);
            EmitPopIfUnused(used);
        }

        private void EmitDupExpression(BoundDup expression, bool used)
        {
            if (expression.RefKind == RefKind.None)
            {
                // unused dup is noop
                if (used)
                {
654
                    _builder.EmitOpCode(ILOpCode.Dup);
P
Pilchie 已提交
655 656 657 658
                }
            }
            else
            {
659
                _builder.EmitOpCode(ILOpCode.Dup);
P
Pilchie 已提交
660 661 662 663 664 665 666 667 668

                // must read in case if it is a null ref
                EmitLoadIndirect(expression.Type, expression.Syntax);
                EmitPopIfUnused(used);
            }
        }

        private void EmitDelegateCreationExpression(BoundDelegateCreationExpression expression, bool used)
        {
669 670
            var mg = expression.Argument as BoundMethodGroup;
            var receiver = mg != null ? mg.ReceiverOpt : expression.Argument;
671
            var meth = expression.MethodOpt ?? receiver.Type.DelegateInvokeMethod();
P
Pilchie 已提交
672 673 674 675 676 677 678 679 680
            Debug.Assert((object)meth != null);
            EmitDelegateCreation(expression, receiver, expression.IsExtensionMethod, meth, expression.Type, used);
        }

        private void EmitThisReferenceExpression(BoundThisReference thisRef)
        {
            var thisType = thisRef.Type;
            Debug.Assert(thisType.TypeKind != TypeKind.TypeParameter);

681
            _builder.EmitOpCode(ILOpCode.Ldarg_0);
P
Pilchie 已提交
682 683 684 685 686 687
            if (thisType.IsValueType)
            {
                EmitLoadIndirect(thisType, thisRef.Syntax);
            }
        }

688 689
        private void EmitPseudoVariableValue(BoundPseudoVariable expression, bool used)
        {
690
            EmitExpression(expression.EmitExpressions.GetValue(expression, _diagnostics), used);
691 692
        }

P
Pilchie 已提交
693
        private void EmitSequencePointExpression(BoundSequencePointExpression node, bool used)
694 695 696 697 698 699 700 701 702
        {
            EmitSequencePoint(node);

            // used is true to ensure that something is emitted
            EmitExpression(node.Expression, used: true);
            EmitPopIfUnused(used);
        }

        private void EmitSequencePoint(BoundSequencePointExpression node)
P
Pilchie 已提交
703 704
        {
            var syntax = node.Syntax;
705
            if (_emitPdbSequencePoints)
P
Pilchie 已提交
706 707 708 709 710 711 712
            {
                if (syntax == null)
                {
                    EmitHiddenSequencePoint();
                }
                else
                {
713
                    EmitSequencePoint(syntax);
P
Pilchie 已提交
714 715 716 717 718 719
                }
            }
        }

        private void EmitSequenceExpression(BoundSequence sequence, bool used)
        {
720
            DefineLocals(sequence);
P
Pilchie 已提交
721 722 723 724 725 726 727 728 729 730 731 732 733 734
            EmitSideEffects(sequence);

            // CONSIDER:    LocalRewriter.RewriteNestedObjectOrCollectionInitializerExpression may create a bound sequence with an unused BoundTypeExpression as the value,
            // CONSIDER:    which must be ignored by codegen. See comments in RewriteNestedObjectOrCollectionInitializerExpression for details and an example.
            // CONSIDER:    We may want to instead consider making the Value field of BoundSequence node optional to allow a sequence with
            // CONSIDER:    only side effects and no value. Note that VB's BoundSequence node has an optional value field.
            // CONSIDER:    This will allow us to remove the below check before emitting the value.

            Debug.Assert(sequence.Value.Kind != BoundKind.TypeExpression || !used);
            if (sequence.Value.Kind != BoundKind.TypeExpression)
            {
                EmitExpression(sequence.Value, used);
            }

735
            // sequence is used as a value, can release all locals
736
            FreeLocals(sequence);
737 738 739 740 741
        }

        private void DefineLocals(BoundSequence sequence)
        {
            if (sequence.Locals.IsEmpty)
P
Pilchie 已提交
742
            {
743 744
                return;
            }
P
Pilchie 已提交
745

746
            _builder.OpenLocalScope();
747 748 749 750 751 752 753

            foreach (var local in sequence.Locals)
            {
                DefineLocal(local, sequence.Syntax);
            }
        }

754
        private void FreeLocals(BoundSequence sequence)
755 756 757 758 759 760
        {
            if (sequence.Locals.IsEmpty)
            {
                return;
            }

761
            _builder.CloseLocalScope();
762 763 764

            foreach (var local in sequence.Locals)
            {
765 766 767 768 769 770
                FreeLocal(local);
            }
        }

        /// <summary>
        /// Defines sequence locals and record them so tht they could be retained for the duration of the encompassing expresson
V
vsadov 已提交
771
        /// Use this when taking a reference of the sequence, which can indirectly refer to any of its locals.
772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
        /// </summary>
        private void DefineAndRecordLocals(BoundSequence sequence)
        {
            if (sequence.Locals.IsEmpty)
            {
                return;
            }

            _builder.OpenLocalScope();

            foreach (var local in sequence.Locals)
            {
                var seqLocal = DefineLocal(local, sequence.Syntax);
                AddExpressionTemp(seqLocal);
            }
        }

        /// <summary>
        /// Closes the visibility/debug scopes for the sequence locals, but keep the local slots from reuse
        /// for the duration of the encompassing expresson.
        /// Use this paired with DefineAndRecordLocals when taking a reference of the sequence, which can indirectly refer to any of its locals.
        /// </summary>
        private void CloseScopeAndKeepLocals(BoundSequence sequence)
        {
            if (sequence.Locals.IsEmpty)
            {
                return;
P
Pilchie 已提交
799
            }
800 801

            _builder.CloseLocalScope();
P
Pilchie 已提交
802 803 804 805 806 807 808 809 810 811 812 813 814 815
        }

        private void EmitSideEffects(BoundSequence sequence)
        {
            var sideEffects = sequence.SideEffects;
            if (!sideEffects.IsDefaultOrEmpty)
            {
                foreach (var se in sideEffects)
                {
                    EmitExpression(se, false);
                }
            }
        }

816
        private void EmitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<RefKind> refKindsOpt)
P
Pilchie 已提交
817 818 819 820 821
        {
            // We might have an extra argument for the __arglist() of a varargs method.
            Debug.Assert(arguments.Length == parameters.Length || arguments.Length == parameters.Length + 1, "argument count must match parameter count");
            for (int i = 0; i < arguments.Length; i++)
            {
822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841
                RefKind refKind;

                if (!refKindsOpt.IsDefault && i < refKindsOpt.Length)
                {
                    // if we have an explicit refKind for the given argument, use that
                    refKind = refKindsOpt[i];
                }
                else if (i < parameters.Length)
                {
                    // otherwise check the parameter
                    refKind = parameters[i].RefKind;
                }
                else
                {
                    // vararg case
                    Debug.Assert(arguments[i].Kind == BoundKind.ArgListOperator);
                    refKind = RefKind.None;
                }

                EmitArgument(arguments[i], refKind);
P
Pilchie 已提交
842 843 844 845 846 847 848 849
            }
        }

        private void EmitArrayElementLoad(BoundArrayAccess arrayAccess, bool used)
        {
            EmitExpression(arrayAccess.Expression, used: true);
            EmitArrayIndices(arrayAccess.Indices);

850
            if (((ArrayTypeSymbol)arrayAccess.Expression.Type).IsSZArray)
P
Pilchie 已提交
851 852 853 854 855 856 857 858 859 860 861
            {
                var elementType = arrayAccess.Type;
                if (elementType.IsEnumType())
                {
                    //underlying primitives do not need type tokens.
                    elementType = ((NamedTypeSymbol)elementType).EnumUnderlyingType;
                }

                switch (elementType.PrimitiveTypeCode)
                {
                    case Microsoft.Cci.PrimitiveTypeCode.Int8:
862
                        _builder.EmitOpCode(ILOpCode.Ldelem_i1);
P
Pilchie 已提交
863 864
                        break;

865
                    case Microsoft.Cci.PrimitiveTypeCode.Boolean:
P
Pilchie 已提交
866
                    case Microsoft.Cci.PrimitiveTypeCode.UInt8:
867
                        _builder.EmitOpCode(ILOpCode.Ldelem_u1);
P
Pilchie 已提交
868 869 870
                        break;

                    case Microsoft.Cci.PrimitiveTypeCode.Int16:
871
                        _builder.EmitOpCode(ILOpCode.Ldelem_i2);
P
Pilchie 已提交
872 873 874 875
                        break;

                    case Microsoft.Cci.PrimitiveTypeCode.Char:
                    case Microsoft.Cci.PrimitiveTypeCode.UInt16:
876
                        _builder.EmitOpCode(ILOpCode.Ldelem_u2);
P
Pilchie 已提交
877 878 879
                        break;

                    case Microsoft.Cci.PrimitiveTypeCode.Int32:
880
                        _builder.EmitOpCode(ILOpCode.Ldelem_i4);
P
Pilchie 已提交
881 882 883
                        break;

                    case Microsoft.Cci.PrimitiveTypeCode.UInt32:
884
                        _builder.EmitOpCode(ILOpCode.Ldelem_u4);
P
Pilchie 已提交
885 886 887 888
                        break;

                    case Microsoft.Cci.PrimitiveTypeCode.Int64:
                    case Microsoft.Cci.PrimitiveTypeCode.UInt64:
889
                        _builder.EmitOpCode(ILOpCode.Ldelem_i8);
P
Pilchie 已提交
890 891 892 893 894
                        break;

                    case Microsoft.Cci.PrimitiveTypeCode.IntPtr:
                    case Microsoft.Cci.PrimitiveTypeCode.UIntPtr:
                    case Microsoft.Cci.PrimitiveTypeCode.Pointer:
895
                        _builder.EmitOpCode(ILOpCode.Ldelem_i);
P
Pilchie 已提交
896 897 898
                        break;

                    case Microsoft.Cci.PrimitiveTypeCode.Float32:
899
                        _builder.EmitOpCode(ILOpCode.Ldelem_r4);
P
Pilchie 已提交
900 901 902
                        break;

                    case Microsoft.Cci.PrimitiveTypeCode.Float64:
903
                        _builder.EmitOpCode(ILOpCode.Ldelem_r8);
P
Pilchie 已提交
904 905 906 907 908
                        break;

                    default:
                        if (elementType.IsVerifierReference())
                        {
909
                            _builder.EmitOpCode(ILOpCode.Ldelem_ref);
P
Pilchie 已提交
910 911 912 913 914
                        }
                        else
                        {
                            if (used)
                            {
915
                                _builder.EmitOpCode(ILOpCode.Ldelem);
P
Pilchie 已提交
916 917 918 919
                            }
                            else
                            {
                                // no need to read whole element of nontrivial type/size here
920
                                // just take a reference to an element for array access side-effects 
P
Pilchie 已提交
921 922
                                if (elementType.TypeKind == TypeKind.TypeParameter)
                                {
923
                                    _builder.EmitOpCode(ILOpCode.Readonly);
P
Pilchie 已提交
924 925
                                }

926
                                _builder.EmitOpCode(ILOpCode.Ldelema);
P
Pilchie 已提交
927 928 929 930 931 932 933 934 935
                            }

                            EmitSymbolToken(elementType, arrayAccess.Syntax);
                        }
                        break;
                }
            }
            else
            {
936
                _builder.EmitArrayElementLoad(Emit.PEModuleBuilder.Translate((ArrayTypeSymbol)arrayAccess.Expression.Type), arrayAccess.Expression.Syntax, _diagnostics);
P
Pilchie 已提交
937 938 939 940 941 942 943 944 945
            }

            EmitPopIfUnused(used);
        }

        private void EmitFieldLoad(BoundFieldAccess fieldAccess, bool used)
        {
            var field = fieldAccess.FieldSymbol;

946
            if (!used)
P
Pilchie 已提交
947
            {
948
                // fetching unused captured frame is a no-op (like reading "this")
V
VSadov 已提交
949
                if (field.IsCapturedFrame)
950 951 952 953
                {
                    return;
                }

V
VSadov 已提交
954 955
                // Accessing a volatile field is sideeffecting because it establishes an acquire fence.
                // Otherwise, accessing an unused instance field on a struct is a noop. Just emit an unused receiver.
956 957 958 959 960
                if (!field.IsVolatile && !field.IsStatic && fieldAccess.ReceiverOpt.Type.IsVerifierValue())
                {
                    EmitExpression(fieldAccess.ReceiverOpt, used: false);
                    return;
                }
P
Pilchie 已提交
961 962 963 964 965
            }

            Debug.Assert(!field.IsConst || field.ContainingType.SpecialType == SpecialType.System_Decimal,
                "rewriter should lower constant fields into constant expressions");

V
VSadov 已提交
966 967
            // static field access is sideeffecting since it gurantees that ..ctor has run.
            // we emit static accesses even if unused.
P
Pilchie 已提交
968 969 970 971
            if (field.IsStatic)
            {
                if (field.IsVolatile)
                {
972
                    _builder.EmitOpCode(ILOpCode.Volatile);
P
Pilchie 已提交
973
                }
974
                _builder.EmitOpCode(ILOpCode.Ldsfld);
P
Pilchie 已提交
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991
                EmitSymbolToken(field, fieldAccess.Syntax);
            }
            else
            {
                var receiver = fieldAccess.ReceiverOpt;
                var fieldType = field.Type;
                if (fieldType.IsValueType && (object)fieldType == (object)receiver.Type)
                {
                    //Handle emitting a field of a self-containing struct (only possible in mscorlib)
                    //since "val.field" is the same as val, we only need to emit val.
                    EmitExpression(receiver, used);
                }
                else
                {
                    var temp = EmitFieldLoadReceiver(receiver);
                    if (temp != null)
                    {
992
                        Debug.Assert(FieldLoadMustUseRef(receiver), "only clr-ambiguous structs use temps here");
P
Pilchie 已提交
993 994 995 996 997
                        FreeTemp(temp);
                    }

                    if (field.IsVolatile)
                    {
998
                        _builder.EmitOpCode(ILOpCode.Volatile);
P
Pilchie 已提交
999 1000
                    }

1001
                    _builder.EmitOpCode(ILOpCode.Ldfld);
P
Pilchie 已提交
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
                    EmitSymbolToken(field, fieldAccess.Syntax);
                }
            }
            EmitPopIfUnused(used);
        }

        private LocalDefinition EmitFieldLoadReceiver(BoundExpression receiver)
        {
            // ldfld can work with structs directly or with their addresses
            // accessing via address is typically same or cheaper, but not for homeless values, obviously
            // there are also cases where we must emit receiver as a reference
            if (FieldLoadMustUseRef(receiver) || FieldLoadPrefersRef(receiver))
            {
V
vsadov 已提交
1015
                return EmitFieldLoadReceiverAddress(receiver) ? null : EmitReceiverRef(receiver, AddressKind.ReadOnly);
P
Pilchie 已提交
1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
            }

            EmitExpression(receiver, true);
            return null;
        }

        // In special case of loading the sequence of field accesses we can perform all the 
        // necessary field loads using the following IL: 
        //
        //      <expr>.a.b...y.z
        //          |
        //          V
        //      Unbox -or- Load.Ref (<expr>)
        //      Ldflda a
        //      Ldflda b
        //      ...
        //      Ldflda y
        //      Ldfld z
        //
        // Returns 'true' if the receiver was actually emitted this way
        private bool EmitFieldLoadReceiverAddress(BoundExpression receiver)
        {
1038
            if (receiver == null || !receiver.Type.IsValueType)
P
Pilchie 已提交
1039 1040 1041 1042 1043 1044 1045 1046 1047
            {
                return false;
            }
            else if (receiver.Kind == BoundKind.Conversion)
            {
                var conversion = (BoundConversion)receiver;
                if (conversion.ConversionKind == ConversionKind.Unboxing)
                {
                    EmitExpression(conversion.Operand, true);
1048
                    _builder.EmitOpCode(ILOpCode.Unbox);
P
Pilchie 已提交
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059
                    EmitSymbolToken(receiver.Type, receiver.Syntax);
                    return true;
                }
            }
            else if (receiver.Kind == BoundKind.FieldAccess)
            {
                var fieldAccess = (BoundFieldAccess)receiver;
                var field = fieldAccess.FieldSymbol;

                if (!field.IsStatic && EmitFieldLoadReceiverAddress(fieldAccess.ReceiverOpt))
                {
B
bkoelman 已提交
1060
                    Debug.Assert(!field.IsVolatile, "volatile valuetype fields are unexpected");
P
Pilchie 已提交
1061

1062
                    _builder.EmitOpCode(ILOpCode.Ldflda);
P
Pilchie 已提交
1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
                    EmitSymbolToken(field, fieldAccess.Syntax);
                    return true;
                }
            }

            return false;
        }

        // ldfld can work with structs directly or with their addresses
        // In some cases it results in same native code emitted, but in some cases JIT pushes values for real
        // resulting in much worse code (on x64 in particular).
        // So, we will always prefer references here except when receiver is a struct non-ref local or parameter. 
        private bool FieldLoadPrefersRef(BoundExpression receiver)
        {
            // only fields of structs can be accessed via value
            if (!receiver.Type.IsVerifierValue())
            {
                return true;
            }

            // can unbox directly into a ref.
            if (receiver.Kind == BoundKind.Conversion && ((BoundConversion)receiver).ConversionKind == ConversionKind.Unboxing)
            {
                return true;
            }

            // can we take address at all?
1090
            if (!HasHome(receiver, AddressKind.ReadOnly))
P
Pilchie 已提交
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114
            {
                return false;
            }

            switch (receiver.Kind)
            {
                case BoundKind.Parameter:
                    // prefer ldarg over ldarga
                    return ((BoundParameter)receiver).ParameterSymbol.RefKind != RefKind.None;

                case BoundKind.Local:
                    // prefer ldloc over ldloca
                    return ((BoundLocal)receiver).LocalSymbol.RefKind != RefKind.None;

                case BoundKind.Sequence:
                    return FieldLoadPrefersRef(((BoundSequence)receiver).Value);

                case BoundKind.FieldAccess:
                    var fieldAccess = (BoundFieldAccess)receiver;
                    if (fieldAccess.FieldSymbol.IsStatic)
                    {
                        return true;
                    }

1115
                    if (DiagnosticsPass.IsNonAgileFieldAccess(fieldAccess, _module.Compilation))
P
Pilchie 已提交
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
                    {
                        return false;
                    }

                    return FieldLoadPrefersRef(fieldAccess.ReceiverOpt);
            }

            return true;
        }

        internal static bool FieldLoadMustUseRef(BoundExpression expr)
        {
            var type = expr.Type;

            // type parameter values must be boxed to get access to fields
            if (type.IsTypeParameter())
            {
                return true;
            }

            // From   Dev12/symbol.cpp
            //  
            //  // Used by ILGEN to determine if the type of this AggregateSymbol is one that the CLR
            //  // will consider ambiguous to an unmanaged pointer when it is on the stack (see VSW #396011)
            //  bool AggregateSymbol::IsCLRAmbigStruct()
            //      . . .
            switch (type.SpecialType)
            {
                // case PT_BYTE:
                case SpecialType.System_Byte:
                // case PT_SHORT:
                case SpecialType.System_Int16:
                // case PT_INT:
                case SpecialType.System_Int32:
                // case PT_LONG:
                case SpecialType.System_Int64:
                // case PT_CHAR:
                case SpecialType.System_Char:
                // case PT_BOOL:
                case SpecialType.System_Boolean:
                // case PT_SBYTE:
                case SpecialType.System_SByte:
                // case PT_USHORT:
                case SpecialType.System_UInt16:
                // case PT_UINT:
                case SpecialType.System_UInt32:
                // case PT_ULONG:
                case SpecialType.System_UInt64:
                // case PT_INTPTR:
                case SpecialType.System_IntPtr:
                // case PT_UINTPTR:
                case SpecialType.System_UIntPtr:
                // case PT_FLOAT:
                case SpecialType.System_Single:
                // case PT_DOUBLE:
                case SpecialType.System_Double:
                // case PT_TYPEHANDLE:
                case SpecialType.System_RuntimeTypeHandle:
                // case PT_FIELDHANDLE:
                case SpecialType.System_RuntimeFieldHandle:
                // case PT_METHODHANDLE:
                case SpecialType.System_RuntimeMethodHandle:
                //case PT_ARGUMENTHANDLE:
                case SpecialType.System_RuntimeArgumentHandle:
                    return true;
            }

            // this is for value__
            // I do not know how to hit this, since value__ is not bindable in C#, but Dev12 has code to handle this
            return type.IsEnumType();
        }


        private static int ParameterSlot(BoundParameter parameter)
        {
            var sym = parameter.ParameterSymbol;
            int slot = sym.Ordinal;
            if (!sym.ContainingSymbol.IsStatic)
            {
                slot++;  // skip "this"
            }
            return slot;
        }

        private void EmitLocalLoad(BoundLocal local, bool used)
        {
            if (IsStackLocal(local.LocalSymbol))
            {
                // local must be already on the stack
                EmitPopIfUnused(used);
            }
            else
            {
                if (used)
                {
                    LocalDefinition definition = GetLocal(local);
1212
                    _builder.EmitLocalLoad(definition);
P
Pilchie 已提交
1213 1214 1215
                }
                else
                {
1216
                    // do nothing. Unused local load has no side-effects.
P
Pilchie 已提交
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
                    return;
                }
            }

            if (used && local.LocalSymbol.RefKind != RefKind.None)
            {
                EmitLoadIndirect(local.LocalSymbol.Type, local.Syntax);
            }
        }

        private void EmitParameterLoad(BoundParameter parameter)
        {
            int slot = ParameterSlot(parameter);
1230
            _builder.EmitLoadArgumentOpcode(slot);
P
Pilchie 已提交
1231 1232 1233 1234 1235 1236 1237 1238

            if (parameter.ParameterSymbol.RefKind != RefKind.None)
            {
                var parameterType = parameter.ParameterSymbol.Type;
                EmitLoadIndirect(parameterType, parameter.Syntax);
            }
        }

1239
        private void EmitLoadIndirect(TypeSymbol type, SyntaxNode syntaxNode)
P
Pilchie 已提交
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
        {
            if (type.IsEnumType())
            {
                //underlying primitives do not need type tokens.
                type = ((NamedTypeSymbol)type).EnumUnderlyingType;
            }

            switch (type.PrimitiveTypeCode)
            {
                case Microsoft.Cci.PrimitiveTypeCode.Int8:
1250
                    _builder.EmitOpCode(ILOpCode.Ldind_i1);
P
Pilchie 已提交
1251 1252
                    break;

1253
                case Microsoft.Cci.PrimitiveTypeCode.Boolean:
P
Pilchie 已提交
1254
                case Microsoft.Cci.PrimitiveTypeCode.UInt8:
1255
                    _builder.EmitOpCode(ILOpCode.Ldind_u1);
P
Pilchie 已提交
1256 1257 1258
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Int16:
1259
                    _builder.EmitOpCode(ILOpCode.Ldind_i2);
P
Pilchie 已提交
1260 1261 1262 1263
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Char:
                case Microsoft.Cci.PrimitiveTypeCode.UInt16:
1264
                    _builder.EmitOpCode(ILOpCode.Ldind_u2);
P
Pilchie 已提交
1265 1266 1267
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Int32:
1268
                    _builder.EmitOpCode(ILOpCode.Ldind_i4);
P
Pilchie 已提交
1269 1270 1271
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.UInt32:
1272
                    _builder.EmitOpCode(ILOpCode.Ldind_u4);
P
Pilchie 已提交
1273 1274 1275 1276
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Int64:
                case Microsoft.Cci.PrimitiveTypeCode.UInt64:
1277
                    _builder.EmitOpCode(ILOpCode.Ldind_i8);
P
Pilchie 已提交
1278 1279 1280 1281 1282
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.IntPtr:
                case Microsoft.Cci.PrimitiveTypeCode.UIntPtr:
                case Microsoft.Cci.PrimitiveTypeCode.Pointer:
1283
                    _builder.EmitOpCode(ILOpCode.Ldind_i);
P
Pilchie 已提交
1284 1285 1286
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Float32:
1287
                    _builder.EmitOpCode(ILOpCode.Ldind_r4);
P
Pilchie 已提交
1288 1289 1290
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Float64:
1291
                    _builder.EmitOpCode(ILOpCode.Ldind_r8);
P
Pilchie 已提交
1292 1293 1294 1295 1296
                    break;

                default:
                    if (type.IsVerifierReference())
                    {
1297
                        _builder.EmitOpCode(ILOpCode.Ldind_ref);
P
Pilchie 已提交
1298 1299 1300
                    }
                    else
                    {
1301
                        _builder.EmitOpCode(ILOpCode.Ldobj);
P
Pilchie 已提交
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
                        EmitSymbolToken(type, syntaxNode);
                    }
                    break;
            }
        }

        /// <summary>
        /// Used to decide if we need to emit call or callvirt.
        /// It basically checks if the receiver expression cannot be null, but it is not 100% precise. 
        /// There are cases where it really can be null, but we do not care.
        /// </summary>
        private bool CanUseCallOnRefTypeReceiver(BoundExpression receiver)
        {
            // It seems none of the ways that could produce a receiver typed as a type param 
1316
            // can guarantee that it is not null.
P
Pilchie 已提交
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
            if (receiver.Type.IsTypeParameter())
            {
                return false;
            }

            Debug.Assert(receiver.Type.IsVerifierReference(), "this is not a reference");
            Debug.Assert(receiver.Kind != BoundKind.BaseReference, "base should always use call");

            var constVal = receiver.ConstantValue;
            if (constVal != null)
            {
                // only when this is a constant Null, we need a callvirt
                return !constVal.IsNull;
            }

            switch (receiver.Kind)
            {
                case BoundKind.ArrayCreation:
                    return true;

                case BoundKind.ObjectCreationExpression:
V
VSadov 已提交
1338 1339
                    // NOTE: there are cases involving ProxyAttribute
                    // where newobj may produce null
P
Pilchie 已提交
1340 1341 1342 1343 1344 1345 1346 1347
                    return true;

                case BoundKind.Conversion:
                    var conversion = (BoundConversion)receiver;

                    switch (conversion.ConversionKind)
                    {
                        case ConversionKind.Boxing:
V
VSadov 已提交
1348 1349
                            // NOTE: boxing can produce null for Nullable, but any call through that
                            // will result in null reference exceptions anyways.
P
Pilchie 已提交
1350 1351 1352 1353
                            return true;

                        case ConversionKind.MethodGroup:
                        case ConversionKind.AnonymousFunction:
1354
                            return true;
P
Pilchie 已提交
1355 1356 1357 1358 1359 1360 1361 1362

                        case ConversionKind.ExplicitReference:
                        case ConversionKind.ImplicitReference:
                            return CanUseCallOnRefTypeReceiver(conversion.Operand);
                    }
                    break;

                case BoundKind.ThisReference:
V
VSadov 已提交
1363 1364 1365 1366
                    // NOTE: these actually can be null if called from a different language
                    // however, we assume it is responsibility of the caller to nullcheck "this"
                    // if we already have access to "this", we must be in a member and should 
                    // not redo the check
P
Pilchie 已提交
1367 1368
                    return true;

1369 1370 1371 1372 1373 1374 1375 1376
                case BoundKind.FieldAccess:
                    // same reason as for "ThisReference"
                    return ((BoundFieldAccess)receiver).FieldSymbol.IsCapturedFrame;

                case BoundKind.Local:
                    // same reason as for "ThisReference"
                    return ((BoundLocal)receiver).LocalSymbol.SynthesizedKind == SynthesizedLocalKind.FrameCache;

P
Pilchie 已提交
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390
                case BoundKind.DelegateCreationExpression:
                    return true;

                case BoundKind.Sequence:
                    var seqValue = ((BoundSequence)(receiver)).Value;
                    return CanUseCallOnRefTypeReceiver(seqValue);

                case BoundKind.AssignmentOperator:
                    var rhs = ((BoundAssignmentOperator)receiver).Right;
                    return CanUseCallOnRefTypeReceiver(rhs);

                case BoundKind.TypeOfOperator:
                    return true;

1391 1392 1393
                case BoundKind.ConditionalReceiver:
                    return true;

P
Pilchie 已提交
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424
                    //TODO: there could be more cases where we can be sure that receiver is not a null.
            }

            return false;
        }

        /// <summary>
        /// checks if receiver is effectively ldarg.0
        /// </summary>
        private bool IsThisReceiver(BoundExpression receiver)
        {
            switch (receiver.Kind)
            {
                case BoundKind.ThisReference:
                    return true;

                case BoundKind.Sequence:
                    var seqValue = ((BoundSequence)(receiver)).Value;
                    return IsThisReceiver(seqValue);
            }

            return false;
        }

        private enum CallKind
        {
            Call,
            CallVirt,
            ConstrainedCallVirt,
        }

1425
        private void EmitCallExpression(BoundCall call, UseKind useKind)
P
Pilchie 已提交
1426 1427 1428 1429 1430 1431
        {
            var method = call.Method;
            var receiver = call.ReceiverOpt;
            LocalDefinition tempOpt = null;

            // Calls to the default struct constructor are emitted as initobj, rather than call.
1432
            // NOTE: constructor invocations are represented as BoundObjectCreationExpressions,
P
Pilchie 已提交
1433 1434
            // rather than BoundCalls.  This is why we can be confident that if we see a call to a
            // constructor, it has this very specific form.
1435
            if (method.IsDefaultValueTypeConstructor())
P
Pilchie 已提交
1436 1437 1438 1439 1440
            {
                Debug.Assert(method.IsImplicitlyDeclared);
                Debug.Assert(method.ContainingType == receiver.Type);
                Debug.Assert(receiver.Kind == BoundKind.ThisReference);

1441
                tempOpt = EmitReceiverRef(receiver, AddressKind.Writeable);
1442
                _builder.EmitOpCode(ILOpCode.Initobj);    //  initobj  <MyStruct>
P
Pilchie 已提交
1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
                EmitSymbolToken(method.ContainingType, call.Syntax);
                FreeOptTemp(tempOpt);

                return;
            }

            var arguments = call.Arguments;

            CallKind callKind;

            if (method.IsStatic)
            {
                callKind = CallKind.Call;
            }
            else
            {
                var receiverType = receiver.Type;

                if (receiverType.IsVerifierReference())
                {
1463
                    EmitExpression(receiver, used: true);
P
Pilchie 已提交
1464

1465 1466 1467
                    // In some cases CanUseCallOnRefTypeReceiver returns true which means that 
                    // null check is unnecessary and we can use "call"
                    if (receiver.SuppressVirtualCalls ||
P
Pilchie 已提交
1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479
                        (!method.IsMetadataVirtual() && CanUseCallOnRefTypeReceiver(receiver)))
                    {
                        callKind = CallKind.Call;
                    }
                    else
                    {
                        callKind = CallKind.CallVirt;
                    }
                }
                else if (receiverType.IsVerifierValue())
                {
                    NamedTypeSymbol methodContainingType = method.ContainingType;
V
vsadov 已提交
1480
                    if (methodContainingType.IsVerifierValue())
P
Pilchie 已提交
1481
                    {
V
vsadov 已提交
1482 1483
                        // if method is defined in the struct itself it is assumed to be mutating, unless 
                        // it is a member of a readonly struct and is not a constructor
V
vsadov 已提交
1484
                        var receiverAddresskind = methodContainingType.IsReadOnly && method.MethodKind != MethodKind.Constructor ?
V
vsadov 已提交
1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
                                                                        AddressKind.ReadOnly :
                                                                        AddressKind.Writeable;
                        if (MayUseCallForStructMethod(method))
                        {
                            // NOTE: this should be either a method which overrides some abstract method or 
                            //       does not override anything (with few exceptions, see MayUseCallForStructMethod); 
                            //       otherwise we should not use direct 'call' and must use constrained call;

                            // calling a method defined in a value type
                            Debug.Assert(receiverType == methodContainingType);
V
vsadov 已提交
1495
                            tempOpt = EmitReceiverRef(receiver, receiverAddresskind);
V
vsadov 已提交
1496 1497 1498 1499
                            callKind = CallKind.Call;
                        }
                        else
                        {
V
vsadov 已提交
1500
                            tempOpt = EmitReceiverRef(receiver, receiverAddresskind);
V
vsadov 已提交
1501 1502
                            callKind = CallKind.ConstrainedCallVirt;
                        }
P
Pilchie 已提交
1503 1504 1505
                    }
                    else
                    {
V
vsadov 已提交
1506 1507 1508 1509
                        // calling a method defined in a base class.

                        // When calling a method that is virtual in metadata on a struct receiver, 
                        // we use a constrained virtual call. If possible, it will skip boxing.
P
Pilchie 已提交
1510 1511
                        if (method.IsMetadataVirtual())
                        {
1512
                            // NB: all methods that a struct could inherit from bases are non-mutating
1513 1514
                            //     treat receiver as ReadOnly
                            tempOpt = EmitReceiverRef(receiver, AddressKind.ReadOnly);
P
Pilchie 已提交
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529
                            callKind = CallKind.ConstrainedCallVirt;
                        }
                        else
                        {
                            EmitExpression(receiver, used: true);
                            EmitBox(receiverType, receiver.Syntax);
                            callKind = CallKind.Call;
                        }
                    }
                }
                else
                {
                    // receiver is generic and method must come from the base or an interface or a generic constraint
                    // if the receiver is actually a value type it would need to be boxed.
                    // let .constrained sort this out. 
1530
                    callKind = receiverType.IsReferenceType && !IsRef(receiver) ?
P
Pilchie 已提交
1531 1532 1533
                                CallKind.CallVirt :
                                CallKind.ConstrainedCallVirt;

1534
                    tempOpt = EmitReceiverRef(receiver, callKind == CallKind.ConstrainedCallVirt ? AddressKind.Constrained : AddressKind.Writeable);
P
Pilchie 已提交
1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545
                }
            }

            // When emitting a callvirt to a virtual method we always emit the method info of the
            // method that first declared the virtual method, not the method info of an
            // overriding method. It would be a subtle breaking change to change that rule;
            // see bug 6156 for details.

            MethodSymbol actualMethodTargetedByTheCall = method;
            if (method.IsOverride && callKind != CallKind.Call)
            {
1546
                actualMethodTargetedByTheCall = method.GetConstructedLeastOverriddenMethod(_method.ContainingType);
P
Pilchie 已提交
1547 1548 1549 1550
            }

            if (callKind == CallKind.ConstrainedCallVirt && actualMethodTargetedByTheCall.ContainingType.IsValueType)
            {
C
Charles Stoner 已提交
1551
                // special case for overridden methods like ToString(...) called on
P
Pilchie 已提交
1552 1553 1554 1555 1556 1557 1558 1559 1560
                // value types: if the original method used in emit cannot use callvirt in this
                // case, change it to Call.
                callKind = CallKind.Call;
            }

            // Devirtualizing of calls to effectively sealed methods.
            if (callKind == CallKind.CallVirt)
            {
                // NOTE: we check that we call method in same module just to be sure
C
Charles Stoner 已提交
1561
                // that it cannot be recompiled as not final and make our call not verifiable. 
P
Pilchie 已提交
1562 1563 1564 1565 1566
                // such change by adversarial user would arguably be a compat break, but better be safe...
                // In reality we would typically have one method calling another method in the same class (one GetEnumerator calling another).
                // Other scenarios are uncommon since base class cannot be sealed and 
                // referring to a derived type in a different module is not an easy thing to do.
                if (IsThisReceiver(receiver) && actualMethodTargetedByTheCall.ContainingType.IsSealed &&
1567
                        (object)actualMethodTargetedByTheCall.ContainingModule == (object)_method.ContainingModule)
P
Pilchie 已提交
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577
                {
                    // special case for target is in a sealed class and "this" receiver.
                    Debug.Assert(receiver.Type.IsVerifierReference());
                    callKind = CallKind.Call;
                }

                // NOTE: we do not check that we call method in same module.
                // Because of the "GetOriginalConstructedOverriddenMethod" above, the actual target
                // can only be final when it is "newslot virtual final".
                // In such case Dev11 emits "call" and we will just replicate the behavior. (see DevDiv: 546853 )
1578
                else if (actualMethodTargetedByTheCall.IsMetadataFinal && CanUseCallOnRefTypeReceiver(receiver))
P
Pilchie 已提交
1579 1580 1581 1582 1583 1584 1585
                {
                    // special case for calling 'final' virtual method on reference receiver
                    Debug.Assert(receiver.Type.IsVerifierReference());
                    callKind = CallKind.Call;
                }
            }

1586
            EmitArguments(arguments, method.Parameters, call.ArgumentRefKindsOpt);
P
Pilchie 已提交
1587 1588 1589 1590
            int stackBehavior = GetCallStackBehavior(call);
            switch (callKind)
            {
                case CallKind.Call:
1591
                    _builder.EmitOpCode(ILOpCode.Call, stackBehavior);
P
Pilchie 已提交
1592 1593 1594
                    break;

                case CallKind.CallVirt:
1595
                    _builder.EmitOpCode(ILOpCode.Callvirt, stackBehavior);
P
Pilchie 已提交
1596 1597 1598
                    break;

                case CallKind.ConstrainedCallVirt:
1599
                    _builder.EmitOpCode(ILOpCode.Constrained);
P
Pilchie 已提交
1600
                    EmitSymbolToken(receiver.Type, receiver.Syntax);
1601
                    _builder.EmitOpCode(ILOpCode.Callvirt, stackBehavior);
P
Pilchie 已提交
1602 1603 1604 1605 1606 1607 1608 1609
                    break;
            }

            EmitSymbolToken(actualMethodTargetedByTheCall, call.Syntax,
                            actualMethodTargetedByTheCall.IsVararg ? (BoundArgListOperator)call.Arguments[call.Arguments.Length - 1] : null);

            if (!method.ReturnsVoid)
            {
1610
                EmitPopIfUnused(useKind != UseKind.Unused);
P
Pilchie 已提交
1611
            }
V
vsadov 已提交
1612
            else if (_ilEmitStyle == ILEmitStyle.Debug)
P
Pilchie 已提交
1613 1614 1615
            {
                // The only void methods with usable return values are constructors and we represent those
                // as BoundObjectCreationExpressions, not BoundCalls.
1616
                Debug.Assert(useKind == UseKind.Unused, "Using the return value of a void method.");
1617
                Debug.Assert(_method.GenerateDebugInfo, "Implied by this.emitSequencePoints");
P
Pilchie 已提交
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646

                // DevDiv #15135.  When a method like System.Diagnostics.Debugger.Break() is called, the
                // debugger sees an event indicating that a user break (vs a breakpoint) has occurred.
                // When this happens, it uses ICorDebugILFrame.GetIP(out uint, out CorDebugMappingResult)
                // to determine the current instruction pointer.  This method returns the instruction
                // *after* the call.  The source location is then given by the last sequence point before
                // or on this instruction.  As a result, if the instruction after the call has its own
                // sequence point, then that sequence point will be used to determine the source location
                // and the debugging experience will be disrupted.  The easiest way to ensure that the next
                // instruction does not have a sequence point is to insert a nop.  Obviously, we only do this
                // if debugging is enabled and optimization is disabled.

                // From ILGENREC::genCall:
                //   We want to generate a NOP after CALL opcodes that end a statement so the debugger
                //   has better stepping behavior

                // CONSIDER: In the native compiler, there's an additional restriction on when this nop is
                // inserted.  It is quite complicated, but it basically seems to say that, if we thought
                // we could omit the temp-and-copy for a struct construction and it turned out that we
                // couldn't (perhaps because the assigned local was captured by a lambda), and if we're
                // not using the result of the constructor call (how can this even happen?), then we don't
                // want to insert the nop.  Since the consequence of not implementing this complicated logic
                // is an extra nop in debug code, this is likely not a priority.

                // CONSIDER: The native compiler also checks !(tree->flags & EXF_NODEBUGINFO).  We don't have
                // this mutable bit on our bound nodes, so we can't exactly match the behavior.  We might be
                // able to approximate the native behavior by inspecting call.WasCompilerGenerated, but it is
                // not in a reliable state after lowering.

1647
                _builder.EmitOpCode(ILOpCode.Nop);
P
Pilchie 已提交
1648 1649
            }

1650 1651 1652 1653 1654 1655 1656 1657 1658
            if (useKind == UseKind.UsedAsValue && method.RefKind != RefKind.None)
            {
                EmitLoadIndirect(method.ReturnType, call.Syntax);
            }
            else if (useKind == UseKind.UsedAsAddress)
            {
                Debug.Assert(method.RefKind != RefKind.None);
            }

P
Pilchie 已提交
1659 1660 1661
            FreeOptTemp(tempOpt);
        }

1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674
        // returns true when receiver is already a ref.
        // in such cases calling through a ref could be preferred over 
        // calling through indirectly loaded value.
        private bool IsRef(BoundExpression receiver)
        {
            switch (receiver.Kind)
            {
                case BoundKind.Local:
                    return ((BoundLocal)receiver).LocalSymbol.RefKind != RefKind.None;

                case BoundKind.Parameter:
                    return ((BoundParameter)receiver).ParameterSymbol.RefKind != RefKind.None;

1675 1676 1677
                case BoundKind.Call:
                    return ((BoundCall)receiver).Method.RefKind != RefKind.None;

1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
                case BoundKind.Dup:
                    return ((BoundDup)receiver).RefKind != RefKind.None;

                case BoundKind.Sequence:
                    return IsRef(((BoundSequence)receiver).Value);
            }

            return false;
        }

P
Pilchie 已提交
1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
        private static int GetCallStackBehavior(BoundCall call)
        {
            int stack = 0;

            if (!call.Method.ReturnsVoid)
            {
                // The call puts the return value on the stack.
                stack += 1;
            }

            if (!call.Method.IsStatic)
            {
                // The call pops the receiver off the stack.
                stack -= 1;
            }

            if (call.Method.IsVararg)
            {
                // The call pops all the arguments, fixed and variadic.
                int fixedArgCount = call.Arguments.Length - 1;
                int varArgCount = ((BoundArgListOperator)call.Arguments[fixedArgCount]).Arguments.Length;
                stack -= fixedArgCount;
                stack -= varArgCount;
            }
            else
            {
                // The call pops all the arguments.
                stack -= call.Arguments.Length;
            }

            return stack;
        }

        private static int GetObjCreationStackBehavior(BoundObjectCreationExpression objCreation)
        {
            int stack = 0;

            // Constructor puts the return value on the stack.
            stack += 1;

            if (objCreation.Constructor.IsVararg)
            {
                // Constructor pops all the arguments, fixed and variadic.
                int fixedArgCount = objCreation.Arguments.Length - 1;
                int varArgCount = ((BoundArgListOperator)objCreation.Arguments[fixedArgCount]).Arguments.Length;
                stack -= fixedArgCount;
                stack -= varArgCount;
            }
            else
            {
                // Constructor pops all the arguments.
                stack -= objCreation.Arguments.Length;
            }

            return stack;
        }

        /// <summary>
        /// Used to decide if we need to emit 'call' or 'callvirt' for structure method.
        /// It basically checks if the method overrides any other and method's defining type
        /// is not a 'special' or 'special-by-ref' type. 
        /// </summary>
1750
        internal static bool MayUseCallForStructMethod(MethodSymbol method)
P
Pilchie 已提交
1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765
        {
            Debug.Assert(method.ContainingType.IsVerifierValue(), "this is not a value type");

            if (!method.IsMetadataVirtual())
            {
                return true;
            }

            var overriddenMethod = method.OverriddenMethod;
            if ((object)overriddenMethod == null || overriddenMethod.IsAbstract)
            {
                return true;
            }

            var containingType = method.ContainingType;
1766 1767 1768
            // overrides in structs that are special types can be caled directly.
            // we can assume that special types will not be removing oiverrides
            return containingType.SpecialType != SpecialType.None;
P
Pilchie 已提交
1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
        }

        /// <summary>
        /// When array operation get long or ulong arguments the args should be 
        /// cast to native int.
        /// Note that the cast is always checked.
        /// </summary>
        private void TreatLongsAsNative(Microsoft.Cci.PrimitiveTypeCode tc)
        {
            if (tc == Microsoft.Cci.PrimitiveTypeCode.Int64)
            {
1780
                _builder.EmitOpCode(ILOpCode.Conv_ovf_i);
P
Pilchie 已提交
1781 1782 1783
            }
            else if (tc == Microsoft.Cci.PrimitiveTypeCode.UInt64)
            {
1784
                _builder.EmitOpCode(ILOpCode.Conv_ovf_i_un);
P
Pilchie 已提交
1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
            }
        }

        private void EmitArrayLength(BoundArrayLength expression, bool used)
        {
            // The binder recognizes Array.Length and Array.LongLength and creates BoundArrayLength for them.
            // 
            // ArrayLength can be either 
            //      int32 for Array.Length
            //      int64 for Array.LongLength
            //      UIntPtr for synthetic code that needs just check if length != 0 - 
            //                  this is used in "fixed(int* ptr = arr)"
            Debug.Assert(expression.Type.SpecialType == SpecialType.System_Int32 ||
                expression.Type.SpecialType == SpecialType.System_Int64 ||
                expression.Type.SpecialType == SpecialType.System_UIntPtr);

            // ldlen will null-check the expression so it must be "used"
            EmitExpression(expression.Expression, used: true);
1803
            _builder.EmitOpCode(ILOpCode.Ldlen);
P
Pilchie 已提交
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816

            var typeTo = expression.Type.PrimitiveTypeCode;

            // NOTE: ldlen returns native uint, but newarr takes native int, so the length value is always 
            //       a positive native int. We can treat it as either signed or unsigned.
            //       We will use whatever typeTo says so we do not need to convert because of sign.
            var typeFrom = typeTo.IsUnsigned() ? Microsoft.Cci.PrimitiveTypeCode.UIntPtr : Microsoft.Cci.PrimitiveTypeCode.IntPtr;

            // NOTE: In Dev10 C# this cast is unchecked.
            // That seems to be wrong since that would cause silent truncation on 64bit platform if that implements large arrays. 
            // 
            // Emitting checked conversion however results in redundant overflow checks on 64bit and also inhibits range check hoisting in loops.
            // Therefore we will emit unchecked conversion here as C# compiler always did.
1817
            _builder.EmitNumericConversion(typeFrom, typeTo, @checked: false);
P
Pilchie 已提交
1818 1819 1820 1821 1822 1823 1824 1825 1826 1827

            EmitPopIfUnused(used);
        }

        private void EmitArrayCreationExpression(BoundArrayCreation expression, bool used)
        {
            var arrayType = (ArrayTypeSymbol)expression.Type;

            EmitArrayIndices(expression.Bounds);

1828
            if (arrayType.IsSZArray)
P
Pilchie 已提交
1829
            {
1830
                _builder.EmitOpCode(ILOpCode.Newarr);
P
Pilchie 已提交
1831 1832 1833 1834
                EmitSymbolToken(arrayType.ElementType, expression.Syntax);
            }
            else
            {
1835
                _builder.EmitArrayCreation(Emit.PEModuleBuilder.Translate(arrayType), expression.Syntax, _diagnostics);
P
Pilchie 已提交
1836 1837 1838 1839 1840 1841 1842
            }

            if (expression.InitializerOpt != null)
            {
                EmitArrayInitializers(arrayType, expression.InitializerOpt);
            }

1843
            // newarr has side-effects (negative bounds etc) so always emitted.
P
Pilchie 已提交
1844 1845 1846
            EmitPopIfUnused(used);
        }

1847
        private void EmitConvertedStackAllocExpression(BoundConvertedStackAllocExpression expression, bool used)
P
Pilchie 已提交
1848
        {
V
vsadov 已提交
1849 1850 1851 1852 1853 1854 1855 1856
            EmitExpression(expression.Count, used);

            // the only sideeffect of a localloc is a nondeterminisic and generaly fatal StackOverflow.
            // we can ignore that if the actual result is unused
            if (used)
            {
                _builder.EmitOpCode(ILOpCode.Localloc);
            }
P
Pilchie 已提交
1857 1858 1859 1860 1861
        }

        private void EmitObjectCreationExpression(BoundObjectCreationExpression expression, bool used)
        {
            MethodSymbol constructor = expression.Constructor;
1862
            if (constructor.IsDefaultValueTypeConstructor())
P
Pilchie 已提交
1863 1864 1865 1866 1867
            {
                EmitInitObj(expression.Type, used, expression.Syntax);
            }
            else
            {
1868
                if (!used && ConstructorNotSideEffecting(constructor))
1869
                {
1870 1871 1872 1873 1874
                    // creating nullable has no side-effects, so we will just evaluate the arguments
                    foreach (var arg in expression.Arguments)
                    {
                        EmitExpression(arg, used: false);
                    }
1875 1876 1877
                }
                else
                {
1878
                    EmitArguments(expression.Arguments, constructor.Parameters, expression.ArgumentRefKindsOpt);
P
Pilchie 已提交
1879

1880
                    var stackAdjustment = GetObjCreationStackBehavior(expression);
1881
                    _builder.EmitOpCode(ILOpCode.Newobj, stackAdjustment);
P
Pilchie 已提交
1882

1883 1884 1885
                    // for variadic ctors emit expanded ctor token
                    EmitSymbolToken(constructor, expression.Syntax,
                                    constructor.IsVararg ? (BoundArgListOperator)expression.Arguments[expression.Arguments.Length - 1] : null);
P
Pilchie 已提交
1886

1887 1888
                    EmitPopIfUnused(used);
                }
P
Pilchie 已提交
1889 1890 1891
            }
        }

1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920
        /// <summary>
        /// Recognizes constructors known to not have side-effects (which means they can be skipped unless the constructed object is used)
        /// </summary>
        private bool ConstructorNotSideEffecting(MethodSymbol constructor)
        {
            var originalDef = constructor.OriginalDefinition;
            var compilation = _module.Compilation;

            if (originalDef == compilation.GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor))
            {
                return true;
            }

            if (originalDef.ContainingType.Name == TupleTypeSymbol.TupleTypeName &&
                    (originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T2__ctor) ||
                    originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T3__ctor) ||
                    originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T4__ctor) ||
                    originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T5__ctor) ||
                    originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T6__ctor) ||
                    originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T7__ctor) ||
                    originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_TRest__ctor) ||
                    originalDef == compilation.GetWellKnownTypeMember(WellKnownMember.System_ValueTuple_T1__ctor)))
            {
                return true;
            }

            return false;
        }

1921
        private void EmitAssignmentExpression(BoundAssignmentOperator assignmentOperator, UseKind useKind)
P
Pilchie 已提交
1922
        {
1923
            if (TryEmitAssignmentInPlace(assignmentOperator, useKind != UseKind.Unused))
P
Pilchie 已提交
1924
            {
1925
                Debug.Assert(assignmentOperator.RefKind == RefKind.None);
P
Pilchie 已提交
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974
                return;
            }

            // Assignment expression codegen has the following parts:
            //
            // * PreRHS: We need to emit instructions before the load of the right hand side if:
            //   - If the left hand side is a ref local or ref formal parameter and the right hand 
            //     side is a value then we must put the ref on the stack early so that we can store 
            //     indirectly into it.
            //   - If the left hand side is an array slot then we must evaluate the array and indices
            //     before we evaluate the right hand side. We ensure that the array and indices are 
            //     on the stack when the store is executed.
            //   - Similarly, if the left hand side is a non-static field then its receiver must be
            //     evaluated before the right hand side.
            //
            // * RHS: There are three possible ways to do an assignment with respect to "refness", 
            //   and all are found in the lowering of:
            //
            //   N().s += 10;
            //
            //   That expression is realized as 
            //
            //   ref int addr = ref N().s;   // Assign a ref on the right hand side to the left hand side.
            //   int sum = addr + 10;        // No refs at all; assign directly to sum.
            //   addr = sum;                 // Assigns indirectly through the address.
            //
            //   - If we are in the first case then assignmentOperator.RefKind is Ref and the left hand side is a 
            //     ref local temporary. We simply assign the ref on the RHS to the storage on the LHS with no indirection.
            //
            //   - If we are in the second case then nothing is ref; we have a value on one side an a local on the other.
            //     Again, there is no indirection.
            // 
            //   - If we are in the third case then we have a ref on the left and a value on the right. We must compute the
            //     value of the right hand side and then store it into the left hand side.
            //
            // * Duplication: The result of an assignment operation is the value that was assigned. It is possible that 
            //   later codegen is expecting this value to be on the stack when we're done here. This is controlled by
            //   the "used" formal parameter. There are two possible cases:
            //   - If the preamble put stuff on the stack for the usage of the store, then we must not put an extra copy
            //     of the right hand side value on the stack; that will be between the value and the stuff needed to 
            //     do the storage. In that case we put the right hand side value in a temporary and restore it later.
            //   - Otherwise we can just do a dup instruction; there's nothing before the dup on the stack that we'll need.
            // 
            // * Storage: Either direct or indirect, depending. See the RHS section above for details.
            // 
            // * Post-storage: If we stashed away the duplicated value in the temporary, we need to restore it back to the stack.

            bool lhsUsesStack = EmitAssignmentPreamble(assignmentOperator);
            EmitAssignmentValue(assignmentOperator);
1975
            LocalDefinition temp = EmitAssignmentDuplication(assignmentOperator, useKind, lhsUsesStack);
P
Pilchie 已提交
1976
            EmitStore(assignmentOperator);
1977
            EmitAssignmentPostfix(assignmentOperator, temp, useKind);
P
Pilchie 已提交
1978 1979 1980 1981 1982 1983 1984 1985
        }

        // sometimes it is possible and advantageous to get an address of the lHS and 
        // perform assignment as an in-place initialization via initobj or constructor invocation.
        //
        // 1) initobj 
        //    is used when assigning default value to T that is not a verifier reference.
        //
1986
        // 2) in-place ctor call 
P
Pilchie 已提交
1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027
        //    is used when assigning a freshly created struct. "x = new S(arg)" can be
        //    replaced by x.S(arg) as long as partial assignment cannot be observed -
        //    i.e. target must not be on the heap and we should not be in a try block.
        private bool TryEmitAssignmentInPlace(BoundAssignmentOperator assignmentOperator, bool used)
        {
            var left = assignmentOperator.Left;

            // if result is used, and lives on heap, we must keep RHS value on the stack.
            // otherwise we can try conjuring up the RHS value directly where it belongs.
            if (used && !TargetIsNotOnHeap(left))
            {
                return false;
            }

            if (!SafeToGetWriteableReference(left))
            {
                // cannot take a ref
                return false;
            }

            var right = assignmentOperator.Right;
            var rightType = right.Type;

            // in-place is not advantageous for reference types or constants
            if (!rightType.IsTypeParameter())
            {
                if (rightType.IsReferenceType || (right.ConstantValue != null && rightType.SpecialType != SpecialType.System_Decimal))
                {
                    return false;
                }
            }

            if (right.IsDefaultValue())
            {
                InPlaceInit(left, used);
                return true;
            }

            if (right.Kind == BoundKind.ObjectCreationExpression)
            {
                // It is desirable to do in-place ctor call if possible.
2028
                // we could do newobj/stloc, but in-place call 
2029
                // produces the same or better code in current JITs 
P
Pilchie 已提交
2030 2031 2032
                if (PartialCtorResultCannotEscape(left))
                {
                    var objCreation = (BoundObjectCreationExpression)right;
2033 2034 2035 2036 2037 2038 2039 2040 2041
                    var ctor = objCreation.Constructor;

                    // ctor can possibly see its own assignments indirectly if there are ref parameters or __arglist
                    if (System.Linq.ImmutableArrayExtensions.All(ctor.Parameters, p => p.RefKind == RefKind.None) &&
                        !ctor.IsVararg)
                    {
                        InPlaceCtorCall(left, objCreation, used);
                        return true;
                    }
P
Pilchie 已提交
2042 2043 2044 2045 2046 2047 2048 2049
                }
            }

            return false;
        }

        private bool SafeToGetWriteableReference(BoundExpression left)
        {
2050
            if (!HasHome(left, AddressKind.Writeable))
P
Pilchie 已提交
2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
            {
                return false;
            }

            // because of array covariance, taking a reference to an element of 
            // generic array may fail even though assignment "arr[i] = default(T)" would always succeed.
            if (left.Kind == BoundKind.ArrayAccess && left.Type.TypeKind == TypeKind.TypeParameter && !left.Type.IsValueType)
            {
                return false;
            }

            if (left.Kind == BoundKind.FieldAccess)
            {
                var fieldAccess = (BoundFieldAccess)left;
                if (fieldAccess.FieldSymbol.IsVolatile ||
2066
                    DiagnosticsPass.IsNonAgileFieldAccess(fieldAccess, _module.Compilation))
P
Pilchie 已提交
2067 2068 2069 2070 2071 2072 2073 2074 2075 2076
                {
                    return false;
                }
            }

            return true;
        }

        private void InPlaceInit(BoundExpression target, bool used)
        {
2077
            var temp = EmitAddress(target, AddressKind.Writeable);
2078
            Debug.Assert(temp == null, "in-place init target should not create temps");
2079

V
vsadov 已提交
2080
            _builder.EmitOpCode(ILOpCode.Initobj);    //  initobj  <MyStruct>
P
Pilchie 已提交
2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091
            EmitSymbolToken(target.Type, target.Syntax);

            if (used)
            {
                Debug.Assert(TargetIsNotOnHeap(target), "cannot read-back the target since it could have been modified");
                EmitExpression(target, used);
            }
        }

        private void InPlaceCtorCall(BoundExpression target, BoundObjectCreationExpression objCreation, bool used)
        {
2092
            var temp = EmitAddress(target, AddressKind.Writeable);
2093
            Debug.Assert(temp == null, "in-place ctor target should not create temps");
P
Pilchie 已提交
2094 2095

            var constructor = objCreation.Constructor;
2096
            EmitArguments(objCreation.Arguments, constructor.Parameters, objCreation.ArgumentRefKindsOpt);
P
Pilchie 已提交
2097 2098
            // -2 to adjust for consumed target address and not produced value.
            var stackAdjustment = GetObjCreationStackBehavior(objCreation) - 2;
2099
            _builder.EmitOpCode(ILOpCode.Call, stackAdjustment);
P
Pilchie 已提交
2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117
            // for variadic ctors emit expanded ctor token
            EmitSymbolToken(constructor, objCreation.Syntax,
                            constructor.IsVararg ? (BoundArgListOperator)objCreation.Arguments[objCreation.Arguments.Length - 1] : null);

            if (used)
            {
                Debug.Assert(TargetIsNotOnHeap(target), "cannot read-back the target since it could have been modified");
                EmitExpression(target, used: true);
            }
        }

        // partial ctor results are not observable when target is not on the heap.
        // we also must not be in a try, otherwise if ctor throws
        // partially assigned value may be observed in the handler.
        private bool PartialCtorResultCannotEscape(BoundExpression left)
        {
            if (TargetIsNotOnHeap(left))
            {
2118
                if (_tryNestingLevel != 0)
P
Pilchie 已提交
2119 2120
                {
                    var local = left as BoundLocal;
2121
                    if (local != null && !_builder.PossiblyDefinedOutsideOfTry(GetLocal(local)))
P
Pilchie 已提交
2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158
                    {
                        // local defined inside immediate Try - cannot escape
                        return true;
                    }

                    // local defined outside of immediate try or it is a parameter - can escape
                    return false;
                }

                // we are not in a try - locals, parameters cannot escape
                return true;
            }

            // left is a reference, partial initializations can escape.
            return false;
        }

        // returns True when assignment target is definitely not on the heap
        private static bool TargetIsNotOnHeap(BoundExpression left)
        {
            switch (left.Kind)
            {
                case BoundKind.Parameter:
                    return ((BoundParameter)left).ParameterSymbol.RefKind == RefKind.None;

                case BoundKind.Local:
                    // NOTE: stack locals are either homeless or refs, no need to special case them
                    //       they will never be assigned in-place.
                    return ((BoundLocal)left).LocalSymbol.RefKind == RefKind.None;
            }

            return false;
        }


        private bool EmitAssignmentPreamble(BoundAssignmentOperator assignmentOperator)
        {
2159
            var assignmentTarget = assignmentOperator.Left;
P
Pilchie 已提交
2160 2161
            bool lhsUsesStack = false;

2162
            switch (assignmentTarget.Kind)
P
Pilchie 已提交
2163 2164
            {
                case BoundKind.RefValueOperator:
2165
                    EmitRefValueAddress((BoundRefValueOperator)assignmentTarget);
P
Pilchie 已提交
2166 2167 2168 2169
                    break;

                case BoundKind.FieldAccess:
                    {
2170
                        var left = (BoundFieldAccess)assignmentTarget;
P
Pilchie 已提交
2171 2172
                        if (!left.FieldSymbol.IsStatic)
                        {
2173
                            var temp = EmitReceiverRef(left.ReceiverOpt, AddressKind.Writeable);
P
Pilchie 已提交
2174 2175 2176 2177 2178 2179 2180 2181
                            Debug.Assert(temp == null, "temp is unexpected when assigning to a field");
                            lhsUsesStack = true;
                        }
                    }
                    break;

                case BoundKind.Parameter:
                    {
2182
                        var left = (BoundParameter)assignmentTarget;
P
Pilchie 已提交
2183 2184
                        if (left.ParameterSymbol.RefKind != RefKind.None)
                        {
2185
                            _builder.EmitLoadArgumentOpcode(ParameterSlot(left));
P
Pilchie 已提交
2186 2187 2188 2189 2190 2191 2192
                            lhsUsesStack = true;
                        }
                    }
                    break;

                case BoundKind.Local:
                    {
2193
                        var left = (BoundLocal)assignmentTarget;
P
Pilchie 已提交
2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218

                        // Again, consider our earlier case:
                        //
                        // ref int addr = ref N().s;
                        // int sum = addr + 10; 
                        // addr = sum;
                        //
                        // There are three different ways we could be assigning to a local.
                        //
                        // In the first case, we want to simply call N(), take the address
                        // of s, and then store that address in addr.
                        //
                        // In the second case again we simply want to compute the sum and
                        // store the result in sum.
                        //
                        // In the third case however we want to first load the contents of
                        // addr -- the address of field s -- then put the sum on the stack,
                        // and then do an indirect store. In that case we need to have the
                        // contents of addr on the stack.

                        if (left.LocalSymbol.RefKind != RefKind.None && assignmentOperator.RefKind == RefKind.None)
                        {
                            if (!IsStackLocal(left.LocalSymbol))
                            {
                                LocalDefinition localDefinition = GetLocal(left);
2219
                                _builder.EmitLocalLoad(localDefinition);
P
Pilchie 已提交
2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244
                            }
                            else
                            {
                                // this is a case of indirect assignment to a stack temp.
                                // currently byref temp can only be a stack local in scenarios where 
                                // there is only one assignment and it is the last one. 
                                // I do not yet know how to support cases where we assign more than once. 
                                // That where Dup of LHS would be needed, but as a general scenario 
                                // it is not always possible to handle. Fortunately all the cases where we
                                // indirectly assign to a byref temp come from rewriter and all
                                // they all are write-once cases.
                                //
                                // For now analyzer asserts that indirect writes are final reads of 
                                // a ref local. And we never need a dup here.

                                // builder.EmitOpCode(ILOpCode.Dup);
                            }

                            lhsUsesStack = true;
                        }
                    }
                    break;

                case BoundKind.ArrayAccess:
                    {
2245
                        var left = (BoundArrayAccess)assignmentTarget;
P
Pilchie 已提交
2246 2247 2248 2249 2250 2251 2252 2253
                        EmitExpression(left.Expression, used: true);
                        EmitArrayIndices(left.Indices);
                        lhsUsesStack = true;
                    }
                    break;

                case BoundKind.ThisReference:
                    {
2254
                        var left = (BoundThisReference)assignmentTarget;
P
Pilchie 已提交
2255 2256 2257 2258 2259 2260 2261 2262 2263 2264

                        var temp = EmitAddress(left, AddressKind.Writeable);
                        Debug.Assert(temp == null, "taking ref of this should not create a temp");

                        lhsUsesStack = true;
                    }
                    break;

                case BoundKind.Dup:
                    {
2265
                        var left = (BoundDup)assignmentTarget;
P
Pilchie 已提交
2266 2267 2268 2269 2270 2271 2272 2273

                        var temp = EmitAddress(left, AddressKind.Writeable);
                        Debug.Assert(temp == null, "taking ref of Dup should not create a temp");

                        lhsUsesStack = true;
                    }
                    break;

2274 2275 2276
                case BoundKind.ConditionalOperator:
                    {
                        var left = (BoundConditionalOperator)assignmentTarget;
V
vsadov 已提交
2277
                        Debug.Assert(left.IsByRef);
2278 2279 2280 2281 2282 2283 2284 2285

                        var temp = EmitAddress(left, AddressKind.Writeable);
                        Debug.Assert(temp == null, "taking ref of this should not create a temp");

                        lhsUsesStack = true;
                    }
                    break;

P
Pilchie 已提交
2286 2287
                case BoundKind.PointerIndirectionOperator:
                    {
2288
                        var left = (BoundPointerIndirectionOperator)assignmentTarget;
P
Pilchie 已提交
2289 2290 2291 2292 2293 2294 2295

                        EmitExpression(left.Operand, used: true);

                        lhsUsesStack = true;
                    }
                    break;

2296 2297
                case BoundKind.Sequence:
                    {
2298
                        var sequence = (BoundSequence)assignmentTarget;
2299

2300 2301 2302
                        // NOTE: not releasing sequence locals right away. 
                        // Since sequence is used as a variable, we will keep the locals for the extent of the containing expression
                        DefineAndRecordLocals(sequence);
2303 2304
                        EmitSideEffects(sequence);
                        lhsUsesStack = EmitAssignmentPreamble(assignmentOperator.Update(sequence.Value, assignmentOperator.Right, assignmentOperator.RefKind, assignmentOperator.Type));
2305
                        CloseScopeAndKeepLocals(sequence);
2306 2307 2308
                    }
                    break;

2309 2310
                case BoundKind.Call:
                    {
2311
                        var left = (BoundCall)assignmentTarget;
2312 2313 2314 2315 2316 2317 2318 2319

                        Debug.Assert(left.Method.RefKind != RefKind.None);
                        EmitCallExpression(left, UseKind.UsedAsAddress);

                        lhsUsesStack = true;
                    }
                    break;

P
Pilchie 已提交
2320 2321 2322 2323 2324
                case BoundKind.PropertyAccess:
                case BoundKind.IndexerAccess:
                // Property access should have been rewritten.
                case BoundKind.PreviousSubmissionReference:
                    // Script references are lowered to a this reference and a field access.
2325 2326 2327 2328 2329 2330
                    throw ExceptionUtilities.UnexpectedValue(assignmentTarget.Kind);

                case BoundKind.PseudoVariable:
                    EmitPseudoVariableAddress((BoundPseudoVariable)assignmentTarget);
                    lhsUsesStack = true;
                    break;
2331 2332 2333 2334 2335 2336 2337

                case BoundKind.ModuleVersionId:
                case BoundKind.InstrumentationPayloadRoot:
                    break;

                default:
                    throw ExceptionUtilities.UnexpectedValue(assignmentTarget.Kind);
P
Pilchie 已提交
2338
            }
2339

P
Pilchie 已提交
2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350
            return lhsUsesStack;
        }

        private void EmitAssignmentValue(BoundAssignmentOperator assignmentOperator)
        {
            if (assignmentOperator.RefKind == RefKind.None)
            {
                EmitExpression(assignmentOperator.Right, used: true);
            }
            else
            {
V
vsadov 已提交
2351
                int exprTempsBefore = _expressionTemps?.Count ?? 0;
2352
                var local = ((BoundLocal)assignmentOperator.Left).LocalSymbol;
2353

2354 2355 2356
                // NOTE: passing "ReadOnlyStrict" here. 
                //       we should not get an address of a copy if at all possible
                LocalDefinition temp = EmitAddress(assignmentOperator.Right, local.RefKind == RefKind.RefReadOnly ? AddressKind.ReadOnlyStrict : AddressKind.Writeable);
2357 2358 2359 2360 2361

                // Generally taking a ref for the purpose of ref assignment should not be done on homeless values
                // however, there are very rare cases when we need to get a ref off a temp in synthetic code.
                // Retain those temps for the extent of the encompassing expression.
                AddExpressionTemp(temp);
V
vsadov 已提交
2362 2363

                // are we, by the way, ref-assigning to something that lives longer than encompassing expression?
2364
                if (local.SynthesizedKind.IsLongLived())
V
vsadov 已提交
2365
                {
2366 2367
                    var exprTempsAfter = _expressionTemps?.Count ?? 0;

V
vsadov 已提交
2368 2369
                    // This situation is extremely rare. We are assigning a ref to a local with unknown lifetime
                    // while computing that ref required expression temps.
2370
                    //
V
vsadov 已提交
2371 2372
                    // We cannot reuse any of those temps and must leak them from the retained set.
                    // Any of them could be directly or indirectly referred by the LHS after the assignment.
2373
                    // and we do not know the scope of the LHS - could be the whole method.
V
vsadov 已提交
2374
                    if (exprTempsAfter > exprTempsBefore)
2375 2376 2377 2378
                    {
                        _expressionTemps.Count = exprTempsBefore;
                    }
                }
P
Pilchie 已提交
2379 2380 2381
            }
        }

2382
        private LocalDefinition EmitAssignmentDuplication(BoundAssignmentOperator assignmentOperator, UseKind useKind, bool lhsUsesStack)
P
Pilchie 已提交
2383 2384
        {
            LocalDefinition temp = null;
2385
            if (useKind != UseKind.Unused)
P
Pilchie 已提交
2386
            {
2387
                _builder.EmitOpCode(ILOpCode.Dup);
P
Pilchie 已提交
2388 2389 2390 2391 2392 2393 2394 2395 2396 2397

                if (lhsUsesStack)
                {
                    // Today we sometimes have a case where we assign a ref directly to a temporary of ref type:
                    //
                    // ref int addr = ref N().y;  <-- copies the address by value; no indirection
                    // int sum = addr + 10;
                    // addr = sum;
                    //
                    // In "Redhawk" we can write this sort of code directly as well. However, we should
2398
                    // never have a case where the value of the assignment is "used", either in our own
P
Pilchie 已提交
2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417
                    // lowering passes or in Redhawk. We never have something like:
                    //
                    // ref int t1 = (ref int t2 = ref M().s); 
                    //
                    // or the even more odd:
                    //
                    // int t1 = (ref int t2 = ref M().s);
                    //
                    // Therefore we don't have to worry about what if the temporary value we are stashing
                    // away is of ref type.
                    //
                    // If we ever do implement this sort of feature then we will need to figure out which
                    // of the situations above we are in, and ensure that the correct kind of temporary
                    // is created here. And also that either its value or its indirected value is read out
                    // after the store, in EmitAssignmentPostfix, below.

                    Debug.Assert(assignmentOperator.RefKind == RefKind.None);

                    temp = AllocateTemp(assignmentOperator.Left.Type, assignmentOperator.Left.Syntax);
2418
                    _builder.EmitLocalStore(temp);
P
Pilchie 已提交
2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454
                }
            }
            return temp;
        }

        private void EmitStore(BoundAssignmentOperator assignment)
        {
            BoundExpression expression = assignment.Left;
            switch (expression.Kind)
            {
                case BoundKind.FieldAccess:
                    EmitFieldStore((BoundFieldAccess)expression);
                    break;

                case BoundKind.Local:
                    // If we are doing a 'normal' local assignment like 'int t = 10;', or
                    // if we are initializing a temporary like 'ref int t = ref M().s;' then
                    // we just emit a local store. If we are doing an assignment through
                    // a ref local temporary then we assume that the instruction to load
                    // the address is already on the stack, and we must indirect through it.

                    // See the comments in EmitAssignmentExpression above for details.
                    BoundLocal local = (BoundLocal)expression;
                    if (local.LocalSymbol.RefKind != RefKind.None && assignment.RefKind == RefKind.None)
                    {
                        EmitIndirectStore(local.LocalSymbol.Type, local.Syntax);
                    }
                    else
                    {
                        if (IsStackLocal(local.LocalSymbol))
                        {
                            // assign to stack var == leave original value on stack
                            break;
                        }
                        else
                        {
2455
                            _builder.EmitLocalStore(GetLocal(local));
P
Pilchie 已提交
2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476
                        }
                    }
                    break;

                case BoundKind.ArrayAccess:
                    var array = ((BoundArrayAccess)expression).Expression;
                    var arrayType = (ArrayTypeSymbol)array.Type;
                    EmitArrayElementStore(arrayType, expression.Syntax);
                    break;

                case BoundKind.ThisReference:
                    EmitThisStore((BoundThisReference)expression);
                    break;

                case BoundKind.Parameter:
                    EmitParameterStore((BoundParameter)expression);
                    break;

                case BoundKind.Dup:
                    Debug.Assert(((BoundDup)expression).RefKind != RefKind.None);
                    EmitIndirectStore(expression.Type, expression.Syntax);
2477 2478 2479
                    break;

                case BoundKind.ConditionalOperator:
V
vsadov 已提交
2480
                    Debug.Assert(((BoundConditionalOperator)expression).IsByRef);
2481
                    EmitIndirectStore(expression.Type, expression.Syntax);
P
Pilchie 已提交
2482 2483 2484 2485
                    break;

                case BoundKind.RefValueOperator:
                case BoundKind.PointerIndirectionOperator:
2486
                case BoundKind.PseudoVariable:
P
Pilchie 已提交
2487 2488 2489
                    EmitIndirectStore(expression.Type, expression.Syntax);
                    break;

2490 2491 2492 2493 2494 2495 2496
                case BoundKind.Sequence:
                    {
                        var sequence = (BoundSequence)expression;
                        EmitStore(assignment.Update(sequence.Value, assignment.Right, assignment.RefKind, assignment.Type));
                    }
                    break;

2497 2498 2499 2500 2501
                case BoundKind.Call:
                    Debug.Assert(((BoundCall)expression).Method.RefKind != RefKind.None);
                    EmitIndirectStore(expression.Type, expression.Syntax);
                    break;

2502
                case BoundKind.ModuleVersionId:
J
John Hamby 已提交
2503
                    EmitModuleVersionIdStore((BoundModuleVersionId)expression);
2504 2505
                    break;

J
John Hamby 已提交
2506 2507
                case BoundKind.InstrumentationPayloadRoot:
                    EmitInstrumentationPayloadRootStore((BoundInstrumentationPayloadRoot)expression);
J
John Hamby 已提交
2508 2509
                    break;

P
Pilchie 已提交
2510 2511 2512 2513 2514 2515 2516
                case BoundKind.PreviousSubmissionReference:
                // Script references are lowered to a this reference and a field access.
                default:
                    throw ExceptionUtilities.UnexpectedValue(expression.Kind);
            }
        }

2517
        private void EmitAssignmentPostfix(BoundAssignmentOperator assignment, LocalDefinition temp, UseKind useKind)
P
Pilchie 已提交
2518 2519 2520
        {
            if (temp != null)
            {
2521
                _builder.EmitLocalLoad(temp);
P
Pilchie 已提交
2522 2523
                FreeTemp(temp);
            }
2524 2525 2526 2527 2528

            if (useKind == UseKind.UsedAsValue && assignment.RefKind != RefKind.None)
            {
                EmitLoadIndirect(assignment.Type, assignment.Syntax);
            }
P
Pilchie 已提交
2529 2530 2531 2532 2533 2534
        }

        private void EmitThisStore(BoundThisReference thisRef)
        {
            Debug.Assert(thisRef.Type.IsValueType);

2535
            _builder.EmitOpCode(ILOpCode.Stobj);
P
Pilchie 已提交
2536 2537 2538
            EmitSymbolToken(thisRef.Type, thisRef.Syntax);
        }

2539
        private void EmitArrayElementStore(ArrayTypeSymbol arrayType, SyntaxNode syntaxNode)
P
Pilchie 已提交
2540
        {
2541
            if (arrayType.IsSZArray)
P
Pilchie 已提交
2542 2543 2544 2545 2546
            {
                EmitVectorElementStore(arrayType, syntaxNode);
            }
            else
            {
2547
                _builder.EmitArrayElementStore(Emit.PEModuleBuilder.Translate(arrayType), syntaxNode, _diagnostics);
P
Pilchie 已提交
2548 2549 2550 2551 2552 2553
            }
        }

        /// <summary>
        /// Emit an element store instruction for a single dimensional array.
        /// </summary>
2554
        private void EmitVectorElementStore(ArrayTypeSymbol arrayType, SyntaxNode syntaxNode)
P
Pilchie 已提交
2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568
        {
            var elementType = arrayType.ElementType;

            if (elementType.IsEnumType())
            {
                //underlying primitives do not need type tokens.
                elementType = ((NamedTypeSymbol)elementType).EnumUnderlyingType;
            }

            switch (elementType.PrimitiveTypeCode)
            {
                case Microsoft.Cci.PrimitiveTypeCode.Boolean:
                case Microsoft.Cci.PrimitiveTypeCode.Int8:
                case Microsoft.Cci.PrimitiveTypeCode.UInt8:
2569
                    _builder.EmitOpCode(ILOpCode.Stelem_i1);
P
Pilchie 已提交
2570 2571 2572 2573 2574
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Char:
                case Microsoft.Cci.PrimitiveTypeCode.Int16:
                case Microsoft.Cci.PrimitiveTypeCode.UInt16:
2575
                    _builder.EmitOpCode(ILOpCode.Stelem_i2);
P
Pilchie 已提交
2576 2577 2578 2579
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Int32:
                case Microsoft.Cci.PrimitiveTypeCode.UInt32:
2580
                    _builder.EmitOpCode(ILOpCode.Stelem_i4);
P
Pilchie 已提交
2581 2582 2583 2584
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Int64:
                case Microsoft.Cci.PrimitiveTypeCode.UInt64:
2585
                    _builder.EmitOpCode(ILOpCode.Stelem_i8);
P
Pilchie 已提交
2586 2587 2588 2589 2590
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.IntPtr:
                case Microsoft.Cci.PrimitiveTypeCode.UIntPtr:
                case Microsoft.Cci.PrimitiveTypeCode.Pointer:
2591
                    _builder.EmitOpCode(ILOpCode.Stelem_i);
P
Pilchie 已提交
2592 2593 2594
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Float32:
2595
                    _builder.EmitOpCode(ILOpCode.Stelem_r4);
P
Pilchie 已提交
2596 2597 2598
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Float64:
2599
                    _builder.EmitOpCode(ILOpCode.Stelem_r8);
P
Pilchie 已提交
2600 2601 2602 2603 2604
                    break;

                default:
                    if (elementType.IsVerifierReference())
                    {
2605
                        _builder.EmitOpCode(ILOpCode.Stelem_ref);
P
Pilchie 已提交
2606 2607 2608
                    }
                    else
                    {
2609
                        _builder.EmitOpCode(ILOpCode.Stelem);
P
Pilchie 已提交
2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621
                        EmitSymbolToken(elementType, syntaxNode);
                    }
                    break;
            }
        }

        private void EmitFieldStore(BoundFieldAccess fieldAccess)
        {
            var field = fieldAccess.FieldSymbol;

            if (field.IsVolatile)
            {
2622
                _builder.EmitOpCode(ILOpCode.Volatile);
P
Pilchie 已提交
2623 2624
            }

2625
            _builder.EmitOpCode(field.IsStatic ? ILOpCode.Stsfld : ILOpCode.Stfld);
P
Pilchie 已提交
2626 2627 2628 2629 2630 2631 2632 2633 2634
            EmitSymbolToken(field, fieldAccess.Syntax);
        }

        private void EmitParameterStore(BoundParameter parameter)
        {
            int slot = ParameterSlot(parameter);

            if (parameter.ParameterSymbol.RefKind == RefKind.None)
            {
2635
                _builder.EmitStoreArgumentOpcode(slot);
P
Pilchie 已提交
2636 2637 2638 2639 2640 2641 2642 2643 2644
            }
            else
            {
                //NOTE: we should have the actual parameter already loaded, 
                //now need to do a store to where it points to
                EmitIndirectStore(parameter.ParameterSymbol.Type, parameter.Syntax);
            }
        }

2645
        private void EmitIndirectStore(TypeSymbol type, SyntaxNode syntaxNode)
P
Pilchie 已提交
2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657
        {
            if (type.IsEnumType())
            {
                //underlying primitives do not need type tokens.
                type = ((NamedTypeSymbol)type).EnumUnderlyingType;
            }

            switch (type.PrimitiveTypeCode)
            {
                case Microsoft.Cci.PrimitiveTypeCode.Boolean:
                case Microsoft.Cci.PrimitiveTypeCode.Int8:
                case Microsoft.Cci.PrimitiveTypeCode.UInt8:
2658
                    _builder.EmitOpCode(ILOpCode.Stind_i1);
P
Pilchie 已提交
2659 2660 2661 2662 2663
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Char:
                case Microsoft.Cci.PrimitiveTypeCode.Int16:
                case Microsoft.Cci.PrimitiveTypeCode.UInt16:
2664
                    _builder.EmitOpCode(ILOpCode.Stind_i2);
P
Pilchie 已提交
2665 2666 2667 2668
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Int32:
                case Microsoft.Cci.PrimitiveTypeCode.UInt32:
2669
                    _builder.EmitOpCode(ILOpCode.Stind_i4);
P
Pilchie 已提交
2670 2671 2672 2673
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Int64:
                case Microsoft.Cci.PrimitiveTypeCode.UInt64:
2674
                    _builder.EmitOpCode(ILOpCode.Stind_i8);
P
Pilchie 已提交
2675 2676 2677 2678 2679
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.IntPtr:
                case Microsoft.Cci.PrimitiveTypeCode.UIntPtr:
                case Microsoft.Cci.PrimitiveTypeCode.Pointer:
2680
                    _builder.EmitOpCode(ILOpCode.Stind_i);
P
Pilchie 已提交
2681 2682 2683
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Float32:
2684
                    _builder.EmitOpCode(ILOpCode.Stind_r4);
P
Pilchie 已提交
2685 2686 2687
                    break;

                case Microsoft.Cci.PrimitiveTypeCode.Float64:
2688
                    _builder.EmitOpCode(ILOpCode.Stind_r8);
P
Pilchie 已提交
2689 2690 2691 2692 2693
                    break;

                default:
                    if (type.IsVerifierReference())
                    {
2694
                        _builder.EmitOpCode(ILOpCode.Stind_ref);
P
Pilchie 已提交
2695 2696 2697
                    }
                    else
                    {
2698
                        _builder.EmitOpCode(ILOpCode.Stobj);
P
Pilchie 已提交
2699 2700 2701 2702 2703 2704 2705 2706 2707 2708
                        EmitSymbolToken(type, syntaxNode);
                    }
                    break;
            }
        }

        private void EmitPopIfUnused(bool used)
        {
            if (!used)
            {
2709
                _builder.EmitOpCode(ILOpCode.Pop);
P
Pilchie 已提交
2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721
            }
        }

        private void EmitIsExpression(BoundIsOperator isOp, bool used)
        {
            var operand = isOp.Operand;
            EmitExpression(operand, used);
            if (used)
            {
                Debug.Assert((object)operand.Type != null);
                if (!operand.Type.IsVerifierReference())
                {
2722
                    // box the operand for isinst if it is not a verifier reference
P
Pilchie 已提交
2723 2724
                    EmitBox(operand.Type, operand.Syntax);
                }
2725
                _builder.EmitOpCode(ILOpCode.Isinst);
P
Pilchie 已提交
2726
                EmitSymbolToken(isOp.TargetType.Type, isOp.Syntax);
2727 2728
                _builder.EmitOpCode(ILOpCode.Ldnull);
                _builder.EmitOpCode(ILOpCode.Cgt_un);
P
Pilchie 已提交
2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745
            }
        }

        private void EmitAsExpression(BoundAsOperator asOp, bool used)
        {
            Debug.Assert(!asOp.Conversion.Kind.IsImplicitConversion());

            var operand = asOp.Operand;
            EmitExpression(operand, used);

            if (used)
            {
                var operandType = operand.Type;
                var targetType = asOp.Type;
                Debug.Assert((object)targetType != null);
                if ((object)operandType != null && !operandType.IsVerifierReference())
                {
2746
                    // box the operand for isinst if it is not a verifier reference
P
Pilchie 已提交
2747 2748
                    EmitBox(operandType, operand.Syntax);
                }
2749
                _builder.EmitOpCode(ILOpCode.Isinst);
P
Pilchie 已提交
2750 2751 2752 2753
                EmitSymbolToken(targetType, asOp.Syntax);
                if (!targetType.IsVerifierReference())
                {
                    // We need to unbox if the target type is not a reference type
2754
                    _builder.EmitOpCode(ILOpCode.Unbox_any);
P
Pilchie 已提交
2755 2756 2757 2758 2759
                    EmitSymbolToken(targetType, asOp.Syntax);
                }
            }
        }

2760
        private void EmitDefaultValue(TypeSymbol type, bool used, SyntaxNode syntaxNode)
2761
        {
2762
            if (used)
2763
            {
2764
                // default type parameter values must be emitted as 'initobj' regardless of constraints
2765
                if (!type.IsTypeParameter() && type.SpecialType != SpecialType.System_Decimal)
2766
                {
2767 2768 2769 2770 2771 2772
                    var constantValue = type.GetDefaultValue();
                    if (constantValue != null)
                    {
                        _builder.EmitConstantValue(constantValue);
                        return;
                    }
2773
                }
2774

V
vsadov 已提交
2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786
                if (type.IsPointerType() || type.SpecialType == SpecialType.System_UIntPtr)
                {
                    // default(whatever*) and default(UIntPtr) can be emitted as:
                    _builder.EmitOpCode(ILOpCode.Ldc_i4_0);
                    _builder.EmitOpCode(ILOpCode.Conv_u);
                }
                else if (type.SpecialType == SpecialType.System_IntPtr)
                {
                    _builder.EmitOpCode(ILOpCode.Ldc_i4_0);
                    _builder.EmitOpCode(ILOpCode.Conv_i);
                }
                else
V
vsadov 已提交
2787
                {
V
vsadov 已提交
2788 2789
                    EmitInitObj(type, true, syntaxNode);
                }
2790 2791 2792
            }
        }

2793
        private void EmitDefaultExpression(BoundDefaultExpression expression, bool used)
P
Pilchie 已提交
2794 2795 2796 2797 2798 2799 2800
        {
            Debug.Assert(expression.Type.SpecialType == SpecialType.System_Decimal ||
                expression.Type.GetDefaultValue() == null, "constant should be set on this expression");

            // Default value for the given default expression is not a constant
            // Expression must be of type parameter type or a non-primitive value type
            // Emit an initobj instruction for these cases
V
vsadov 已提交
2801
            EmitDefaultValue(expression.Type, used, expression.Syntax);
P
Pilchie 已提交
2802 2803
        }

2804
        private void EmitConstantExpression(TypeSymbol type, ConstantValue constantValue, bool used, SyntaxNode syntaxNode)
P
Pilchie 已提交
2805
        {
2806
            if (used)  // unused constant has no side-effects
P
Pilchie 已提交
2807 2808 2809 2810 2811 2812 2813 2814
            {
                // Null type parameter values must be emitted as 'initobj' rather than 'ldnull'.
                if (((object)type != null) && (type.TypeKind == TypeKind.TypeParameter) && constantValue.IsNull)
                {
                    EmitInitObj(type, used, syntaxNode);
                }
                else
                {
2815
                    _builder.EmitConstantValue(constantValue);
P
Pilchie 已提交
2816 2817 2818 2819
                }
            }
        }

2820
        private void EmitInitObj(TypeSymbol type, bool used, SyntaxNode syntaxNode)
P
Pilchie 已提交
2821 2822
        {
            if (used)
V
vsadov 已提交
2823
            {
V
vsadov 已提交
2824 2825
                var temp = this.AllocateTemp(type, syntaxNode);
                _builder.EmitLocalAddress(temp);                  //  ldloca temp
V
vsadov 已提交
2826
                _builder.EmitOpCode(ILOpCode.Initobj);            //  initobj  <MyStruct>
V
vsadov 已提交
2827 2828 2829
                EmitSymbolToken(type, syntaxNode);
                _builder.EmitLocalLoad(temp);                     //  ldloc temp
                FreeTemp(temp);
P
Pilchie 已提交
2830 2831 2832
            }
        }

2833
        private void EmitGetTypeFromHandle(BoundTypeOf boundTypeOf)
2834 2835 2836 2837 2838 2839 2840
        {
            _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0); //argument off, return value on
            var getTypeMethod = boundTypeOf.GetTypeFromHandle;
            Debug.Assert((object)getTypeMethod != null); // Should have been checked during binding
            EmitSymbolToken(getTypeMethod, boundTypeOf.Syntax, null);
        }

P
Pilchie 已提交
2841 2842 2843
        private void EmitTypeOfExpression(BoundTypeOfOperator boundTypeOfOperator)
        {
            TypeSymbol type = boundTypeOfOperator.SourceType.Type;
2844
            _builder.EmitOpCode(ILOpCode.Ldtoken);
P
Pilchie 已提交
2845
            EmitSymbolToken(type, boundTypeOfOperator.SourceType.Syntax);
2846
            EmitGetTypeFromHandle(boundTypeOfOperator);
P
Pilchie 已提交
2847 2848 2849 2850 2851
        }

        private void EmitSizeOfExpression(BoundSizeOfOperator boundSizeOfOperator)
        {
            TypeSymbol type = boundSizeOfOperator.SourceType.Type;
2852
            _builder.EmitOpCode(ILOpCode.Sizeof);
P
Pilchie 已提交
2853
            EmitSymbolToken(type, boundSizeOfOperator.SourceType.Syntax);
J
More  
John Hamby 已提交
2854 2855
        }

J
John Hamby 已提交
2856
        private void EmitMethodDefIndexExpression(BoundMethodDefIndex node)
J
More  
John Hamby 已提交
2857
        {
J
John Hamby 已提交
2858 2859
            Debug.Assert(node.Method.IsDefinition);
            Debug.Assert(node.Type.SpecialType == SpecialType.System_Int32);
J
John Hamby 已提交
2860
            _builder.EmitOpCode(ILOpCode.Ldtoken);
S
Shyam N 已提交
2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871

            // For partial methods, we emit pseudo token based on the symbol for the partial
            // definition part as opposed to the symbol for the partial implementation part.
            // We will need to resolve the symbol associated with each pseudo token in order
            // to compute the real method definition tokens later. For partial methods, this
            // resolution can only succeed if the associated symbol is the symbol for the
            // partial definition and not the symbol for the partial implementation (see
            // MethodSymbol.ResolvedMethodImpl()).
            var symbol = node.Method.PartialDefinitionPart ?? node.Method;

            EmitSymbolToken(symbol, node.Syntax, null, encodeAsRawDefinitionToken: true);
2872 2873
        }

J
John Hamby 已提交
2874
        private void EmitMaximumMethodDefIndexExpression(BoundMaximumMethodDefIndex node)
J
John Hamby 已提交
2875 2876 2877 2878 2879 2880
        {
            Debug.Assert(node.Type.SpecialType == SpecialType.System_Int32);
            _builder.EmitOpCode(ILOpCode.Ldtoken);
            _builder.EmitGreatestMethodToken();
        }

J
John Hamby 已提交
2881
        private void EmitModuleVersionIdLoad(BoundModuleVersionId node)
2882 2883
        {
            _builder.EmitOpCode(ILOpCode.Ldsfld);
J
John Hamby 已提交
2884
            EmitModuleVersionIdToken(node);
2885 2886
        }

J
John Hamby 已提交
2887
        private void EmitModuleVersionIdStore(BoundModuleVersionId node)
2888 2889
        {
            _builder.EmitOpCode(ILOpCode.Stsfld);
J
John Hamby 已提交
2890 2891 2892 2893 2894
            EmitModuleVersionIdToken(node);
        }

        private void EmitModuleVersionIdToken(BoundModuleVersionId node)
        {
J
John Hamby 已提交
2895
            _builder.EmitToken(_module.GetModuleVersionId(_module.Translate(node.Type, node.Syntax, _diagnostics), node.Syntax, _diagnostics), node.Syntax, _diagnostics);
J
John Hamby 已提交
2896
        }
J
More.  
John Hamby 已提交
2897 2898 2899 2900 2901 2902 2903

        private void EmitModuleVersionIdStringLoad(BoundModuleVersionIdString node)
        {
            _builder.EmitOpCode(ILOpCode.Ldstr);
            _builder.EmitModuleVersionIdStringToken();
        }

J
John Hamby 已提交
2904
        private void EmitInstrumentationPayloadRootLoad(BoundInstrumentationPayloadRoot node)
J
John Hamby 已提交
2905 2906
        {
            _builder.EmitOpCode(ILOpCode.Ldsfld);
J
John Hamby 已提交
2907
            EmitInstrumentationPayloadRootToken(node);
J
John Hamby 已提交
2908 2909
        }

J
John Hamby 已提交
2910
        private void EmitInstrumentationPayloadRootStore(BoundInstrumentationPayloadRoot node)
J
John Hamby 已提交
2911 2912
        {
            _builder.EmitOpCode(ILOpCode.Stsfld);
2913
            EmitInstrumentationPayloadRootToken(node);
J
John Hamby 已提交
2914 2915 2916 2917
        }

        private void EmitInstrumentationPayloadRootToken(BoundInstrumentationPayloadRoot node)
        {
J
John Hamby 已提交
2918
            _builder.EmitToken(_module.GetInstrumentationPayloadRoot(node.AnalysisKind, _module.Translate(node.Type, node.Syntax, _diagnostics), node.Syntax, _diagnostics), node.Syntax, _diagnostics);
2919 2920 2921 2922 2923 2924 2925
        }

        private void EmitSourceDocumentIndex(BoundSourceDocumentIndex node)
        {
            Debug.Assert(node.Type.SpecialType == SpecialType.System_Int32);
            _builder.EmitOpCode(ILOpCode.Ldtoken);
            _builder.EmitSourceDocumentIndexToken(node.Document);
P
Pilchie 已提交
2926 2927 2928 2929
        }

        private void EmitMethodInfoExpression(BoundMethodInfo node)
        {
2930
            _builder.EmitOpCode(ILOpCode.Ldtoken);
P
Pilchie 已提交
2931 2932 2933 2934 2935 2936 2937
            EmitSymbolToken(node.Method, node.Syntax, null);

            MethodSymbol getMethod = node.GetMethodFromHandle;
            Debug.Assert((object)getMethod != null);

            if (getMethod.ParameterCount == 1)
            {
2938
                _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0); //argument off, return value on
P
Pilchie 已提交
2939 2940 2941 2942
            }
            else
            {
                Debug.Assert(getMethod.ParameterCount == 2);
2943
                _builder.EmitOpCode(ILOpCode.Ldtoken);
P
Pilchie 已提交
2944
                EmitSymbolToken(node.Method.ContainingType, node.Syntax);
2945
                _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: -1); //2 arguments off, return value on
P
Pilchie 已提交
2946 2947 2948 2949 2950
            }

            EmitSymbolToken(getMethod, node.Syntax, null);
            if (node.Type != getMethod.ReturnType)
            {
2951
                _builder.EmitOpCode(ILOpCode.Castclass);
P
Pilchie 已提交
2952 2953 2954 2955 2956 2957
                EmitSymbolToken(node.Type, node.Syntax);
            }
        }

        private void EmitFieldInfoExpression(BoundFieldInfo node)
        {
2958
            _builder.EmitOpCode(ILOpCode.Ldtoken);
P
Pilchie 已提交
2959 2960 2961 2962 2963 2964
            EmitSymbolToken(node.Field, node.Syntax);
            MethodSymbol getField = node.GetFieldFromHandle;
            Debug.Assert((object)getField != null);

            if (getField.ParameterCount == 1)
            {
2965
                _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0); //argument off, return value on
P
Pilchie 已提交
2966 2967 2968 2969
            }
            else
            {
                Debug.Assert(getField.ParameterCount == 2);
2970
                _builder.EmitOpCode(ILOpCode.Ldtoken);
P
Pilchie 已提交
2971
                EmitSymbolToken(node.Field.ContainingType, node.Syntax);
2972
                _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: -1); //2 arguments off, return value on
P
Pilchie 已提交
2973 2974 2975 2976 2977
            }

            EmitSymbolToken(getField, node.Syntax, null);
            if (node.Type != getField.ReturnType)
            {
2978
                _builder.EmitOpCode(ILOpCode.Castclass);
P
Pilchie 已提交
2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038
                EmitSymbolToken(node.Type, node.Syntax);
            }
        }

        /// <summary>
        /// Emit code for a conditional (aka ternary) operator.
        /// </summary>
        /// <remarks>
        /// (b ? x : y) becomes
        ///     push b
        ///     if pop then goto CONSEQUENCE
        ///     push y
        ///     goto DONE
        ///   CONSEQUENCE:
        ///     push x
        ///   DONE:
        /// </remarks>
        private void EmitConditionalOperator(BoundConditionalOperator expr, bool used)
        {
            Debug.Assert(expr.ConstantValue == null, "Constant value should have been emitted directly");

            object consequenceLabel = new object();
            object doneLabel = new object();

            EmitCondBranch(expr.Condition, ref consequenceLabel, sense: true);
            EmitExpression(expr.Alternative, used);

            //
            // III.1.8.1.3 Merging stack states
            // . . . 
            // Let T be the type from the slot on the newly computed state and S
            // be the type from the corresponding slot on the previously stored state. The merged type, U, shall
            // be computed as follows (recall that S := T is the compatibility function defined
            // in §III.1.8.1.2.2):
            // 1. if S := T then U=S
            // 2. Otherwise, if T := S then U=T
            // 3. Otherwise, if S and T are both object types, then let V be the closest common supertype of S and T then U=V.
            // 4. Otherwise, the merge shall fail.
            //
            // When the target merge type is an interface that one or more classes implement, we emit static casts
            // from any class to the target interface.
            // You may think that it's possible to elide one of the static casts and have the CLR recognize
            // that merging a class and interface should succeed if the class implements the interface. Unfortunately,
            // it seems that either PEVerify or the runtime/JIT verifier will complain at you if you try to remove
            // either of the casts.
            //
            var mergeTypeOfAlternative = StackMergeType(expr.Alternative);
            if (used)
            {
                if (IsVarianceCast(expr.Type, mergeTypeOfAlternative))
                {
                    EmitStaticCast(expr.Type, expr.Syntax);
                    mergeTypeOfAlternative = expr.Type;
                }
                else if (expr.Type.IsInterfaceType() && expr.Type != mergeTypeOfAlternative)
                {
                    EmitStaticCast(expr.Type, expr.Syntax);
                }
            }

3039
            _builder.EmitBranch(ILOpCode.Br, doneLabel);
P
Pilchie 已提交
3040 3041
            if (used)
            {
C
Charles Stoner 已提交
3042
                // If we get to consequenceLabel, we should not have Alternative on stack, adjust for that.
3043
                _builder.AdjustStack(-1);
P
Pilchie 已提交
3044 3045
            }

3046
            _builder.MarkLabel(consequenceLabel);
P
Pilchie 已提交
3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062
            EmitExpression(expr.Consequence, used);

            if (used)
            {
                var mergeTypeOfConsequence = StackMergeType(expr.Consequence);
                if (IsVarianceCast(expr.Type, mergeTypeOfConsequence))
                {
                    EmitStaticCast(expr.Type, expr.Syntax);
                    mergeTypeOfConsequence = expr.Type;
                }
                else if (expr.Type.IsInterfaceType() && expr.Type != mergeTypeOfConsequence)
                {
                    EmitStaticCast(expr.Type, expr.Syntax);
                }
            }

3063
            _builder.MarkLabel(doneLabel);
P
Pilchie 已提交
3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098
        }

        /// <summary>
        /// Emit code for a null-coalescing operator.
        /// </summary>
        /// <remarks>
        /// x ?? y becomes
        ///   push x
        ///   dup x
        ///   if pop != null goto LEFT_NOT_NULL
        ///     pop 
        ///     push y
        ///   LEFT_NOT_NULL:
        /// </remarks>
        private void EmitNullCoalescingOperator(BoundNullCoalescingOperator expr, bool used)
        {
            Debug.Assert(expr.LeftConversion.IsIdentity, "coalesce with nontrivial left conversions are lowered into ternary.");
            Debug.Assert(expr.Type.IsReferenceType);

            EmitExpression(expr.LeftOperand, used: true);

            // See the notes about verification type merges in EmitConditionalOperator
            var mergeTypeOfLeftValue = StackMergeType(expr.LeftOperand);
            if (used)
            {
                if (IsVarianceCast(expr.Type, mergeTypeOfLeftValue))
                {
                    EmitStaticCast(expr.Type, expr.Syntax);
                    mergeTypeOfLeftValue = expr.Type;
                }
                else if (expr.Type.IsInterfaceType() && expr.Type != mergeTypeOfLeftValue)
                {
                    EmitStaticCast(expr.Type, expr.Syntax);
                }

3099
                _builder.EmitOpCode(ILOpCode.Dup);
P
Pilchie 已提交
3100 3101 3102 3103 3104 3105 3106 3107
            }

            if (expr.Type.IsTypeParameter())
            {
                EmitBox(expr.Type, expr.LeftOperand.Syntax);
            }

            object ifLeftNotNullLabel = new object();
3108
            _builder.EmitBranch(ILOpCode.Brtrue, ifLeftNotNullLabel);
P
Pilchie 已提交
3109 3110 3111

            if (used)
            {
3112
                _builder.EmitOpCode(ILOpCode.Pop);
P
Pilchie 已提交
3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125
            }

            EmitExpression(expr.RightOperand, used);
            if (used)
            {
                var mergeTypeOfRightValue = StackMergeType(expr.RightOperand);
                if (IsVarianceCast(expr.Type, mergeTypeOfRightValue))
                {
                    EmitStaticCast(expr.Type, expr.Syntax);
                    mergeTypeOfRightValue = expr.Type;
                }
            }

3126
            _builder.MarkLabel(ifLeftNotNullLabel);
P
Pilchie 已提交
3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160
        }

        // Implicit casts are not emitted. As a result verifier may operate on a different 
        // types from the types of operands when performing stack merges in coalesce/ternary.
        // Such differences are in general irrelevant since merging rules work the same way
        // for base and derived types.
        //
        // Situation becomes more complicated with delegates, arrays and interfaces since they 
        // allow implicit casts from types that do not derive from them. In such cases
        // we may need to introduce static casts in the code to prod the verifier to the 
        // right direction
        //
        // This helper returns actual type of array|interface|delegate expression ignoring implicit 
        // casts. This would be the effective stack merge type in the verifier.
        // 
        // NOTE: In cases where stack merge type cannot be determined, we just return null.
        //       We still must assume that it can be an array, delegate or interface though.
        private TypeSymbol StackMergeType(BoundExpression expr)
        {
            // these cases are not interesting. Merge type is the same or derived. No difference.
            if (!(expr.Type.IsArray() || expr.Type.IsInterfaceType() || expr.Type.IsDelegateType()))
            {
                return expr.Type;
            }

            // Dig through casts. We only need to check for expressions that -
            // 1) implicit casts
            // 2) transparently return operands, so we need to dig deeper
            // 3) stack values
            switch (expr.Kind)
            {
                case BoundKind.Conversion:
                    var conversion = (BoundConversion)expr;
                    var conversionKind = conversion.ConversionKind;
3161 3162
                    Debug.Assert(conversionKind != ConversionKind.DefaultOrNullLiteral);

P
Pilchie 已提交
3163
                    if (conversionKind.IsImplicitConversion() &&
3164
                        conversionKind != ConversionKind.MethodGroup &&
V
vsadov 已提交
3165
                        conversionKind != ConversionKind.DefaultOrNullLiteral)
P
Pilchie 已提交
3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199
                    {
                        return StackMergeType(conversion.Operand);
                    }
                    break;

                case BoundKind.AssignmentOperator:
                    var assignment = (BoundAssignmentOperator)expr;
                    return StackMergeType(assignment.Right);

                case BoundKind.Sequence:
                    var sequence = (BoundSequence)expr;
                    return StackMergeType(sequence.Value);

                case BoundKind.Local:
                    var local = (BoundLocal)expr;
                    if (this.IsStackLocal(local.LocalSymbol))
                    {
                        // stack value, we cannot be sure what it is
                        return null;
                    }
                    break;

                case BoundKind.Dup:
                    // stack value, we cannot be sure what it is
                    return null;
            }

            return expr.Type;
        }

        // Although III.1.8.1.3 seems to imply that verifier understands variance casts.
        // It appears that verifier/JIT gets easily confused. 
        // So to not rely on whether that should work or not we will flag potentially 
        // "complicated" casts and make them static casts to ensure we are all on 
3200
        // the same page with what type should be tracked.
P
Pilchie 已提交
3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224
        private static bool IsVarianceCast(TypeSymbol to, TypeSymbol from)
        {
            if (to == from)
            {
                return false;
            }

            if ((object)from == null)
            {
                // from unknown type - this could be a variance conversion.
                return true;
            }

            // while technically variance casts, array conversions do not seem to be a problem
            // unless the element types are converted via variance.
            if (to.IsArray())
            {
                return IsVarianceCast(((ArrayTypeSymbol)to).ElementType, ((ArrayTypeSymbol)from).ElementType);
            }

            return (to.IsDelegateType() && to != from) ||
                   (to.IsInterfaceType() && from.IsInterfaceType() && !from.InterfacesAndTheirBaseInterfacesNoUseSiteDiagnostics.Contains((NamedTypeSymbol)to));
        }

3225
        private void EmitStaticCast(TypeSymbol to, SyntaxNode syntax)
P
Pilchie 已提交
3226 3227 3228 3229
        {
            Debug.Assert(to.IsVerifierReference());

            // From ILGENREC::GenQMark
C
Charles Stoner 已提交
3230
            // See VSWhidbey Bugs #49619 and 108643. If the destination type is an interface we need
P
Pilchie 已提交
3231 3232 3233 3234 3235 3236 3237 3238 3239
            // to force a static cast to be generated for any cast result expressions. The static cast
            // should be done before the unifying jump so the code is verifiable and to allow the JIT to
            // optimize it away. NOTE: Since there is no staticcast instruction, we implement static cast
            // with a stloc / ldloc to a temporary.
            // Bug: VSWhidbey/49619
            // Bug: VSWhidbey/108643
            // Bug: Devdiv/42645

            var temp = AllocateTemp(to, syntax);
3240 3241
            _builder.EmitLocalStore(temp);
            _builder.EmitLocalLoad(temp);
P
Pilchie 已提交
3242 3243 3244
            FreeTemp(temp);
        }

3245
        private void EmitBox(TypeSymbol type, SyntaxNode syntaxNode)
P
Pilchie 已提交
3246
        {
3247
            _builder.EmitOpCode(ILOpCode.Box);
P
Pilchie 已提交
3248 3249 3250
            EmitSymbolToken(type, syntaxNode);
        }
    }
S
Sam Harwell 已提交
3251
}