2 // codegen.cs: The code generator
5 // Miguel de Icaza (miguel@ximian.com)
6 // Marek Safar (marek.safar@gmail.com)
8 // Copyright 2001, 2002, 2003 Ximian, Inc.
9 // Copyright 2004 Novell, Inc.
10 // Copyright 2011 Xamarin Inc
14 using System.Collections.Generic;
15 using Mono.CompilerServices.SymbolWriter;
18 using MetaType = IKVM.Reflection.Type;
19 using IKVM.Reflection;
20 using IKVM.Reflection.Emit;
22 using MetaType = System.Type;
23 using System.Reflection;
24 using System.Reflection.Emit;
30 /// An Emit Context is created for each body of code (from methods,
31 /// properties bodies, indexer bodies or constructor bodies)
33 public class EmitContext : BuilderContext
35 // TODO: Has to be private
36 public readonly ILGenerator ig;
39 /// The value that is allowed to be returned or NULL if there is no
42 readonly TypeSpec return_type;
45 /// Keeps track of the Type to LocalBuilder temporary storage created
46 /// to store structures (used to compute the address of the structure
47 /// value on structure method invocations)
49 Dictionary<TypeSpec, object> temporary_storage;
52 /// The location where we store the return value.
54 public LocalBuilder return_value;
58 /// Current loop begin and end labels.
60 public Label LoopBegin, LoopEnd;
63 /// Default target in a switch statement. Only valid if
66 public Label DefaultTarget;
69 /// If this is non-null, points to the current switch statement
74 /// Whether we are inside an anonymous method.
76 public AnonymousExpression CurrentAnonymousMethod;
78 readonly IMemberContext member_context;
80 readonly SourceMethodBuilder methodSymbols;
82 DynamicSiteClass dynamic_site_container;
86 List<IExpressionCleanup> epilogue_expressions;
88 public EmitContext (IMemberContext rc, ILGenerator ig, TypeSpec return_type, SourceMethodBuilder methodSymbols)
90 this.member_context = rc;
92 this.return_type = return_type;
94 if (rc.Module.Compiler.Settings.Checked)
95 flags |= Options.CheckedScope;
97 if (methodSymbols != null) {
98 this.methodSymbols = methodSymbols;
99 if (!rc.Module.Compiler.Settings.Optimize)
100 flags |= Options.AccurateDebugInfo;
102 flags |= Options.OmitDebugInfo;
106 ig.__CleverExceptionBlockAssistance ();
112 internal AsyncTaskStorey AsyncTaskStorey {
114 return CurrentAnonymousMethod.Storey as AsyncTaskStorey;
118 public BuiltinTypes BuiltinTypes {
120 return MemberContext.Module.Compiler.BuiltinTypes;
124 public ConditionalAccessContext ConditionalAccess { get; set; }
126 public TypeSpec CurrentType {
127 get { return member_context.CurrentType; }
130 public TypeParameters CurrentTypeParameters {
131 get { return member_context.CurrentTypeParameters; }
134 public MemberCore CurrentTypeDefinition {
135 get { return member_context.CurrentMemberDefinition; }
138 public bool EmitAccurateDebugInfo {
140 return (flags & Options.AccurateDebugInfo) != 0;
144 public bool HasMethodSymbolBuilder {
146 return methodSymbols != null;
150 public bool HasReturnLabel {
152 return return_label.HasValue;
156 public bool IsStatic {
157 get { return member_context.IsStatic; }
160 public bool IsStaticConstructor {
162 return member_context.IsStatic && (flags & Options.ConstructorScope) != 0;
166 public bool IsAnonymousStoreyMutateRequired {
168 return CurrentAnonymousMethod != null &&
169 CurrentAnonymousMethod.Storey != null &&
170 CurrentAnonymousMethod.Storey.Mutator != null;
174 public IMemberContext MemberContext {
176 return member_context;
180 public ModuleContainer Module {
182 return member_context.Module;
186 public bool NotifyEvaluatorOnStore {
188 return Module.Evaluator != null && Module.Evaluator.ModificationListener != null;
192 // Has to be used for specific emitter errors only any
193 // possible resolver errors have to be reported during Resolve
194 public Report Report {
196 return member_context.Module.Compiler.Report;
200 public TypeSpec ReturnType {
207 // The label where we have to jump before leaving the context
209 public Label ReturnLabel {
211 return return_label.Value;
215 public List<IExpressionCleanup> StatementEpilogue {
217 return epilogue_expressions;
221 public LocalVariable AsyncThrowVariable { get; set; }
223 public List<TryFinally> TryFinallyUnwind { get; set; }
225 public Label RecursivePatternLabel { get; set; }
229 public void AddStatementEpilog (IExpressionCleanup cleanupExpression)
231 if (epilogue_expressions == null) {
232 epilogue_expressions = new List<IExpressionCleanup> ();
233 } else if (epilogue_expressions.Contains (cleanupExpression)) {
237 epilogue_expressions.Add (cleanupExpression);
240 public void AssertEmptyStack ()
243 if (ig.__StackHeight != 0)
244 throw new InternalErrorException ("Await yields with non-empty stack in `{0}",
245 member_context.GetSignatureForError ());
250 /// This is called immediately before emitting an IL opcode to tell the symbol
251 /// writer to which source line this opcode belongs.
253 public bool Mark (Location loc)
255 if ((flags & Options.OmitDebugInfo) != 0)
258 if (loc.IsNull || methodSymbols == null)
261 var sf = loc.SourceFile;
262 if (sf.IsHiddenLocation (loc))
265 methodSymbols.MarkSequencePoint (ig.ILOffset, sf.SourceFileEntry, loc.Row, loc.Column, false);
269 public void MarkCallEntry (Location loc)
271 if (!EmitAccurateDebugInfo)
275 // TODO: This should emit different kind of sequence point to make
276 // step-over work for statement over multiple lines
278 // Debugging experience for Foo (A () + B ()) where A and B are
279 // on separate lines is not great
284 public void DefineLocalVariable (string name, LocalBuilder builder)
286 if ((flags & Options.OmitDebugInfo) != 0)
289 methodSymbols.AddLocal (builder.LocalIndex, name);
292 public void BeginCatchBlock (TypeSpec type)
294 if (IsAnonymousStoreyMutateRequired)
295 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
297 ig.BeginCatchBlock (type.GetMetaInfo ());
300 public void BeginFilterHandler ()
302 ig.BeginCatchBlock (null);
305 public void BeginExceptionBlock ()
307 ig.BeginExceptionBlock ();
310 public void BeginExceptionFilterBlock ()
312 ig.BeginExceptFilterBlock ();
315 public void BeginFinallyBlock ()
317 ig.BeginFinallyBlock ();
320 public void BeginScope ()
322 if ((flags & Options.OmitDebugInfo) != 0)
325 methodSymbols.StartBlock (CodeBlockEntry.Type.Lexical, ig.ILOffset);
328 public void BeginCompilerScope ()
330 if ((flags & Options.OmitDebugInfo) != 0)
333 methodSymbols.StartBlock (CodeBlockEntry.Type.CompilerGenerated, ig.ILOffset);
336 public void EndExceptionBlock ()
338 ig.EndExceptionBlock ();
341 public void EndScope ()
343 if ((flags & Options.OmitDebugInfo) != 0)
346 methodSymbols.EndBlock (ig.ILOffset);
349 public void CloseConditionalAccess (TypeSpec type)
352 Emit (OpCodes.Newobj, Nullable.NullableInfo.GetConstructor (type));
354 MarkLabel (ConditionalAccess.EndLabel);
355 ConditionalAccess = null;
359 // Creates a nested container in this context for all dynamic compiler generated stuff
361 internal DynamicSiteClass CreateDynamicSite ()
363 if (dynamic_site_container == null) {
364 var mc = member_context.CurrentMemberDefinition as MemberBase;
365 dynamic_site_container = new DynamicSiteClass (CurrentTypeDefinition.Parent.PartialContainer, mc, member_context.CurrentTypeParameters);
367 CurrentTypeDefinition.Module.AddCompilerGeneratedClass (dynamic_site_container);
368 dynamic_site_container.CreateContainer ();
369 dynamic_site_container.DefineContainer ();
370 dynamic_site_container.Define ();
372 var inflator = new TypeParameterInflator (Module, CurrentType, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes);
373 var inflated = dynamic_site_container.CurrentType.InflateMember (inflator);
374 CurrentType.MemberCache.AddMember (inflated);
377 return dynamic_site_container;
380 public Label CreateReturnLabel ()
382 if (!return_label.HasValue)
383 return_label = DefineLabel ();
385 return return_label.Value;
388 public LocalBuilder DeclareLocal (TypeSpec type, bool pinned)
390 if (IsAnonymousStoreyMutateRequired)
391 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
393 return ig.DeclareLocal (type.GetMetaInfo (), pinned);
396 public Label DefineLabel ()
398 return ig.DefineLabel ();
402 // Creates temporary field in current async storey
404 public StackFieldExpr GetTemporaryField (TypeSpec type, bool initializedFieldRequired = false)
406 var f = AsyncTaskStorey.AddCapturedLocalVariable (type, initializedFieldRequired);
407 var fexpr = new StackFieldExpr (f);
408 fexpr.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location.Null);
412 public void MarkLabel (Label label)
414 ig.MarkLabel (label);
417 public void Emit (OpCode opcode)
422 public void Emit (OpCode opcode, LocalBuilder local)
424 ig.Emit (opcode, local);
427 public void Emit (OpCode opcode, string arg)
429 ig.Emit (opcode, arg);
432 public void Emit (OpCode opcode, double arg)
434 ig.Emit (opcode, arg);
437 public void Emit (OpCode opcode, float arg)
439 ig.Emit (opcode, arg);
442 public void Emit (OpCode opcode, Label label)
444 ig.Emit (opcode, label);
447 public void Emit (OpCode opcode, Label[] labels)
449 ig.Emit (opcode, labels);
452 public void Emit (OpCode opcode, TypeSpec type)
454 if (IsAnonymousStoreyMutateRequired)
455 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
457 ig.Emit (opcode, type.GetMetaInfo ());
460 public void Emit (OpCode opcode, FieldSpec field)
462 if (IsAnonymousStoreyMutateRequired)
463 field = field.Mutate (CurrentAnonymousMethod.Storey.Mutator);
465 ig.Emit (opcode, field.GetMetaInfo ());
468 public void Emit (OpCode opcode, MethodSpec method)
470 if (IsAnonymousStoreyMutateRequired)
471 method = method.Mutate (CurrentAnonymousMethod.Storey.Mutator);
473 if (method.IsConstructor)
474 ig.Emit (opcode, (ConstructorInfo) method.GetMetaInfo ());
476 ig.Emit (opcode, (MethodInfo) method.GetMetaInfo ());
479 // TODO: REMOVE breaks mutator
480 public void Emit (OpCode opcode, MethodInfo method)
482 ig.Emit (opcode, method);
485 public void Emit (OpCode opcode, MethodSpec method, MetaType[] vargs)
487 // TODO MemberCache: This should mutate too
488 ig.EmitCall (opcode, (MethodInfo) method.GetMetaInfo (), vargs);
491 public void EmitArrayNew (ArrayContainer ac)
494 var type = IsAnonymousStoreyMutateRequired ?
495 CurrentAnonymousMethod.Storey.Mutator.Mutate (ac.Element) :
498 ig.Emit (OpCodes.Newarr, type.GetMetaInfo ());
500 if (IsAnonymousStoreyMutateRequired)
501 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
503 ig.Emit (OpCodes.Newobj, ac.GetConstructor ());
507 public void EmitArrayAddress (ArrayContainer ac)
510 if (IsAnonymousStoreyMutateRequired)
511 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
513 ig.Emit (OpCodes.Call, ac.GetAddressMethod ());
515 var type = IsAnonymousStoreyMutateRequired ?
516 CurrentAnonymousMethod.Storey.Mutator.Mutate (ac.Element) :
519 ig.Emit (OpCodes.Ldelema, type.GetMetaInfo ());
524 // Emits the right opcode to load from an array
526 public void EmitArrayLoad (ArrayContainer ac)
529 if (IsAnonymousStoreyMutateRequired)
530 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
532 ig.Emit (OpCodes.Call, ac.GetGetMethod ());
537 var type = ac.Element;
538 if (type.Kind == MemberKind.Enum)
539 type = EnumSpec.GetUnderlyingType (type);
541 switch (type.BuiltinType) {
542 case BuiltinTypeSpec.Type.Bool:
544 // bool array can actually store any byte value in underlying byte slot
545 // and C# spec does not specify any normalization rule, except the result
548 case BuiltinTypeSpec.Type.Byte:
549 ig.Emit (OpCodes.Ldelem_U1);
551 case BuiltinTypeSpec.Type.SByte:
552 ig.Emit (OpCodes.Ldelem_I1);
554 case BuiltinTypeSpec.Type.Short:
555 ig.Emit (OpCodes.Ldelem_I2);
557 case BuiltinTypeSpec.Type.UShort:
558 case BuiltinTypeSpec.Type.Char:
559 ig.Emit (OpCodes.Ldelem_U2);
561 case BuiltinTypeSpec.Type.Int:
562 ig.Emit (OpCodes.Ldelem_I4);
564 case BuiltinTypeSpec.Type.UInt:
565 ig.Emit (OpCodes.Ldelem_U4);
567 case BuiltinTypeSpec.Type.ULong:
568 case BuiltinTypeSpec.Type.Long:
569 ig.Emit (OpCodes.Ldelem_I8);
571 case BuiltinTypeSpec.Type.Float:
572 ig.Emit (OpCodes.Ldelem_R4);
574 case BuiltinTypeSpec.Type.Double:
575 ig.Emit (OpCodes.Ldelem_R8);
577 case BuiltinTypeSpec.Type.IntPtr:
578 ig.Emit (OpCodes.Ldelem_I);
582 case MemberKind.Struct:
583 if (IsAnonymousStoreyMutateRequired)
584 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
586 ig.Emit (OpCodes.Ldelema, type.GetMetaInfo ());
587 ig.Emit (OpCodes.Ldobj, type.GetMetaInfo ());
589 case MemberKind.TypeParameter:
590 if (IsAnonymousStoreyMutateRequired)
591 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
593 ig.Emit (OpCodes.Ldelem, type.GetMetaInfo ());
595 case MemberKind.PointerType:
596 ig.Emit (OpCodes.Ldelem_I);
599 ig.Emit (OpCodes.Ldelem_Ref);
607 // Emits the right opcode to store to an array
609 public void EmitArrayStore (ArrayContainer ac)
612 if (IsAnonymousStoreyMutateRequired)
613 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
615 ig.Emit (OpCodes.Call, ac.GetSetMethod ());
619 var type = ac.Element;
621 if (type.Kind == MemberKind.Enum)
622 type = EnumSpec.GetUnderlyingType (type);
624 switch (type.BuiltinType) {
625 case BuiltinTypeSpec.Type.Byte:
626 case BuiltinTypeSpec.Type.SByte:
627 case BuiltinTypeSpec.Type.Bool:
628 Emit (OpCodes.Stelem_I1);
630 case BuiltinTypeSpec.Type.Short:
631 case BuiltinTypeSpec.Type.UShort:
632 case BuiltinTypeSpec.Type.Char:
633 Emit (OpCodes.Stelem_I2);
635 case BuiltinTypeSpec.Type.Int:
636 case BuiltinTypeSpec.Type.UInt:
637 Emit (OpCodes.Stelem_I4);
639 case BuiltinTypeSpec.Type.Long:
640 case BuiltinTypeSpec.Type.ULong:
641 Emit (OpCodes.Stelem_I8);
643 case BuiltinTypeSpec.Type.Float:
644 Emit (OpCodes.Stelem_R4);
646 case BuiltinTypeSpec.Type.Double:
647 Emit (OpCodes.Stelem_R8);
652 case MemberKind.Struct:
653 Emit (OpCodes.Stobj, type);
655 case MemberKind.TypeParameter:
656 Emit (OpCodes.Stelem, type);
658 case MemberKind.PointerType:
659 Emit (OpCodes.Stelem_I);
662 Emit (OpCodes.Stelem_Ref);
667 public void EmitInt (int i)
672 void EmitIntConstant (int i)
676 ig.Emit (OpCodes.Ldc_I4_M1);
680 ig.Emit (OpCodes.Ldc_I4_0);
684 ig.Emit (OpCodes.Ldc_I4_1);
688 ig.Emit (OpCodes.Ldc_I4_2);
692 ig.Emit (OpCodes.Ldc_I4_3);
696 ig.Emit (OpCodes.Ldc_I4_4);
700 ig.Emit (OpCodes.Ldc_I4_5);
704 ig.Emit (OpCodes.Ldc_I4_6);
708 ig.Emit (OpCodes.Ldc_I4_7);
712 ig.Emit (OpCodes.Ldc_I4_8);
716 if (i >= -128 && i <= 127) {
717 ig.Emit (OpCodes.Ldc_I4_S, (sbyte) i);
719 ig.Emit (OpCodes.Ldc_I4, i);
724 public void EmitLong (long l)
726 if (l >= int.MinValue && l <= int.MaxValue) {
727 EmitIntConstant (unchecked ((int) l));
728 ig.Emit (OpCodes.Conv_I8);
729 } else if (l >= 0 && l <= uint.MaxValue) {
730 EmitIntConstant (unchecked ((int) l));
731 ig.Emit (OpCodes.Conv_U8);
733 ig.Emit (OpCodes.Ldc_I8, l);
738 // Load the object from the pointer.
740 public void EmitLoadFromPtr (TypeSpec type)
742 if (type.Kind == MemberKind.Enum)
743 type = EnumSpec.GetUnderlyingType (type);
745 switch (type.BuiltinType) {
746 case BuiltinTypeSpec.Type.Int:
747 ig.Emit (OpCodes.Ldind_I4);
749 case BuiltinTypeSpec.Type.UInt:
750 ig.Emit (OpCodes.Ldind_U4);
752 case BuiltinTypeSpec.Type.Short:
753 ig.Emit (OpCodes.Ldind_I2);
755 case BuiltinTypeSpec.Type.UShort:
756 case BuiltinTypeSpec.Type.Char:
757 ig.Emit (OpCodes.Ldind_U2);
759 case BuiltinTypeSpec.Type.Byte:
760 ig.Emit (OpCodes.Ldind_U1);
762 case BuiltinTypeSpec.Type.SByte:
763 case BuiltinTypeSpec.Type.Bool:
764 ig.Emit (OpCodes.Ldind_I1);
766 case BuiltinTypeSpec.Type.ULong:
767 case BuiltinTypeSpec.Type.Long:
768 ig.Emit (OpCodes.Ldind_I8);
770 case BuiltinTypeSpec.Type.Float:
771 ig.Emit (OpCodes.Ldind_R4);
773 case BuiltinTypeSpec.Type.Double:
774 ig.Emit (OpCodes.Ldind_R8);
776 case BuiltinTypeSpec.Type.IntPtr:
777 ig.Emit (OpCodes.Ldind_I);
781 case MemberKind.Struct:
782 case MemberKind.TypeParameter:
783 if (IsAnonymousStoreyMutateRequired)
784 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
786 ig.Emit (OpCodes.Ldobj, type.GetMetaInfo ());
788 case MemberKind.PointerType:
789 ig.Emit (OpCodes.Ldind_I);
792 ig.Emit (OpCodes.Ldind_Ref);
799 public void EmitNull ()
801 ig.Emit (OpCodes.Ldnull);
804 public void EmitArgumentAddress (int pos)
809 if (pos > byte.MaxValue)
810 ig.Emit (OpCodes.Ldarga, pos);
812 ig.Emit (OpCodes.Ldarga_S, (byte) pos);
815 public void EmitArgumentLoad (int pos)
821 case 0: ig.Emit (OpCodes.Ldarg_0); break;
822 case 1: ig.Emit (OpCodes.Ldarg_1); break;
823 case 2: ig.Emit (OpCodes.Ldarg_2); break;
824 case 3: ig.Emit (OpCodes.Ldarg_3); break;
826 if (pos > byte.MaxValue)
827 ig.Emit (OpCodes.Ldarg, pos);
829 ig.Emit (OpCodes.Ldarg_S, (byte) pos);
834 public void EmitArgumentStore (int pos)
839 if (pos > byte.MaxValue)
840 ig.Emit (OpCodes.Starg, pos);
842 ig.Emit (OpCodes.Starg_S, (byte) pos);
846 // The stack contains the pointer and the value of type `type'
848 public void EmitStoreFromPtr (TypeSpec type)
851 type = EnumSpec.GetUnderlyingType (type);
853 switch (type.BuiltinType) {
854 case BuiltinTypeSpec.Type.Int:
855 case BuiltinTypeSpec.Type.UInt:
856 ig.Emit (OpCodes.Stind_I4);
858 case BuiltinTypeSpec.Type.Long:
859 case BuiltinTypeSpec.Type.ULong:
860 ig.Emit (OpCodes.Stind_I8);
862 case BuiltinTypeSpec.Type.Char:
863 case BuiltinTypeSpec.Type.Short:
864 case BuiltinTypeSpec.Type.UShort:
865 ig.Emit (OpCodes.Stind_I2);
867 case BuiltinTypeSpec.Type.Float:
868 ig.Emit (OpCodes.Stind_R4);
870 case BuiltinTypeSpec.Type.Double:
871 ig.Emit (OpCodes.Stind_R8);
873 case BuiltinTypeSpec.Type.Byte:
874 case BuiltinTypeSpec.Type.SByte:
875 case BuiltinTypeSpec.Type.Bool:
876 ig.Emit (OpCodes.Stind_I1);
878 case BuiltinTypeSpec.Type.IntPtr:
879 ig.Emit (OpCodes.Stind_I);
884 case MemberKind.Struct:
885 case MemberKind.TypeParameter:
886 if (IsAnonymousStoreyMutateRequired)
887 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
889 ig.Emit (OpCodes.Stobj, type.GetMetaInfo ());
891 case MemberKind.PointerType:
892 ig.Emit (OpCodes.Stind_I);
895 ig.Emit (OpCodes.Stind_Ref);
900 public void EmitThis ()
902 ig.Emit (OpCodes.Ldarg_0);
905 public void EmitEpilogue ()
907 if (epilogue_expressions == null)
910 foreach (var e in epilogue_expressions)
911 e.EmitCleanup (this);
913 epilogue_expressions = null;
917 /// Returns a temporary storage for a variable of type t as
918 /// a local variable in the current body.
920 public LocalBuilder GetTemporaryLocal (TypeSpec t)
922 if (temporary_storage != null) {
924 if (temporary_storage.TryGetValue (t, out o)) {
925 if (o is Stack<LocalBuilder>) {
926 var s = (Stack<LocalBuilder>) o;
927 o = s.Count == 0 ? null : s.Pop ();
929 temporary_storage.Remove (t);
933 return (LocalBuilder) o;
935 return DeclareLocal (t, false);
938 public void FreeTemporaryLocal (LocalBuilder b, TypeSpec t)
940 if (temporary_storage == null) {
941 temporary_storage = new Dictionary<TypeSpec, object> (ReferenceEquality<TypeSpec>.Default);
942 temporary_storage.Add (t, b);
947 if (!temporary_storage.TryGetValue (t, out o)) {
948 temporary_storage.Add (t, b);
951 var s = o as Stack<LocalBuilder>;
953 s = new Stack<LocalBuilder> ();
954 s.Push ((LocalBuilder)o);
955 temporary_storage [t] = s;
961 /// ReturnValue creates on demand the LocalBuilder for the
962 /// return value from the function. By default this is not
963 /// used. This is only required when returns are found inside
964 /// Try or Catch statements.
966 /// This method is typically invoked from the Emit phase, so
967 /// we allow the creation of a return label if it was not
968 /// requested during the resolution phase. Could be cleaned
969 /// up, but it would replicate a lot of logic in the Emit phase
970 /// of the code that uses it.
972 public LocalBuilder TemporaryReturn ()
974 if (return_value == null){
975 return_value = DeclareLocal (return_type, false);
982 public class ConditionalAccessContext
984 public ConditionalAccessContext (TypeSpec type, Label endLabel)
990 public bool Statement { get; set; }
991 public Label EndLabel { get; private set; }
992 public TypeSpec Type { get; private set; }
997 public Expression InstanceExpression;
1000 // When call has to leave an extra copy of all arguments on the stack
1002 public bool DuplicateArguments;
1005 // Does not emit InstanceExpression load when InstanceExpressionOnStack
1006 // is set. Used by compound assignments.
1008 public bool InstanceExpressionOnStack;
1011 // Any of arguments contains await expression
1013 public bool HasAwaitArguments;
1015 public bool ConditionalAccess;
1018 // When dealing with await arguments the original arguments are converted
1019 // into a new set with hoisted stack results
1021 public Arguments EmittedArguments;
1023 public void Emit (EmitContext ec, MethodSpec method, Arguments Arguments, Location loc)
1025 EmitPredefined (ec, method, Arguments, false, loc);
1028 public void EmitStatement (EmitContext ec, MethodSpec method, Arguments Arguments, Location loc)
1030 EmitPredefined (ec, method, Arguments, true, loc);
1033 public void EmitPredefined (EmitContext ec, MethodSpec method, Arguments Arguments, bool statement = false, Location? loc = null)
1035 Expression instance_copy = null;
1037 if (!HasAwaitArguments && ec.HasSet (BuilderContext.Options.AsyncBody)) {
1038 HasAwaitArguments = Arguments != null && Arguments.ContainsEmitWithAwait ();
1039 if (HasAwaitArguments && InstanceExpressionOnStack) {
1040 throw new NotSupportedException ();
1045 LocalTemporary lt = null;
1047 if (method.IsStatic) {
1048 call_op = OpCodes.Call;
1050 call_op = IsVirtualCallRequired (InstanceExpression, method) ? OpCodes.Callvirt : OpCodes.Call;
1052 if (HasAwaitArguments) {
1053 instance_copy = InstanceExpression.EmitToField (ec);
1054 var ie = new InstanceEmitter (instance_copy, IsAddressCall (instance_copy, call_op, method.DeclaringType));
1056 if (Arguments == null) {
1057 ie.EmitLoad (ec, true);
1059 } else if (!InstanceExpressionOnStack) {
1060 var ie = new InstanceEmitter (InstanceExpression, IsAddressCall (InstanceExpression, call_op, method.DeclaringType));
1061 ie.Emit (ec, ConditionalAccess);
1063 if (DuplicateArguments) {
1064 ec.Emit (OpCodes.Dup);
1065 if (Arguments != null && Arguments.Count != 0) {
1066 lt = new LocalTemporary (ie.GetStackType (ec));
1074 if (Arguments != null && !InstanceExpressionOnStack) {
1075 EmittedArguments = Arguments.Emit (ec, DuplicateArguments, HasAwaitArguments);
1076 if (EmittedArguments != null) {
1077 if (instance_copy != null) {
1078 var ie = new InstanceEmitter (instance_copy, IsAddressCall (instance_copy, call_op, method.DeclaringType));
1079 ie.Emit (ec, ConditionalAccess);
1085 EmittedArguments.Emit (ec);
1089 if (call_op == OpCodes.Callvirt && (InstanceExpression.Type.IsGenericParameter || InstanceExpression.Type.IsStructOrEnum)) {
1090 ec.Emit (OpCodes.Constrained, InstanceExpression.Type);
1095 // Emit explicit sequence point for expressions like Foo.Bar () to help debugger to
1096 // break at right place when LHS expression can be stepped-into
1098 ec.MarkCallEntry (loc.Value);
1102 // Set instance expression to actual result expression. When it contains await it can be
1103 // picked up by caller
1105 InstanceExpression = instance_copy;
1107 if (method.Parameters.HasArglist) {
1108 var varargs_types = GetVarargsTypes (method, Arguments);
1109 ec.Emit (call_op, method, varargs_types);
1114 // and DoFoo is not virtual, you can omit the callvirt,
1115 // because you don't need the null checking behavior.
1117 ec.Emit (call_op, method);
1121 // Pop the return value if there is one and stack should be empty
1123 if (statement && method.ReturnType.Kind != MemberKind.Void)
1124 ec.Emit (OpCodes.Pop);
1127 static MetaType[] GetVarargsTypes (MethodSpec method, Arguments arguments)
1129 AParametersCollection pd = method.Parameters;
1131 Argument a = arguments[pd.Count - 1];
1132 Arglist list = (Arglist) a.Expr;
1134 return list.ArgumentTypes;
1138 // Used to decide whether call or callvirt is needed
1140 static bool IsVirtualCallRequired (Expression instance, MethodSpec method)
1143 // There are 2 scenarious where we emit callvirt
1145 // Case 1: A method is virtual and it's not used to call base
1146 // Case 2: A method instance expression can be null. In this casen callvirt ensures
1147 // correct NRE exception when the method is called
1149 var decl_type = method.DeclaringType;
1150 if (decl_type.IsStruct || decl_type.IsEnum)
1153 if (instance is BaseThis)
1157 // It's non-virtual and will never be null and it can be determined
1158 // whether it's known value or reference type by verifier
1160 if (!method.IsVirtual && Expression.IsNeverNull (instance) && !instance.Type.IsGenericParameter)
1166 static bool IsAddressCall (Expression instance, OpCode callOpcode, TypeSpec declaringType)
1168 var instance_type = instance.Type;
1169 return (instance_type.IsStructOrEnum && (callOpcode == OpCodes.Callvirt || (callOpcode == OpCodes.Call && declaringType.IsStruct))) ||
1170 instance_type.IsGenericParameter || declaringType.IsNullableType;
1174 public struct InstanceEmitter
1176 readonly Expression instance;
1177 readonly bool addressRequired;
1179 public InstanceEmitter (Expression instance, bool addressLoad)
1181 this.instance = instance;
1182 this.addressRequired = addressLoad;
1185 public void Emit (EmitContext ec, bool conditionalAccess)
1187 Label NullOperatorLabel;
1188 Nullable.Unwrap unwrap;
1190 if (conditionalAccess && Expression.IsNeverNull (instance))
1191 conditionalAccess = false;
1193 if (conditionalAccess) {
1194 NullOperatorLabel = ec.DefineLabel ();
1195 unwrap = instance as Nullable.Unwrap;
1197 NullOperatorLabel = new Label ();
1201 IMemoryLocation instance_address = null;
1202 bool conditional_access_dup = false;
1204 if (unwrap != null) {
1206 unwrap.EmitCheck (ec);
1207 ec.Emit (OpCodes.Brtrue_S, NullOperatorLabel);
1209 if (conditionalAccess && addressRequired) {
1211 // Don't allocate temp variable when instance load is cheap and load and load-address
1212 // operate on same memory
1214 instance_address = instance as VariableReference;
1215 if (instance_address == null)
1216 instance_address = instance as LocalTemporary;
1218 if (instance_address == null) {
1219 EmitLoad (ec, false);
1220 ec.Emit (OpCodes.Dup);
1221 ec.EmitLoadFromPtr (instance.Type);
1223 conditional_access_dup = true;
1228 EmitLoad (ec, !conditionalAccess);
1230 if (conditionalAccess) {
1231 conditional_access_dup = !ExpressionAnalyzer.IsInexpensiveLoad (instance);
1232 if (conditional_access_dup)
1233 ec.Emit (OpCodes.Dup);
1237 if (conditionalAccess) {
1238 if (instance.Type.Kind == MemberKind.TypeParameter)
1239 ec.Emit (OpCodes.Box, instance.Type);
1241 ec.Emit (OpCodes.Brtrue_S, NullOperatorLabel);
1243 if (conditional_access_dup)
1244 ec.Emit (OpCodes.Pop);
1248 if (conditionalAccess) {
1249 if (!ec.ConditionalAccess.Statement) {
1250 if (ec.ConditionalAccess.Type.IsNullableType)
1251 Nullable.LiftedNull.Create (ec.ConditionalAccess.Type, Location.Null).Emit (ec);
1256 ec.Emit (OpCodes.Br, ec.ConditionalAccess.EndLabel);
1257 ec.MarkLabel (NullOperatorLabel);
1259 if (instance_address != null) {
1260 instance_address.AddressOf (ec, AddressOp.Load);
1261 } else if (unwrap != null) {
1263 if (addressRequired) {
1264 var tmp = ec.GetTemporaryLocal (unwrap.Type);
1265 ec.Emit (OpCodes.Stloc, tmp);
1266 ec.Emit (OpCodes.Ldloca, tmp);
1267 ec.FreeTemporaryLocal (tmp, unwrap.Type);
1269 } else if (!conditional_access_dup) {
1275 public void EmitLoad (EmitContext ec, bool boxInstance)
1277 var instance_type = instance.Type;
1280 // Push the instance expression
1282 if (addressRequired) {
1284 // If the expression implements IMemoryLocation, then
1285 // we can optimize and use AddressOf on the
1288 // If not we have to use some temporary storage for
1290 var iml = instance as IMemoryLocation;
1292 iml.AddressOf (ec, AddressOp.Load);
1294 LocalTemporary temp = new LocalTemporary (instance_type);
1297 temp.AddressOf (ec, AddressOp.Load);
1305 // Only to make verifier happy
1306 if (boxInstance && ExpressionAnalyzer.RequiresBoxing (instance)) {
1307 ec.Emit (OpCodes.Box, instance_type);
1311 public TypeSpec GetStackType (EmitContext ec)
1313 var instance_type = instance.Type;
1315 if (addressRequired)
1316 return ReferenceContainer.MakeType (ec.Module, instance_type);
1318 if (instance_type.IsStructOrEnum)
1319 return ec.Module.Compiler.BuiltinTypes.Object;
1321 return instance_type;
1327 static class ExpressionAnalyzer
1329 public static bool RequiresBoxing (Expression instance)
1331 var instance_type = instance.Type;
1332 if (instance_type.IsGenericParameter && !(instance is This) && TypeSpec.IsReferenceType (instance_type))
1335 if (instance_type.IsStructOrEnum)
1342 // Returns true for cheap race-free load, where we can avoid using dup
1344 public static bool IsInexpensiveLoad (Expression instance)
1346 if (instance is Constant)
1347 return instance.IsSideEffectFree;
1349 if (RequiresBoxing (instance))
1352 var vr = instance as VariableReference;
1354 // Load from captured local would be racy without dup
1355 return !vr.IsRef && !vr.IsHoisted;
1358 if (instance is LocalTemporary)
1361 var fe = instance as FieldExpr;
1363 return fe.IsStatic || fe.InstanceExpression is This;