forked from dotnet/roslyn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EmitExpression.cs
3893 lines (3312 loc) · 160 KB
/
EmitExpression.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
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
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
using static System.Linq.ImmutableArrayExtensions;
using static Microsoft.CodeAnalysis.CSharp.Binder;
namespace Microsoft.CodeAnalysis.CSharp.CodeGen
{
internal partial class CodeGenerator
{
private int _recursionDepth;
private class EmitCancelledException : Exception
{ }
private enum UseKind
{
Unused,
UsedAsValue,
UsedAsAddress
}
private void EmitExpression(BoundExpression expression, bool used)
{
if (expression == null)
{
return;
}
var constantValue = expression.ConstantValueOpt;
if (constantValue != null)
{
if (!used)
{
// unused constants have no side-effects.
return;
}
if ((object)expression.Type == null ||
(expression.Type.SpecialType != SpecialType.System_Decimal &&
!expression.Type.IsNullableType()))
{
EmitConstantExpression(expression.Type, constantValue, used, expression.Syntax);
return;
}
}
_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 (InsufficientExecutionStackException)
{
_diagnostics.Add(ErrorCode.ERR_InsufficientStack,
BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(expression));
throw new EmitCancelledException();
}
}
private void EmitExpressionCore(BoundExpression expression, bool used)
{
switch (expression.Kind)
{
case BoundKind.AssignmentOperator:
EmitAssignmentExpression((BoundAssignmentOperator)expression, used ? UseKind.UsedAsValue : UseKind.Unused);
break;
case BoundKind.Call:
EmitCallExpression((BoundCall)expression, used ? UseKind.UsedAsValue : UseKind.Unused);
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;
case BoundKind.ConvertedStackAllocExpression:
EmitConvertedStackAllocExpression((BoundConvertedStackAllocExpression)expression, used);
break;
case BoundKind.ReadOnlySpanFromArray:
EmitReadOnlySpanFromArrayExpression((BoundReadOnlySpanFromArray)expression, used);
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.PassByCopy:
EmitExpression(((BoundPassByCopy)expression).Expression, used);
break;
case BoundKind.Parameter:
if (used) // unused parameter has no side-effects
{
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:
if (used) // unused this has no side-effects
{
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:
if (used) // unused base has no side-effects
{
var thisType = _method.ContainingType;
_builder.EmitOpCode(ILOpCode.Ldarg_0);
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, omitBooleanConversion: false);
break;
case BoundKind.AsOperator:
EmitAsExpression((BoundAsOperator)expression, used);
break;
case BoundKind.DefaultExpression:
EmitDefaultExpression((BoundDefaultExpression)expression, used);
break;
case BoundKind.TypeOfOperator:
if (used) // unused typeof has no side-effects
{
EmitTypeOfExpression((BoundTypeOfOperator)expression);
}
break;
case BoundKind.SizeOfOperator:
if (used) // unused sizeof has no side-effects
{
EmitSizeOfExpression((BoundSizeOfOperator)expression);
}
break;
case BoundKind.ModuleVersionId:
Debug.Assert(used);
EmitModuleVersionIdLoad((BoundModuleVersionId)expression);
break;
case BoundKind.ModuleVersionIdString:
Debug.Assert(used);
EmitModuleVersionIdStringLoad();
break;
case BoundKind.InstrumentationPayloadRoot:
Debug.Assert(used);
EmitInstrumentationPayloadRootLoad((BoundInstrumentationPayloadRoot)expression);
break;
case BoundKind.MethodDefIndex:
Debug.Assert(used);
EmitMethodDefIndexExpression((BoundMethodDefIndex)expression);
break;
case BoundKind.MaximumMethodDefIndex:
Debug.Assert(used);
EmitMaximumMethodDefIndexExpression((BoundMaximumMethodDefIndex)expression);
break;
case BoundKind.SourceDocumentIndex:
Debug.Assert(used);
EmitSourceDocumentIndex((BoundSourceDocumentIndex)expression);
break;
case BoundKind.LocalId:
Debug.Assert(used);
EmitLocalIdExpression((BoundLocalId)expression);
break;
case BoundKind.ParameterId:
Debug.Assert(used);
EmitParameterIdExpression((BoundParameterId)expression);
break;
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;
case BoundKind.LoweredConditionalAccess:
EmitLoweredConditionalAccessExpression((BoundLoweredConditionalAccess)expression, used);
break;
case BoundKind.ConditionalReceiver:
EmitConditionalReceiver((BoundConditionalReceiver)expression, used);
break;
case BoundKind.ComplexConditionalReceiver:
EmitComplexConditionalReceiver((BoundComplexConditionalReceiver)expression, used);
break;
case BoundKind.PseudoVariable:
EmitPseudoVariableValue((BoundPseudoVariable)expression, used);
break;
case BoundKind.ThrowExpression:
EmitThrowExpression((BoundThrowExpression)expression, used);
break;
case BoundKind.FunctionPointerInvocation:
EmitCalli((BoundFunctionPointerInvocation)expression, used ? UseKind.UsedAsValue : UseKind.Unused);
break;
case BoundKind.FunctionPointerLoad:
EmitLoadFunction((BoundFunctionPointerLoad)expression, used);
break;
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);
}
}
private void EmitThrowExpression(BoundThrowExpression node, bool used)
{
this.EmitThrow(node.Expression);
// to satisfy invariants, we push a default value to pretend to adjust the stack height
EmitDefaultValue(node.Type, used, node.Syntax);
}
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);
if (used)
{
_builder.AdjustStack(-1);
}
_builder.MarkLabel(whenValueTypeLabel);
EmitExpression(expression.ValueTypeReceiver, used);
_builder.MarkLabel(doneLabel);
}
private void EmitLoweredConditionalAccessExpression(BoundLoweredConditionalAccess expression, bool used)
{
var receiver = expression.Receiver;
var receiverType = receiver.Type;
LocalDefinition receiverTemp = null;
Debug.Assert(!receiverType.IsValueType ||
(receiverType.IsNullableType() && expression.HasValueMethodOpt != null), "conditional receiver cannot be a struct");
var receiverConstant = receiver.ConstantValueOpt;
if (receiverConstant?.IsNull == false)
{
// const but not null, 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.
receiverTemp = EmitReceiverRef(receiver, AddressKind.ReadOnly);
EmitExpression(expression.WhenNotNull, used);
if (receiverTemp != null)
{
FreeTemp(receiverTemp);
}
return;
}
// labels
object whenNotNullLabel = new object();
object doneLabel = new object();
LocalDefinition cloneTemp = null;
var notConstrained = !receiverType.IsReferenceType && !receiverType.IsValueType;
// we need a copy if we deal with nonlocal value (to capture the value)
// or if we have a ref-constrained T (to do box just once)
// or if we deal with stack local (reads are destructive)
// or if we have default(T) (to do box just once)
var nullCheckOnCopy = (expression.ForceCopyOfNullableValueType && notConstrained &&
((TypeParameterSymbol)receiverType).EffectiveInterfacesNoUseSiteDiagnostics.IsEmpty) || // This could be a nullable value type, which must be copied in order to not mutate the original value
LocalRewriter.CanChangeValueBetweenReads(receiver, localsMayBeAssignedOrCaptured: false) ||
(receiverType.IsReferenceType && receiverType.TypeKind == TypeKind.TypeParameter) ||
(receiver.Kind == BoundKind.Local && IsStackLocal(((BoundLocal)receiver).LocalSymbol)) ||
(notConstrained && IsConditionalConstrainedCallThatMustUseTempForReferenceTypeReceiverWalker.Analyze(expression));
// ===== RECEIVER
if (nullCheckOnCopy)
{
if (notConstrained)
{
// if T happens to be a value type, it could be a target of mutating calls.
receiverTemp = EmitReceiverRef(receiver, AddressKind.Constrained);
if (receiverTemp is null)
{
// unconstrained case needs to handle case where T is actually a struct.
// such values are never nulls
// we will emit a check for such case, but the check is really a JIT-time
// 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);
_builder.EmitBranch(ILOpCode.Brtrue, whenNotNullLabel);
EmitLoadIndirect(receiverType, receiver.Syntax);
cloneTemp = AllocateTemp(receiverType, receiver.Syntax);
_builder.EmitLocalStore(cloneTemp);
_builder.EmitLocalAddress(cloneTemp);
_builder.EmitLocalLoad(cloneTemp);
EmitBox(receiverType, receiver.Syntax);
// here we have loaded a ref to a temp and its boxed value { &T, O }
}
else
{
// We are calling the expression on a copy of the target anyway,
// so even if T is a struct, we don't need to make sure we call the expression on the original target.
// We currently have an address on the stack. Duplicate it, and load the value of the address.
_builder.EmitOpCode(ILOpCode.Dup);
EmitLoadIndirect(receiverType, receiver.Syntax);
EmitBox(receiverType, receiver.Syntax);
}
}
else
{
// this does not need to be writeable
// we may call "HasValue" on this, but it is not mutating
var addressKind = AddressKind.ReadOnly;
receiverTemp = EmitReceiverRef(receiver, addressKind);
_builder.EmitOpCode(ILOpCode.Dup);
// here we have loaded two copies of a reference { O, O } or {&nub, &nub}
}
}
else
{
// 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);
// 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);
}
_builder.EmitBranch(ILOpCode.Brtrue, whenNotNullLabel);
// no longer need the temp if we are not holding a copy
if (receiverTemp != null && !nullCheckOnCopy)
{
FreeTemp(receiverTemp);
receiverTemp = null;
}
// ===== WHEN NULL
if (nullCheckOnCopy)
{
_builder.EmitOpCode(ILOpCode.Pop);
}
var whenNull = expression.WhenNullOpt;
if (whenNull == null)
{
EmitDefaultValue(expression.Type, used, expression.Syntax);
}
else
{
EmitExpression(whenNull, used);
}
_builder.EmitBranch(ILOpCode.Br, doneLabel);
// ===== WHEN NOT NULL
if (nullCheckOnCopy)
{
// 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.
_builder.AdjustStack(+1);
}
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.
_builder.AdjustStack(-1);
}
_builder.MarkLabel(whenNotNullLabel);
if (!nullCheckOnCopy)
{
Debug.Assert(receiverTemp == null);
// receiver may be used as target of a struct call (if T happens to be a struct)
receiverTemp = EmitReceiverRef(receiver, AddressKind.Constrained);
Debug.Assert(receiverTemp == null || receiver.IsDefaultValue());
}
EmitExpression(expression.WhenNotNull, used);
// ===== DONE
_builder.MarkLabel(doneLabel);
if (cloneTemp != null)
{
FreeTemp(cloneTemp);
}
if (receiverTemp != null)
{
FreeTemp(receiverTemp);
}
}
/// <summary>
/// We must use a temp when there is a chance that evaluation of the call arguments
/// could actually modify value of the reference type reciever. The call must use
/// the original (unmodified) receiver.
/// </summary>
private sealed class IsConditionalConstrainedCallThatMustUseTempForReferenceTypeReceiverWalker : BoundTreeWalkerWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator
{
private readonly BoundLoweredConditionalAccess _conditionalAccess;
private bool? _result;
private IsConditionalConstrainedCallThatMustUseTempForReferenceTypeReceiverWalker(BoundLoweredConditionalAccess conditionalAccess)
{
_conditionalAccess = conditionalAccess;
}
public static bool Analyze(BoundLoweredConditionalAccess conditionalAccess)
{
var walker = new IsConditionalConstrainedCallThatMustUseTempForReferenceTypeReceiverWalker(conditionalAccess);
walker.Visit(conditionalAccess.WhenNotNull);
Debug.Assert(walker._result.HasValue);
return walker._result.GetValueOrDefault();
}
public override BoundNode Visit(BoundNode node)
{
if (_result.HasValue)
{
return null;
}
return base.Visit(node);
}
public override BoundNode VisitCall(BoundCall node)
{
if (node.ReceiverOpt is BoundConditionalReceiver { Id: var id } && id == _conditionalAccess.Id)
{
Debug.Assert(!_result.HasValue);
_result = !IsSafeToDereferenceReceiverRefAfterEvaluatingArguments(node.Arguments);
return null;
}
return base.VisitCall(node);
}
public override BoundNode VisitConditionalReceiver(BoundConditionalReceiver node)
{
if (node.Id == _conditionalAccess.Id)
{
Debug.Assert(!_result.HasValue);
_result = false;
return null;
}
return base.VisitConditionalReceiver(node);
}
}
private void EmitConditionalReceiver(BoundConditionalReceiver expression, bool used)
{
Debug.Assert(!expression.Type.IsValueType);
if (!expression.Type.IsReferenceType)
{
EmitLoadIndirect(expression.Type, expression.Syntax);
}
EmitPopIfUnused(used);
}
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
var temp = EmitAddress(expression.Operand, AddressKind.Writeable);
Debug.Assert(temp == null, "makeref should not create temps");
_builder.EmitOpCode(ILOpCode.Mkrefany);
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);
_builder.EmitOpCode(ILOpCode.Refanytype);
_builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0);
var getTypeMethod = expression.GetTypeFromHandle;
Debug.Assert((object)getTypeMethod != null);
EmitSymbolToken(getTypeMethod, expression.Syntax, null);
EmitPopIfUnused(used);
}
private void EmitArgList(bool used)
{
_builder.EmitOpCode(ILOpCode.Arglist);
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)
{
switch (refKind)
{
case RefKind.None:
EmitExpression(argument, true);
break;
case RefKind.In:
var temp = EmitAddress(argument, AddressKind.ReadOnly);
AddExpressionTemp(temp);
break;
default:
// 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);
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);
}
break;
}
}
private void EmitAddressOfExpression(BoundAddressOfOperator expression, bool used)
{
// NOTE: passing "ReadOnlyStrict" here.
// we should not get an address of a copy if at all possible
var temp = EmitAddress(expression.Operand, AddressKind.ReadOnlyStrict);
Debug.Assert(temp == null, "If the operand is addressable, then a temp shouldn't be required.");
if (used && !expression.IsManaged)
{
// 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).
_builder.EmitOpCode(ILOpCode.Conv_u);
}
EmitPopIfUnused(used);
}
private void EmitPointerIndirectionOperator(BoundPointerIndirectionOperator expression, bool used)
{
EmitExpression(expression.Operand, used: true);
if (!expression.RefersToLocation)
{
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)
{
_builder.EmitOpCode(ILOpCode.Dup);
}
}
else
{
_builder.EmitOpCode(ILOpCode.Dup);
// must read in case if it is a null ref
EmitLoadIndirect(expression.Type, expression.Syntax);
EmitPopIfUnused(used);
}
}
private void EmitDelegateCreationExpression(BoundDelegateCreationExpression expression, bool used)
{
var mg = expression.Argument as BoundMethodGroup;
var receiver = mg != null ? mg.ReceiverOpt : expression.Argument;
var meth = expression.MethodOpt ?? receiver.Type.DelegateInvokeMethod();
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);
_builder.EmitOpCode(ILOpCode.Ldarg_0);
if (thisType.IsValueType)
{
EmitLoadIndirect(thisType, thisRef.Syntax);
}
}
private void EmitPseudoVariableValue(BoundPseudoVariable expression, bool used)
{
EmitExpression(expression.EmitExpressions.GetValue(expression, _diagnostics.DiagnosticBag), used);
}
private void EmitSequencePointExpression(BoundSequencePointExpression node, bool used)
{
EmitSequencePoint(node);
// used is true to ensure that something is emitted
EmitExpression(node.Expression, used: true);
EmitPopIfUnused(used);
}
private void EmitSequencePoint(BoundSequencePointExpression node)
{
var syntax = node.Syntax;
if (_emitPdbSequencePoints)
{
if (syntax == null)
{
EmitHiddenSequencePoint();
}
else
{
EmitSequencePoint(syntax);
}
}
}
private void EmitSequenceExpression(BoundSequence sequence, bool used)
{
DefineLocals(sequence);
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);
}
// sequence is used as a value, can release all locals
FreeLocals(sequence);
}
private void DefineLocals(BoundSequence sequence)
{
if (sequence.Locals.IsEmpty)
{
return;
}
_builder.OpenLocalScope();
foreach (var local in sequence.Locals)
{
DefineLocal(local, sequence.Syntax);
}
}
private void FreeLocals(BoundSequence sequence)
{
if (sequence.Locals.IsEmpty)
{
return;
}
_builder.CloseLocalScope();
foreach (var local in sequence.Locals)
{
FreeLocal(local);
}
}
/// <summary>
/// Defines sequence locals and record them so that they could be retained for the duration of the encompassing expression
/// Use this when taking a reference of the sequence, which can indirectly refer to any of its locals.
/// </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 expression.
/// 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;
}
_builder.CloseLocalScope();
}
private void EmitSideEffects(BoundSequence sequence)
{
var sideEffects = sequence.SideEffects;
if (!sideEffects.IsDefaultOrEmpty)
{
foreach (var se in sideEffects)
{
EmitExpression(se, false);
}
}
}
private void EmitArguments(ImmutableArray<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<RefKind> argRefKindsOpt)
{
// 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");
Debug.Assert(parameters.All(p => p.RefKind == RefKind.None) || !argRefKindsOpt.IsDefault, "there are nontrivial parameters, so we must have argRefKinds");
Debug.Assert(argRefKindsOpt.IsDefault || argRefKindsOpt.Length == arguments.Length, "if we have argRefKinds, we should have one for each argument");
for (int i = 0; i < arguments.Length; i++)
{
RefKind argRefKind = GetArgumentRefKind(arguments, parameters, argRefKindsOpt, i);
EmitArgument(arguments[i], argRefKind);
}
}
/// <summary>
/// Computes the desired refkind of the argument.
/// Considers all the cases - where ref kinds are explicit, omitted, vararg cases.
/// </summary>
internal static RefKind GetArgumentRefKind(ImmutableArray<BoundExpression> arguments, ImmutableArray<ParameterSymbol> parameters, ImmutableArray<RefKind> argRefKindsOpt, int i)
{
RefKind argRefKind;
if (i < parameters.Length)
{
if (!argRefKindsOpt.IsDefault && i < argRefKindsOpt.Length)
{
// if we have an explicit refKind for the given argument, use that
argRefKind = argRefKindsOpt[i];
Debug.Assert(argRefKind == parameters[i].RefKind ||
argRefKind == RefKindExtensions.StrictIn && parameters[i].RefKind == RefKind.In,
"in Emit the argument RefKind must be compatible with the corresponding parameter");
}
else
{
// otherwise fallback to the refKind of the parameter
argRefKind = parameters[i].RefKind;
}
}
else
{
// vararg case
Debug.Assert(arguments[i].Kind == BoundKind.ArgListOperator);
argRefKind = RefKind.None;
}
return argRefKind;
}
private void EmitArrayElementLoad(BoundArrayAccess arrayAccess, bool used)
{
EmitExpression(arrayAccess.Expression, used: true);
EmitArrayIndices(arrayAccess.Indices);
if (((ArrayTypeSymbol)arrayAccess.Expression.Type).IsSZArray)
{
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:
_builder.EmitOpCode(ILOpCode.Ldelem_i1);
break;
case Microsoft.Cci.PrimitiveTypeCode.Boolean: