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 TypeSpec CurrentType {
125 get { return member_context.CurrentType; }
128 public TypeParameters CurrentTypeParameters {
129 get { return member_context.CurrentTypeParameters; }
132 public MemberCore CurrentTypeDefinition {
133 get { return member_context.CurrentMemberDefinition; }
136 public bool EmitAccurateDebugInfo {
138 return (flags & Options.AccurateDebugInfo) != 0;
142 public bool HasMethodSymbolBuilder {
144 return methodSymbols != null;
148 public bool HasReturnLabel {
150 return return_label.HasValue;
154 public bool IsStatic {
155 get { return member_context.IsStatic; }
158 public bool IsAnonymousStoreyMutateRequired {
160 return CurrentAnonymousMethod != null &&
161 CurrentAnonymousMethod.Storey != null &&
162 CurrentAnonymousMethod.Storey.Mutator != null;
166 public IMemberContext MemberContext {
168 return member_context;
172 public ModuleContainer Module {
174 return member_context.Module;
178 // Has to be used for specific emitter errors only any
179 // possible resolver errors have to be reported during Resolve
180 public Report Report {
182 return member_context.Module.Compiler.Report;
186 public TypeSpec ReturnType {
193 // The label where we have to jump before leaving the context
195 public Label ReturnLabel {
197 return return_label.Value;
201 public List<IExpressionCleanup> StatementEpilogue {
203 return epilogue_expressions;
207 public LocalVariable AsyncThrowVariable { get; set; }
211 public void AddStatementEpilog (IExpressionCleanup cleanupExpression)
213 if (epilogue_expressions == null) {
214 epilogue_expressions = new List<IExpressionCleanup> ();
215 } else if (epilogue_expressions.Contains (cleanupExpression)) {
219 epilogue_expressions.Add (cleanupExpression);
222 public void AssertEmptyStack ()
225 if (ig.__StackHeight != 0)
226 throw new InternalErrorException ("Await yields with non-empty stack in `{0}",
227 member_context.GetSignatureForError ());
232 /// This is called immediately before emitting an IL opcode to tell the symbol
233 /// writer to which source line this opcode belongs.
235 public bool Mark (Location loc)
237 if ((flags & Options.OmitDebugInfo) != 0)
240 if (loc.IsNull || methodSymbols == null)
243 var sf = loc.SourceFile;
244 if (sf.IsHiddenLocation (loc))
248 methodSymbols.MarkSequencePoint (ig.ILOffset, sf.SourceFileEntry, loc.Row, loc.Column, false);
253 public void MarkCallEntry (Location loc)
255 if (!EmitAccurateDebugInfo)
259 // TODO: This should emit different kind of sequence point to make
260 // step-over work for statement over multiple lines
262 // Debugging experience for Foo (A () + B ()) where A and B are
263 // on separate lines is not great
268 public void DefineLocalVariable (string name, LocalBuilder builder)
270 if ((flags & Options.OmitDebugInfo) != 0)
273 methodSymbols.AddLocal (builder.LocalIndex, name);
276 public void BeginCatchBlock (TypeSpec type)
278 if (IsAnonymousStoreyMutateRequired)
279 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
281 ig.BeginCatchBlock (type.GetMetaInfo ());
284 public void BeginFilterHandler ()
286 ig.BeginCatchBlock (null);
289 public void BeginExceptionBlock ()
291 ig.BeginExceptionBlock ();
294 public void BeginExceptionFilterBlock ()
296 ig.BeginExceptFilterBlock ();
299 public void BeginFinallyBlock ()
301 ig.BeginFinallyBlock ();
304 public void BeginScope ()
306 if ((flags & Options.OmitDebugInfo) != 0)
310 methodSymbols.StartBlock (CodeBlockEntry.Type.Lexical, ig.ILOffset);
314 public void BeginCompilerScope ()
316 if ((flags & Options.OmitDebugInfo) != 0)
320 methodSymbols.StartBlock (CodeBlockEntry.Type.CompilerGenerated, ig.ILOffset);
324 public void EndExceptionBlock ()
326 ig.EndExceptionBlock ();
329 public void EndScope ()
331 if ((flags & Options.OmitDebugInfo) != 0)
335 methodSymbols.EndBlock (ig.ILOffset);
340 // Creates a nested container in this context for all dynamic compiler generated stuff
342 internal DynamicSiteClass CreateDynamicSite ()
344 if (dynamic_site_container == null) {
345 var mc = member_context.CurrentMemberDefinition as MemberBase;
346 dynamic_site_container = new DynamicSiteClass (CurrentTypeDefinition.Parent.PartialContainer, mc, member_context.CurrentTypeParameters);
348 CurrentTypeDefinition.Module.AddCompilerGeneratedClass (dynamic_site_container);
349 dynamic_site_container.CreateContainer ();
350 dynamic_site_container.DefineContainer ();
351 dynamic_site_container.Define ();
353 var inflator = new TypeParameterInflator (Module, CurrentType, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes);
354 var inflated = dynamic_site_container.CurrentType.InflateMember (inflator);
355 CurrentType.MemberCache.AddMember (inflated);
358 return dynamic_site_container;
361 public Label CreateReturnLabel ()
363 if (!return_label.HasValue)
364 return_label = DefineLabel ();
366 return return_label.Value;
369 public LocalBuilder DeclareLocal (TypeSpec type, bool pinned)
371 if (IsAnonymousStoreyMutateRequired)
372 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
374 return ig.DeclareLocal (type.GetMetaInfo (), pinned);
377 public Label DefineLabel ()
379 return ig.DefineLabel ();
383 // Creates temporary field in current async storey
385 public StackFieldExpr GetTemporaryField (TypeSpec type)
387 var f = AsyncTaskStorey.AddCapturedLocalVariable (type);
388 var fexpr = new StackFieldExpr (f);
389 fexpr.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location.Null);
393 public void MarkLabel (Label label)
395 ig.MarkLabel (label);
398 public void Emit (OpCode opcode)
403 public void Emit (OpCode opcode, LocalBuilder local)
405 ig.Emit (opcode, local);
408 public void Emit (OpCode opcode, string arg)
410 ig.Emit (opcode, arg);
413 public void Emit (OpCode opcode, double arg)
415 ig.Emit (opcode, arg);
418 public void Emit (OpCode opcode, float arg)
420 ig.Emit (opcode, arg);
423 public void Emit (OpCode opcode, Label label)
425 ig.Emit (opcode, label);
428 public void Emit (OpCode opcode, Label[] labels)
430 ig.Emit (opcode, labels);
433 public void Emit (OpCode opcode, TypeSpec type)
435 if (IsAnonymousStoreyMutateRequired)
436 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
438 ig.Emit (opcode, type.GetMetaInfo ());
441 public void Emit (OpCode opcode, FieldSpec field)
443 if (IsAnonymousStoreyMutateRequired)
444 field = field.Mutate (CurrentAnonymousMethod.Storey.Mutator);
446 ig.Emit (opcode, field.GetMetaInfo ());
449 public void Emit (OpCode opcode, MethodSpec method)
451 if (IsAnonymousStoreyMutateRequired)
452 method = method.Mutate (CurrentAnonymousMethod.Storey.Mutator);
454 if (method.IsConstructor)
455 ig.Emit (opcode, (ConstructorInfo) method.GetMetaInfo ());
457 ig.Emit (opcode, (MethodInfo) method.GetMetaInfo ());
460 // TODO: REMOVE breaks mutator
461 public void Emit (OpCode opcode, MethodInfo method)
463 ig.Emit (opcode, method);
466 public void Emit (OpCode opcode, MethodSpec method, MetaType[] vargs)
468 // TODO MemberCache: This should mutate too
469 ig.EmitCall (opcode, (MethodInfo) method.GetMetaInfo (), vargs);
472 public void EmitArrayNew (ArrayContainer ac)
475 var type = IsAnonymousStoreyMutateRequired ?
476 CurrentAnonymousMethod.Storey.Mutator.Mutate (ac.Element) :
479 ig.Emit (OpCodes.Newarr, type.GetMetaInfo ());
481 if (IsAnonymousStoreyMutateRequired)
482 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
484 ig.Emit (OpCodes.Newobj, ac.GetConstructor ());
488 public void EmitArrayAddress (ArrayContainer ac)
491 if (IsAnonymousStoreyMutateRequired)
492 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
494 ig.Emit (OpCodes.Call, ac.GetAddressMethod ());
496 var type = IsAnonymousStoreyMutateRequired ?
497 CurrentAnonymousMethod.Storey.Mutator.Mutate (ac.Element) :
500 ig.Emit (OpCodes.Ldelema, type.GetMetaInfo ());
505 // Emits the right opcode to load from an array
507 public void EmitArrayLoad (ArrayContainer ac)
510 if (IsAnonymousStoreyMutateRequired)
511 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
513 ig.Emit (OpCodes.Call, ac.GetGetMethod ());
518 var type = ac.Element;
519 if (type.Kind == MemberKind.Enum)
520 type = EnumSpec.GetUnderlyingType (type);
522 switch (type.BuiltinType) {
523 case BuiltinTypeSpec.Type.Byte:
524 case BuiltinTypeSpec.Type.Bool:
525 ig.Emit (OpCodes.Ldelem_U1);
527 case BuiltinTypeSpec.Type.SByte:
528 ig.Emit (OpCodes.Ldelem_I1);
530 case BuiltinTypeSpec.Type.Short:
531 ig.Emit (OpCodes.Ldelem_I2);
533 case BuiltinTypeSpec.Type.UShort:
534 case BuiltinTypeSpec.Type.Char:
535 ig.Emit (OpCodes.Ldelem_U2);
537 case BuiltinTypeSpec.Type.Int:
538 ig.Emit (OpCodes.Ldelem_I4);
540 case BuiltinTypeSpec.Type.UInt:
541 ig.Emit (OpCodes.Ldelem_U4);
543 case BuiltinTypeSpec.Type.ULong:
544 case BuiltinTypeSpec.Type.Long:
545 ig.Emit (OpCodes.Ldelem_I8);
547 case BuiltinTypeSpec.Type.Float:
548 ig.Emit (OpCodes.Ldelem_R4);
550 case BuiltinTypeSpec.Type.Double:
551 ig.Emit (OpCodes.Ldelem_R8);
553 case BuiltinTypeSpec.Type.IntPtr:
554 ig.Emit (OpCodes.Ldelem_I);
558 case MemberKind.Struct:
559 if (IsAnonymousStoreyMutateRequired)
560 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
562 ig.Emit (OpCodes.Ldelema, type.GetMetaInfo ());
563 ig.Emit (OpCodes.Ldobj, type.GetMetaInfo ());
565 case MemberKind.TypeParameter:
566 if (IsAnonymousStoreyMutateRequired)
567 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
569 ig.Emit (OpCodes.Ldelem, type.GetMetaInfo ());
571 case MemberKind.PointerType:
572 ig.Emit (OpCodes.Ldelem_I);
575 ig.Emit (OpCodes.Ldelem_Ref);
583 // Emits the right opcode to store to an array
585 public void EmitArrayStore (ArrayContainer ac)
588 if (IsAnonymousStoreyMutateRequired)
589 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
591 ig.Emit (OpCodes.Call, ac.GetSetMethod ());
595 var type = ac.Element;
597 if (type.Kind == MemberKind.Enum)
598 type = EnumSpec.GetUnderlyingType (type);
600 switch (type.BuiltinType) {
601 case BuiltinTypeSpec.Type.Byte:
602 case BuiltinTypeSpec.Type.SByte:
603 case BuiltinTypeSpec.Type.Bool:
604 Emit (OpCodes.Stelem_I1);
606 case BuiltinTypeSpec.Type.Short:
607 case BuiltinTypeSpec.Type.UShort:
608 case BuiltinTypeSpec.Type.Char:
609 Emit (OpCodes.Stelem_I2);
611 case BuiltinTypeSpec.Type.Int:
612 case BuiltinTypeSpec.Type.UInt:
613 Emit (OpCodes.Stelem_I4);
615 case BuiltinTypeSpec.Type.Long:
616 case BuiltinTypeSpec.Type.ULong:
617 Emit (OpCodes.Stelem_I8);
619 case BuiltinTypeSpec.Type.Float:
620 Emit (OpCodes.Stelem_R4);
622 case BuiltinTypeSpec.Type.Double:
623 Emit (OpCodes.Stelem_R8);
628 case MemberKind.Struct:
629 Emit (OpCodes.Stobj, type);
631 case MemberKind.TypeParameter:
632 Emit (OpCodes.Stelem, type);
634 case MemberKind.PointerType:
635 Emit (OpCodes.Stelem_I);
638 Emit (OpCodes.Stelem_Ref);
643 public void EmitInt (int i)
648 void EmitIntConstant (int i)
652 ig.Emit (OpCodes.Ldc_I4_M1);
656 ig.Emit (OpCodes.Ldc_I4_0);
660 ig.Emit (OpCodes.Ldc_I4_1);
664 ig.Emit (OpCodes.Ldc_I4_2);
668 ig.Emit (OpCodes.Ldc_I4_3);
672 ig.Emit (OpCodes.Ldc_I4_4);
676 ig.Emit (OpCodes.Ldc_I4_5);
680 ig.Emit (OpCodes.Ldc_I4_6);
684 ig.Emit (OpCodes.Ldc_I4_7);
688 ig.Emit (OpCodes.Ldc_I4_8);
692 if (i >= -128 && i <= 127) {
693 ig.Emit (OpCodes.Ldc_I4_S, (sbyte) i);
695 ig.Emit (OpCodes.Ldc_I4, i);
700 public void EmitLong (long l)
702 if (l >= int.MinValue && l <= int.MaxValue) {
703 EmitIntConstant (unchecked ((int) l));
704 ig.Emit (OpCodes.Conv_I8);
705 } else if (l >= 0 && l <= uint.MaxValue) {
706 EmitIntConstant (unchecked ((int) l));
707 ig.Emit (OpCodes.Conv_U8);
709 ig.Emit (OpCodes.Ldc_I8, l);
714 // Load the object from the pointer.
716 public void EmitLoadFromPtr (TypeSpec type)
718 if (type.Kind == MemberKind.Enum)
719 type = EnumSpec.GetUnderlyingType (type);
721 switch (type.BuiltinType) {
722 case BuiltinTypeSpec.Type.Int:
723 ig.Emit (OpCodes.Ldind_I4);
725 case BuiltinTypeSpec.Type.UInt:
726 ig.Emit (OpCodes.Ldind_U4);
728 case BuiltinTypeSpec.Type.Short:
729 ig.Emit (OpCodes.Ldind_I2);
731 case BuiltinTypeSpec.Type.UShort:
732 case BuiltinTypeSpec.Type.Char:
733 ig.Emit (OpCodes.Ldind_U2);
735 case BuiltinTypeSpec.Type.Byte:
736 ig.Emit (OpCodes.Ldind_U1);
738 case BuiltinTypeSpec.Type.SByte:
739 case BuiltinTypeSpec.Type.Bool:
740 ig.Emit (OpCodes.Ldind_I1);
742 case BuiltinTypeSpec.Type.ULong:
743 case BuiltinTypeSpec.Type.Long:
744 ig.Emit (OpCodes.Ldind_I8);
746 case BuiltinTypeSpec.Type.Float:
747 ig.Emit (OpCodes.Ldind_R4);
749 case BuiltinTypeSpec.Type.Double:
750 ig.Emit (OpCodes.Ldind_R8);
752 case BuiltinTypeSpec.Type.IntPtr:
753 ig.Emit (OpCodes.Ldind_I);
757 case MemberKind.Struct:
758 case MemberKind.TypeParameter:
759 if (IsAnonymousStoreyMutateRequired)
760 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
762 ig.Emit (OpCodes.Ldobj, type.GetMetaInfo ());
764 case MemberKind.PointerType:
765 ig.Emit (OpCodes.Ldind_I);
768 ig.Emit (OpCodes.Ldind_Ref);
775 public void EmitNull ()
777 ig.Emit (OpCodes.Ldnull);
780 public void EmitArgumentAddress (int pos)
785 if (pos > byte.MaxValue)
786 ig.Emit (OpCodes.Ldarga, pos);
788 ig.Emit (OpCodes.Ldarga_S, (byte) pos);
791 public void EmitArgumentLoad (int pos)
797 case 0: ig.Emit (OpCodes.Ldarg_0); break;
798 case 1: ig.Emit (OpCodes.Ldarg_1); break;
799 case 2: ig.Emit (OpCodes.Ldarg_2); break;
800 case 3: ig.Emit (OpCodes.Ldarg_3); break;
802 if (pos > byte.MaxValue)
803 ig.Emit (OpCodes.Ldarg, pos);
805 ig.Emit (OpCodes.Ldarg_S, (byte) pos);
810 public void EmitArgumentStore (int pos)
815 if (pos > byte.MaxValue)
816 ig.Emit (OpCodes.Starg, pos);
818 ig.Emit (OpCodes.Starg_S, (byte) pos);
822 // The stack contains the pointer and the value of type `type'
824 public void EmitStoreFromPtr (TypeSpec type)
827 type = EnumSpec.GetUnderlyingType (type);
829 switch (type.BuiltinType) {
830 case BuiltinTypeSpec.Type.Int:
831 case BuiltinTypeSpec.Type.UInt:
832 ig.Emit (OpCodes.Stind_I4);
834 case BuiltinTypeSpec.Type.Long:
835 case BuiltinTypeSpec.Type.ULong:
836 ig.Emit (OpCodes.Stind_I8);
838 case BuiltinTypeSpec.Type.Char:
839 case BuiltinTypeSpec.Type.Short:
840 case BuiltinTypeSpec.Type.UShort:
841 ig.Emit (OpCodes.Stind_I2);
843 case BuiltinTypeSpec.Type.Float:
844 ig.Emit (OpCodes.Stind_R4);
846 case BuiltinTypeSpec.Type.Double:
847 ig.Emit (OpCodes.Stind_R8);
849 case BuiltinTypeSpec.Type.Byte:
850 case BuiltinTypeSpec.Type.SByte:
851 case BuiltinTypeSpec.Type.Bool:
852 ig.Emit (OpCodes.Stind_I1);
854 case BuiltinTypeSpec.Type.IntPtr:
855 ig.Emit (OpCodes.Stind_I);
860 case MemberKind.Struct:
861 case MemberKind.TypeParameter:
862 if (IsAnonymousStoreyMutateRequired)
863 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
865 ig.Emit (OpCodes.Stobj, type.GetMetaInfo ());
868 ig.Emit (OpCodes.Stind_Ref);
873 public void EmitThis ()
875 ig.Emit (OpCodes.Ldarg_0);
878 public void EmitEpilogue ()
880 if (epilogue_expressions == null)
883 foreach (var e in epilogue_expressions)
884 e.EmitCleanup (this);
886 epilogue_expressions = null;
890 /// Returns a temporary storage for a variable of type t as
891 /// a local variable in the current body.
893 public LocalBuilder GetTemporaryLocal (TypeSpec t)
895 if (temporary_storage != null) {
897 if (temporary_storage.TryGetValue (t, out o)) {
898 if (o is Stack<LocalBuilder>) {
899 var s = (Stack<LocalBuilder>) o;
900 o = s.Count == 0 ? null : s.Pop ();
902 temporary_storage.Remove (t);
906 return (LocalBuilder) o;
908 return DeclareLocal (t, false);
911 public void FreeTemporaryLocal (LocalBuilder b, TypeSpec t)
913 if (temporary_storage == null) {
914 temporary_storage = new Dictionary<TypeSpec, object> (ReferenceEquality<TypeSpec>.Default);
915 temporary_storage.Add (t, b);
920 if (!temporary_storage.TryGetValue (t, out o)) {
921 temporary_storage.Add (t, b);
924 var s = o as Stack<LocalBuilder>;
926 s = new Stack<LocalBuilder> ();
927 s.Push ((LocalBuilder)o);
928 temporary_storage [t] = s;
934 /// ReturnValue creates on demand the LocalBuilder for the
935 /// return value from the function. By default this is not
936 /// used. This is only required when returns are found inside
937 /// Try or Catch statements.
939 /// This method is typically invoked from the Emit phase, so
940 /// we allow the creation of a return label if it was not
941 /// requested during the resolution phase. Could be cleaned
942 /// up, but it would replicate a lot of logic in the Emit phase
943 /// of the code that uses it.
945 public LocalBuilder TemporaryReturn ()
947 if (return_value == null){
948 return_value = DeclareLocal (return_type, false);
957 public Expression InstanceExpression;
960 // When set leaves an extra copy of all arguments on the stack
962 public bool DuplicateArguments;
965 // Does not emit InstanceExpression load when InstanceExpressionOnStack
966 // is set. Used by compound assignments.
968 public bool InstanceExpressionOnStack;
971 // Any of arguments contains await expression
973 public bool HasAwaitArguments;
976 // When dealing with await arguments the original arguments are converted
977 // into a new set with hoisted stack results
979 public Arguments EmittedArguments;
981 public void Emit (EmitContext ec, MethodSpec method, Arguments Arguments, Location loc)
983 EmitPredefined (ec, method, Arguments, loc);
986 public void EmitPredefined (EmitContext ec, MethodSpec method, Arguments Arguments, Location? loc = null)
988 Expression instance_copy = null;
990 if (!HasAwaitArguments && ec.HasSet (BuilderContext.Options.AsyncBody)) {
991 HasAwaitArguments = Arguments != null && Arguments.ContainsEmitWithAwait ();
992 if (HasAwaitArguments && InstanceExpressionOnStack) {
993 throw new NotSupportedException ();
998 LocalTemporary lt = null;
1000 if (method.IsStatic) {
1001 call_op = OpCodes.Call;
1003 if (IsVirtualCallRequired (InstanceExpression, method)) {
1004 call_op = OpCodes.Callvirt;
1006 call_op = OpCodes.Call;
1009 if (HasAwaitArguments) {
1010 instance_copy = InstanceExpression.EmitToField (ec);
1011 if (Arguments == null)
1012 EmitCallInstance (ec, instance_copy, method.DeclaringType, call_op);
1013 } else if (!InstanceExpressionOnStack) {
1014 var instance_on_stack_type = EmitCallInstance (ec, InstanceExpression, method.DeclaringType, call_op);
1016 if (DuplicateArguments) {
1017 ec.Emit (OpCodes.Dup);
1018 if (Arguments != null && Arguments.Count != 0) {
1019 lt = new LocalTemporary (instance_on_stack_type);
1027 if (Arguments != null && !InstanceExpressionOnStack) {
1028 EmittedArguments = Arguments.Emit (ec, DuplicateArguments, HasAwaitArguments);
1029 if (EmittedArguments != null) {
1030 if (instance_copy != null) {
1031 EmitCallInstance (ec, instance_copy, method.DeclaringType, call_op);
1037 EmittedArguments.Emit (ec);
1041 if (call_op == OpCodes.Callvirt && (InstanceExpression.Type.IsGenericParameter || InstanceExpression.Type.IsStructOrEnum)) {
1042 ec.Emit (OpCodes.Constrained, InstanceExpression.Type);
1047 // Emit explicit sequence point for expressions like Foo.Bar () to help debugger to
1048 // break at right place when LHS expression can be stepped-into
1050 ec.MarkCallEntry (loc.Value);
1054 // Set instance expression to actual result expression. When it contains await it can be
1055 // picked up by caller
1057 InstanceExpression = instance_copy;
1059 if (method.Parameters.HasArglist) {
1060 var varargs_types = GetVarargsTypes (method, Arguments);
1061 ec.Emit (call_op, method, varargs_types);
1068 // and DoFoo is not virtual, you can omit the callvirt,
1069 // because you don't need the null checking behavior.
1071 ec.Emit (call_op, method);
1074 static TypeSpec EmitCallInstance (EmitContext ec, Expression instance, TypeSpec declaringType, OpCode callOpcode)
1076 var instance_type = instance.Type;
1079 // Push the instance expression
1081 if ((instance_type.IsStructOrEnum && (callOpcode == OpCodes.Callvirt || (callOpcode == OpCodes.Call && declaringType.IsStruct))) ||
1082 instance_type.IsGenericParameter || declaringType.IsNullableType) {
1084 // If the expression implements IMemoryLocation, then
1085 // we can optimize and use AddressOf on the
1088 // If not we have to use some temporary storage for
1090 var iml = instance as IMemoryLocation;
1092 iml.AddressOf (ec, AddressOp.Load);
1094 LocalTemporary temp = new LocalTemporary (instance_type);
1097 temp.AddressOf (ec, AddressOp.Load);
1100 return ReferenceContainer.MakeType (ec.Module, instance_type);
1103 if (instance_type.IsStructOrEnum) {
1105 ec.Emit (OpCodes.Box, instance_type);
1106 return ec.BuiltinTypes.Object;
1110 return instance_type;
1113 static MetaType[] GetVarargsTypes (MethodSpec method, Arguments arguments)
1115 AParametersCollection pd = method.Parameters;
1117 Argument a = arguments[pd.Count - 1];
1118 Arglist list = (Arglist) a.Expr;
1120 return list.ArgumentTypes;
1124 // Used to decide whether call or callvirt is needed
1126 static bool IsVirtualCallRequired (Expression instance, MethodSpec method)
1129 // There are 2 scenarious where we emit callvirt
1131 // Case 1: A method is virtual and it's not used to call base
1132 // Case 2: A method instance expression can be null. In this casen callvirt ensures
1133 // correct NRE exception when the method is called
1135 var decl_type = method.DeclaringType;
1136 if (decl_type.IsStruct || decl_type.IsEnum)
1139 if (instance is BaseThis)
1143 // It's non-virtual and will never be null and it can be determined
1144 // whether it's known value or reference type by verifier
1146 if (!method.IsVirtual && (instance is This || instance is New || instance is ArrayCreation || instance is DelegateCreation) &&
1147 !instance.Type.IsGenericParameter)