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;
209 public void AddStatementEpilog (IExpressionCleanup cleanupExpression)
211 if (epilogue_expressions == null) {
212 epilogue_expressions = new List<IExpressionCleanup> ();
213 } else if (epilogue_expressions.Contains (cleanupExpression)) {
217 epilogue_expressions.Add (cleanupExpression);
220 public void AssertEmptyStack ()
223 if (ig.__StackHeight != 0)
224 throw new InternalErrorException ("Await yields with non-empty stack in `{0}",
225 member_context.GetSignatureForError ());
230 /// This is called immediately before emitting an IL opcode to tell the symbol
231 /// writer to which source line this opcode belongs.
233 public bool Mark (Location loc)
235 if ((flags & Options.OmitDebugInfo) != 0)
238 if (loc.IsNull || methodSymbols == null)
241 var sf = loc.SourceFile;
242 if (sf.IsHiddenLocation (loc))
246 methodSymbols.MarkSequencePoint (ig.ILOffset, sf.SourceFileEntry, loc.Row, loc.Column, false);
251 public void MarkCallEntry (Location loc)
253 if (!EmitAccurateDebugInfo)
257 // TODO: This should emit different kind of sequence point to make
258 // step-over work for statement over multiple lines
260 // Debugging experience for Foo (A () + B ()) where A and B are
261 // on separate lines is not great
266 public void DefineLocalVariable (string name, LocalBuilder builder)
268 if ((flags & Options.OmitDebugInfo) != 0)
271 methodSymbols.AddLocal (builder.LocalIndex, name);
274 public void BeginCatchBlock (TypeSpec type)
276 if (IsAnonymousStoreyMutateRequired)
277 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
279 ig.BeginCatchBlock (type.GetMetaInfo ());
282 public void BeginFilterHandler ()
284 ig.BeginCatchBlock (null);
287 public void BeginExceptionBlock ()
289 ig.BeginExceptionBlock ();
292 public void BeginExceptionFilterBlock ()
294 ig.BeginExceptFilterBlock ();
297 public void BeginFinallyBlock ()
299 ig.BeginFinallyBlock ();
302 public void BeginScope ()
304 if ((flags & Options.OmitDebugInfo) != 0)
308 methodSymbols.StartBlock (CodeBlockEntry.Type.Lexical, ig.ILOffset);
312 public void BeginCompilerScope ()
314 if ((flags & Options.OmitDebugInfo) != 0)
318 methodSymbols.StartBlock (CodeBlockEntry.Type.CompilerGenerated, ig.ILOffset);
322 public void EndExceptionBlock ()
324 ig.EndExceptionBlock ();
327 public void EndScope ()
329 if ((flags & Options.OmitDebugInfo) != 0)
333 methodSymbols.EndBlock (ig.ILOffset);
338 // Creates a nested container in this context for all dynamic compiler generated stuff
340 internal DynamicSiteClass CreateDynamicSite ()
342 if (dynamic_site_container == null) {
343 var mc = member_context.CurrentMemberDefinition as MemberBase;
344 dynamic_site_container = new DynamicSiteClass (CurrentTypeDefinition.Parent.PartialContainer, mc, member_context.CurrentTypeParameters);
346 CurrentTypeDefinition.Module.AddCompilerGeneratedClass (dynamic_site_container);
347 dynamic_site_container.CreateContainer ();
348 dynamic_site_container.DefineContainer ();
349 dynamic_site_container.Define ();
351 var inflator = new TypeParameterInflator (Module, CurrentType, TypeParameterSpec.EmptyTypes, TypeSpec.EmptyTypes);
352 var inflated = dynamic_site_container.CurrentType.InflateMember (inflator);
353 CurrentType.MemberCache.AddMember (inflated);
356 return dynamic_site_container;
359 public Label CreateReturnLabel ()
361 if (!return_label.HasValue)
362 return_label = DefineLabel ();
364 return return_label.Value;
367 public LocalBuilder DeclareLocal (TypeSpec type, bool pinned)
369 if (IsAnonymousStoreyMutateRequired)
370 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
372 return ig.DeclareLocal (type.GetMetaInfo (), pinned);
375 public Label DefineLabel ()
377 return ig.DefineLabel ();
381 // Creates temporary field in current async storey
383 public StackFieldExpr GetTemporaryField (TypeSpec type)
385 var f = AsyncTaskStorey.AddCapturedLocalVariable (type);
386 var fexpr = new StackFieldExpr (f);
387 fexpr.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location.Null);
391 public void MarkLabel (Label label)
393 ig.MarkLabel (label);
396 public void Emit (OpCode opcode)
401 public void Emit (OpCode opcode, LocalBuilder local)
403 ig.Emit (opcode, local);
406 public void Emit (OpCode opcode, string arg)
408 ig.Emit (opcode, arg);
411 public void Emit (OpCode opcode, double arg)
413 ig.Emit (opcode, arg);
416 public void Emit (OpCode opcode, float arg)
418 ig.Emit (opcode, arg);
421 public void Emit (OpCode opcode, Label label)
423 ig.Emit (opcode, label);
426 public void Emit (OpCode opcode, Label[] labels)
428 ig.Emit (opcode, labels);
431 public void Emit (OpCode opcode, TypeSpec type)
433 if (IsAnonymousStoreyMutateRequired)
434 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
436 ig.Emit (opcode, type.GetMetaInfo ());
439 public void Emit (OpCode opcode, FieldSpec field)
441 if (IsAnonymousStoreyMutateRequired)
442 field = field.Mutate (CurrentAnonymousMethod.Storey.Mutator);
444 ig.Emit (opcode, field.GetMetaInfo ());
447 public void Emit (OpCode opcode, MethodSpec method)
449 if (IsAnonymousStoreyMutateRequired)
450 method = method.Mutate (CurrentAnonymousMethod.Storey.Mutator);
452 if (method.IsConstructor)
453 ig.Emit (opcode, (ConstructorInfo) method.GetMetaInfo ());
455 ig.Emit (opcode, (MethodInfo) method.GetMetaInfo ());
458 // TODO: REMOVE breaks mutator
459 public void Emit (OpCode opcode, MethodInfo method)
461 ig.Emit (opcode, method);
464 public void Emit (OpCode opcode, MethodSpec method, MetaType[] vargs)
466 // TODO MemberCache: This should mutate too
467 ig.EmitCall (opcode, (MethodInfo) method.GetMetaInfo (), vargs);
470 public void EmitArrayNew (ArrayContainer ac)
473 var type = IsAnonymousStoreyMutateRequired ?
474 CurrentAnonymousMethod.Storey.Mutator.Mutate (ac.Element) :
477 ig.Emit (OpCodes.Newarr, type.GetMetaInfo ());
479 if (IsAnonymousStoreyMutateRequired)
480 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
482 ig.Emit (OpCodes.Newobj, ac.GetConstructor ());
486 public void EmitArrayAddress (ArrayContainer ac)
489 if (IsAnonymousStoreyMutateRequired)
490 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
492 ig.Emit (OpCodes.Call, ac.GetAddressMethod ());
494 var type = IsAnonymousStoreyMutateRequired ?
495 CurrentAnonymousMethod.Storey.Mutator.Mutate (ac.Element) :
498 ig.Emit (OpCodes.Ldelema, type.GetMetaInfo ());
503 // Emits the right opcode to load from an array
505 public void EmitArrayLoad (ArrayContainer ac)
508 if (IsAnonymousStoreyMutateRequired)
509 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
511 ig.Emit (OpCodes.Call, ac.GetGetMethod ());
516 var type = ac.Element;
517 if (type.Kind == MemberKind.Enum)
518 type = EnumSpec.GetUnderlyingType (type);
520 switch (type.BuiltinType) {
521 case BuiltinTypeSpec.Type.Byte:
522 case BuiltinTypeSpec.Type.Bool:
523 ig.Emit (OpCodes.Ldelem_U1);
525 case BuiltinTypeSpec.Type.SByte:
526 ig.Emit (OpCodes.Ldelem_I1);
528 case BuiltinTypeSpec.Type.Short:
529 ig.Emit (OpCodes.Ldelem_I2);
531 case BuiltinTypeSpec.Type.UShort:
532 case BuiltinTypeSpec.Type.Char:
533 ig.Emit (OpCodes.Ldelem_U2);
535 case BuiltinTypeSpec.Type.Int:
536 ig.Emit (OpCodes.Ldelem_I4);
538 case BuiltinTypeSpec.Type.UInt:
539 ig.Emit (OpCodes.Ldelem_U4);
541 case BuiltinTypeSpec.Type.ULong:
542 case BuiltinTypeSpec.Type.Long:
543 ig.Emit (OpCodes.Ldelem_I8);
545 case BuiltinTypeSpec.Type.Float:
546 ig.Emit (OpCodes.Ldelem_R4);
548 case BuiltinTypeSpec.Type.Double:
549 ig.Emit (OpCodes.Ldelem_R8);
551 case BuiltinTypeSpec.Type.IntPtr:
552 ig.Emit (OpCodes.Ldelem_I);
556 case MemberKind.Struct:
557 if (IsAnonymousStoreyMutateRequired)
558 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
560 ig.Emit (OpCodes.Ldelema, type.GetMetaInfo ());
561 ig.Emit (OpCodes.Ldobj, type.GetMetaInfo ());
563 case MemberKind.TypeParameter:
564 if (IsAnonymousStoreyMutateRequired)
565 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
567 ig.Emit (OpCodes.Ldelem, type.GetMetaInfo ());
569 case MemberKind.PointerType:
570 ig.Emit (OpCodes.Ldelem_I);
573 ig.Emit (OpCodes.Ldelem_Ref);
581 // Emits the right opcode to store to an array
583 public void EmitArrayStore (ArrayContainer ac)
586 if (IsAnonymousStoreyMutateRequired)
587 ac = (ArrayContainer) ac.Mutate (CurrentAnonymousMethod.Storey.Mutator);
589 ig.Emit (OpCodes.Call, ac.GetSetMethod ());
593 var type = ac.Element;
595 if (type.Kind == MemberKind.Enum)
596 type = EnumSpec.GetUnderlyingType (type);
598 switch (type.BuiltinType) {
599 case BuiltinTypeSpec.Type.Byte:
600 case BuiltinTypeSpec.Type.SByte:
601 case BuiltinTypeSpec.Type.Bool:
602 Emit (OpCodes.Stelem_I1);
604 case BuiltinTypeSpec.Type.Short:
605 case BuiltinTypeSpec.Type.UShort:
606 case BuiltinTypeSpec.Type.Char:
607 Emit (OpCodes.Stelem_I2);
609 case BuiltinTypeSpec.Type.Int:
610 case BuiltinTypeSpec.Type.UInt:
611 Emit (OpCodes.Stelem_I4);
613 case BuiltinTypeSpec.Type.Long:
614 case BuiltinTypeSpec.Type.ULong:
615 Emit (OpCodes.Stelem_I8);
617 case BuiltinTypeSpec.Type.Float:
618 Emit (OpCodes.Stelem_R4);
620 case BuiltinTypeSpec.Type.Double:
621 Emit (OpCodes.Stelem_R8);
626 case MemberKind.Struct:
627 Emit (OpCodes.Stobj, type);
629 case MemberKind.TypeParameter:
630 Emit (OpCodes.Stelem, type);
632 case MemberKind.PointerType:
633 Emit (OpCodes.Stelem_I);
636 Emit (OpCodes.Stelem_Ref);
641 public void EmitInt (int i)
646 void EmitIntConstant (int i)
650 ig.Emit (OpCodes.Ldc_I4_M1);
654 ig.Emit (OpCodes.Ldc_I4_0);
658 ig.Emit (OpCodes.Ldc_I4_1);
662 ig.Emit (OpCodes.Ldc_I4_2);
666 ig.Emit (OpCodes.Ldc_I4_3);
670 ig.Emit (OpCodes.Ldc_I4_4);
674 ig.Emit (OpCodes.Ldc_I4_5);
678 ig.Emit (OpCodes.Ldc_I4_6);
682 ig.Emit (OpCodes.Ldc_I4_7);
686 ig.Emit (OpCodes.Ldc_I4_8);
690 if (i >= -128 && i <= 127) {
691 ig.Emit (OpCodes.Ldc_I4_S, (sbyte) i);
693 ig.Emit (OpCodes.Ldc_I4, i);
698 public void EmitLong (long l)
700 if (l >= int.MinValue && l <= int.MaxValue) {
701 EmitIntConstant (unchecked ((int) l));
702 ig.Emit (OpCodes.Conv_I8);
703 } else if (l >= 0 && l <= uint.MaxValue) {
704 EmitIntConstant (unchecked ((int) l));
705 ig.Emit (OpCodes.Conv_U8);
707 ig.Emit (OpCodes.Ldc_I8, l);
712 // Load the object from the pointer.
714 public void EmitLoadFromPtr (TypeSpec type)
716 if (type.Kind == MemberKind.Enum)
717 type = EnumSpec.GetUnderlyingType (type);
719 switch (type.BuiltinType) {
720 case BuiltinTypeSpec.Type.Int:
721 ig.Emit (OpCodes.Ldind_I4);
723 case BuiltinTypeSpec.Type.UInt:
724 ig.Emit (OpCodes.Ldind_U4);
726 case BuiltinTypeSpec.Type.Short:
727 ig.Emit (OpCodes.Ldind_I2);
729 case BuiltinTypeSpec.Type.UShort:
730 case BuiltinTypeSpec.Type.Char:
731 ig.Emit (OpCodes.Ldind_U2);
733 case BuiltinTypeSpec.Type.Byte:
734 ig.Emit (OpCodes.Ldind_U1);
736 case BuiltinTypeSpec.Type.SByte:
737 case BuiltinTypeSpec.Type.Bool:
738 ig.Emit (OpCodes.Ldind_I1);
740 case BuiltinTypeSpec.Type.ULong:
741 case BuiltinTypeSpec.Type.Long:
742 ig.Emit (OpCodes.Ldind_I8);
744 case BuiltinTypeSpec.Type.Float:
745 ig.Emit (OpCodes.Ldind_R4);
747 case BuiltinTypeSpec.Type.Double:
748 ig.Emit (OpCodes.Ldind_R8);
750 case BuiltinTypeSpec.Type.IntPtr:
751 ig.Emit (OpCodes.Ldind_I);
755 case MemberKind.Struct:
756 case MemberKind.TypeParameter:
757 if (IsAnonymousStoreyMutateRequired)
758 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
760 ig.Emit (OpCodes.Ldobj, type.GetMetaInfo ());
762 case MemberKind.PointerType:
763 ig.Emit (OpCodes.Ldind_I);
766 ig.Emit (OpCodes.Ldind_Ref);
773 public void EmitNull ()
775 ig.Emit (OpCodes.Ldnull);
778 public void EmitArgumentAddress (int pos)
783 if (pos > byte.MaxValue)
784 ig.Emit (OpCodes.Ldarga, pos);
786 ig.Emit (OpCodes.Ldarga_S, (byte) pos);
789 public void EmitArgumentLoad (int pos)
795 case 0: ig.Emit (OpCodes.Ldarg_0); break;
796 case 1: ig.Emit (OpCodes.Ldarg_1); break;
797 case 2: ig.Emit (OpCodes.Ldarg_2); break;
798 case 3: ig.Emit (OpCodes.Ldarg_3); break;
800 if (pos > byte.MaxValue)
801 ig.Emit (OpCodes.Ldarg, pos);
803 ig.Emit (OpCodes.Ldarg_S, (byte) pos);
808 public void EmitArgumentStore (int pos)
813 if (pos > byte.MaxValue)
814 ig.Emit (OpCodes.Starg, pos);
816 ig.Emit (OpCodes.Starg_S, (byte) pos);
820 // The stack contains the pointer and the value of type `type'
822 public void EmitStoreFromPtr (TypeSpec type)
825 type = EnumSpec.GetUnderlyingType (type);
827 switch (type.BuiltinType) {
828 case BuiltinTypeSpec.Type.Int:
829 case BuiltinTypeSpec.Type.UInt:
830 ig.Emit (OpCodes.Stind_I4);
832 case BuiltinTypeSpec.Type.Long:
833 case BuiltinTypeSpec.Type.ULong:
834 ig.Emit (OpCodes.Stind_I8);
836 case BuiltinTypeSpec.Type.Char:
837 case BuiltinTypeSpec.Type.Short:
838 case BuiltinTypeSpec.Type.UShort:
839 ig.Emit (OpCodes.Stind_I2);
841 case BuiltinTypeSpec.Type.Float:
842 ig.Emit (OpCodes.Stind_R4);
844 case BuiltinTypeSpec.Type.Double:
845 ig.Emit (OpCodes.Stind_R8);
847 case BuiltinTypeSpec.Type.Byte:
848 case BuiltinTypeSpec.Type.SByte:
849 case BuiltinTypeSpec.Type.Bool:
850 ig.Emit (OpCodes.Stind_I1);
852 case BuiltinTypeSpec.Type.IntPtr:
853 ig.Emit (OpCodes.Stind_I);
858 case MemberKind.Struct:
859 case MemberKind.TypeParameter:
860 if (IsAnonymousStoreyMutateRequired)
861 type = CurrentAnonymousMethod.Storey.Mutator.Mutate (type);
863 ig.Emit (OpCodes.Stobj, type.GetMetaInfo ());
866 ig.Emit (OpCodes.Stind_Ref);
871 public void EmitThis ()
873 ig.Emit (OpCodes.Ldarg_0);
876 public void EmitEpilogue ()
878 if (epilogue_expressions == null)
881 foreach (var e in epilogue_expressions)
882 e.EmitCleanup (this);
884 epilogue_expressions = null;
888 /// Returns a temporary storage for a variable of type t as
889 /// a local variable in the current body.
891 public LocalBuilder GetTemporaryLocal (TypeSpec t)
893 if (temporary_storage != null) {
895 if (temporary_storage.TryGetValue (t, out o)) {
896 if (o is Stack<LocalBuilder>) {
897 var s = (Stack<LocalBuilder>) o;
898 o = s.Count == 0 ? null : s.Pop ();
900 temporary_storage.Remove (t);
904 return (LocalBuilder) o;
906 return DeclareLocal (t, false);
909 public void FreeTemporaryLocal (LocalBuilder b, TypeSpec t)
911 if (temporary_storage == null) {
912 temporary_storage = new Dictionary<TypeSpec, object> (ReferenceEquality<TypeSpec>.Default);
913 temporary_storage.Add (t, b);
918 if (!temporary_storage.TryGetValue (t, out o)) {
919 temporary_storage.Add (t, b);
922 var s = o as Stack<LocalBuilder>;
924 s = new Stack<LocalBuilder> ();
925 s.Push ((LocalBuilder)o);
926 temporary_storage [t] = s;
932 /// ReturnValue creates on demand the LocalBuilder for the
933 /// return value from the function. By default this is not
934 /// used. This is only required when returns are found inside
935 /// Try or Catch statements.
937 /// This method is typically invoked from the Emit phase, so
938 /// we allow the creation of a return label if it was not
939 /// requested during the resolution phase. Could be cleaned
940 /// up, but it would replicate a lot of logic in the Emit phase
941 /// of the code that uses it.
943 public LocalBuilder TemporaryReturn ()
945 if (return_value == null){
946 return_value = DeclareLocal (return_type, false);
955 public Expression InstanceExpression;
958 // When set leaves an extra copy of all arguments on the stack
960 public bool DuplicateArguments;
963 // Does not emit InstanceExpression load when InstanceExpressionOnStack
964 // is set. Used by compound assignments.
966 public bool InstanceExpressionOnStack;
969 // Any of arguments contains await expression
971 public bool HasAwaitArguments;
974 // When dealing with await arguments the original arguments are converted
975 // into a new set with hoisted stack results
977 public Arguments EmittedArguments;
979 public void Emit (EmitContext ec, MethodSpec method, Arguments Arguments, Location loc)
981 EmitPredefined (ec, method, Arguments, loc);
984 public void EmitPredefined (EmitContext ec, MethodSpec method, Arguments Arguments, Location? loc = null)
986 Expression instance_copy = null;
988 if (!HasAwaitArguments && ec.HasSet (BuilderContext.Options.AsyncBody)) {
989 HasAwaitArguments = Arguments != null && Arguments.ContainsEmitWithAwait ();
990 if (HasAwaitArguments && InstanceExpressionOnStack) {
991 throw new NotSupportedException ();
996 LocalTemporary lt = null;
998 if (method.IsStatic) {
999 call_op = OpCodes.Call;
1001 if (IsVirtualCallRequired (InstanceExpression, method)) {
1002 call_op = OpCodes.Callvirt;
1004 call_op = OpCodes.Call;
1007 if (HasAwaitArguments) {
1008 instance_copy = InstanceExpression.EmitToField (ec);
1009 if (Arguments == null)
1010 EmitCallInstance (ec, instance_copy, method.DeclaringType, call_op);
1011 } else if (!InstanceExpressionOnStack) {
1012 var instance_on_stack_type = EmitCallInstance (ec, InstanceExpression, method.DeclaringType, call_op);
1014 if (DuplicateArguments) {
1015 ec.Emit (OpCodes.Dup);
1016 if (Arguments != null && Arguments.Count != 0) {
1017 lt = new LocalTemporary (instance_on_stack_type);
1025 if (Arguments != null && !InstanceExpressionOnStack) {
1026 EmittedArguments = Arguments.Emit (ec, DuplicateArguments, HasAwaitArguments);
1027 if (EmittedArguments != null) {
1028 if (instance_copy != null) {
1029 EmitCallInstance (ec, instance_copy, method.DeclaringType, call_op);
1035 EmittedArguments.Emit (ec);
1039 if (call_op == OpCodes.Callvirt && (InstanceExpression.Type.IsGenericParameter || InstanceExpression.Type.IsStruct)) {
1040 ec.Emit (OpCodes.Constrained, InstanceExpression.Type);
1045 // Emit explicit sequence point for expressions like Foo.Bar () to help debugger to
1046 // break at right place when LHS expression can be stepped-into
1048 ec.MarkCallEntry (loc.Value);
1052 // Set instance expression to actual result expression. When it contains await it can be
1053 // picked up by caller
1055 InstanceExpression = instance_copy;
1057 if (method.Parameters.HasArglist) {
1058 var varargs_types = GetVarargsTypes (method, Arguments);
1059 ec.Emit (call_op, method, varargs_types);
1066 // and DoFoo is not virtual, you can omit the callvirt,
1067 // because you don't need the null checking behavior.
1069 ec.Emit (call_op, method);
1072 static TypeSpec EmitCallInstance (EmitContext ec, Expression instance, TypeSpec declaringType, OpCode callOpcode)
1074 var instance_type = instance.Type;
1077 // Push the instance expression
1079 if ((instance_type.IsStruct && (callOpcode == OpCodes.Callvirt || (callOpcode == OpCodes.Call && declaringType.IsStruct))) ||
1080 instance_type.IsGenericParameter || declaringType.IsNullableType) {
1082 // If the expression implements IMemoryLocation, then
1083 // we can optimize and use AddressOf on the
1086 // If not we have to use some temporary storage for
1088 var iml = instance as IMemoryLocation;
1090 iml.AddressOf (ec, AddressOp.Load);
1092 LocalTemporary temp = new LocalTemporary (instance_type);
1095 temp.AddressOf (ec, AddressOp.Load);
1098 return ReferenceContainer.MakeType (ec.Module, instance_type);
1101 if (instance_type.IsEnum || instance_type.IsStruct) {
1103 ec.Emit (OpCodes.Box, instance_type);
1104 return ec.BuiltinTypes.Object;
1108 return instance_type;
1111 static MetaType[] GetVarargsTypes (MethodSpec method, Arguments arguments)
1113 AParametersCollection pd = method.Parameters;
1115 Argument a = arguments[pd.Count - 1];
1116 Arglist list = (Arglist) a.Expr;
1118 return list.ArgumentTypes;
1122 // Used to decide whether call or callvirt is needed
1124 static bool IsVirtualCallRequired (Expression instance, MethodSpec method)
1127 // There are 2 scenarious where we emit callvirt
1129 // Case 1: A method is virtual and it's not used to call base
1130 // Case 2: A method instance expression can be null. In this casen callvirt ensures
1131 // correct NRE exception when the method is called
1133 var decl_type = method.DeclaringType;
1134 if (decl_type.IsStruct || decl_type.IsEnum)
1137 if (instance is BaseThis)
1141 // It's non-virtual and will never be null and it can be determined
1142 // whether it's known value or reference type by verifier
1144 if (!method.IsVirtual && (instance is This || instance is New || instance is ArrayCreation || instance is DelegateCreation) &&
1145 !instance.Type.IsGenericParameter)