2 // Mono.ILASM.MethodDef
5 // Jackson Harper (Jackson@LatitudeGeo.com)
7 // (C) 2003 Jackson Harper, All rights reserved
13 using System.Collections;
14 using System.Security;
16 using Mono.CompilerServices.SymbolWriter;
18 namespace Mono.ILASM {
20 public class MethodDef : ICustomAttrTarget, IDeclSecurityTarget {
22 private PEAPI.MethAttr meth_attr;
23 private PEAPI.CallConv call_conv;
24 private PEAPI.ImplAttr impl_attr;
26 private string signature;
27 private Hashtable vararg_sig_table;
28 private ParamDef ret_param;
29 private ArrayList param_list;
30 private ArrayList inst_list;
31 private ArrayList customattr_list;
32 private DeclSecurity decl_sec;
33 private Hashtable label_table;
34 private Hashtable labelref_table;
35 private ArrayList label_list;
36 private PEAPI.MethodDef methoddef;
37 private bool entry_point;
38 private bool zero_init;
39 private bool is_resolved;
40 private bool is_defined;
41 private ArrayList local_list;
42 private ArrayList named_local_tables;
43 private int current_scope_depth;
44 private bool init_locals;
45 private int max_stack;
46 private bool pinvoke_info;
47 private ExternModule pinvoke_mod;
48 private string pinvoke_name;
49 private PEAPI.PInvokeAttr pinvoke_attr;
50 private SourceMethod source;
51 private TypeDef type_def;
52 private GenericParameters gen_params;
53 private Location start;
54 private CodeGen codegen;
56 public MethodDef (CodeGen codegen, PEAPI.MethAttr meth_attr,
57 PEAPI.CallConv call_conv, PEAPI.ImplAttr impl_attr,
58 string name, BaseTypeRef ret_type, ArrayList param_list,
59 Location start, GenericParameters gen_params, TypeDef type_def)
61 this.codegen = codegen;
62 this.meth_attr = meth_attr;
63 this.call_conv = call_conv;
64 this.impl_attr = impl_attr;
66 this.param_list = param_list;
67 this.type_def = type_def;
68 this.gen_params = gen_params;
69 this.ret_param = new ParamDef (PEAPI.ParamAttr.Default, "", ret_type);
70 this.start = (Location) start.Clone ();
72 inst_list = new ArrayList ();
73 label_table = new Hashtable ();
74 labelref_table = new Hashtable ();
75 label_list = new ArrayList ();
76 local_list = new ArrayList ();
77 named_local_tables = new ArrayList ();
78 named_local_tables.Add (new Hashtable ());
79 current_scope_depth = 0;
92 codegen.BeginMethodDef (this);
94 if (codegen.SymbolWriter != null)
95 source = codegen.SymbolWriter.BeginMethod (this, start);
102 public string Signature {
103 get { return signature; }
106 public BaseTypeRef RetType {
107 get { return ret_param.Type; }
110 public PEAPI.CallConv CallConv {
111 get { return call_conv; }
114 public PEAPI.MethodDef PeapiMethodDef {
115 get { return methoddef; }
118 public PEAPI.MethAttr Attributes {
119 get { return meth_attr; }
120 set { meth_attr = value; }
123 public bool IsVararg {
124 get { return (call_conv & PEAPI.CallConv.Vararg) != 0; }
127 public bool IsStatic {
128 get { return (meth_attr & PEAPI.MethAttr.Static) != 0; }
131 public bool IsVirtual {
132 get { return (meth_attr & PEAPI.MethAttr.Virtual) != 0; }
135 public bool IsAbstract {
136 get { return (meth_attr & PEAPI.MethAttr.Abstract) != 0; }
139 public Location StartLocation {
140 get { return start; }
143 public DeclSecurity DeclSecurity {
145 if (decl_sec == null)
146 decl_sec = new DeclSecurity ();
151 public string FullName {
153 if (type_def == null)
155 return type_def.FullName + "." + Name;
159 public BaseTypeRef[] ParamTypeList () {
161 if (param_list == null)
162 return new BaseTypeRef[0];
164 BaseTypeRef[] type_list = new BaseTypeRef[param_list.Count];
165 foreach (ParamDef param in param_list) {
166 type_list[count++] = param.Type;
171 public void AddPInvokeInfo (PEAPI.PInvokeAttr pinvoke_attr, ExternModule pinvoke_mod,
174 this.pinvoke_attr = pinvoke_attr;
175 this.pinvoke_mod = pinvoke_mod;
176 this.pinvoke_name = pinvoke_name;
180 public int GenParamCount {
181 get { return (gen_params != null ? gen_params.Count : 0); }
184 public GenericParameter GetGenericParam (string id)
186 if (gen_params == null)
189 return gen_params.GetGenericParam (id);
192 public GenericParameter GetGenericParam (int index)
194 if (gen_params == null || index < 0 || index >= gen_params.Count)
197 return gen_params [index];
200 public int GetGenericParamNum (string id)
202 if (gen_params == null)
205 return gen_params.GetGenericParamNum (id);
208 public void AddCustomAttribute (CustomAttr customattr)
210 if (customattr_list == null)
211 customattr_list = new ArrayList ();
213 customattr_list.Add (customattr);
216 public void AddRetTypeMarshalInfo (PEAPI.NativeType native_type)
218 this.ret_param.AddMarshalInfo (native_type);
221 //try/catch scope, used to scope local vars
222 public void BeginLocalsScope ()
224 current_scope_depth ++;
225 named_local_tables.Add (new Hashtable ());
228 public void EndLocalsScope ()
230 named_local_tables.RemoveAt (current_scope_depth);
231 current_scope_depth --;
234 public void AddLocals (ArrayList local_list)
236 int slot_pos = this.local_list.Count;
238 Hashtable current_named_table = null;
239 current_named_table = (Hashtable) named_local_tables [current_scope_depth];
241 foreach (Local local in local_list) {
242 if (local.Slot == -1) {
243 local.Slot = slot_pos;
246 if (local.Name == null)
249 if (!current_named_table.Contains (local.Name))
250 current_named_table.Add (local.Name, local);
253 this.local_list.AddRange (local_list);
256 public Local GetNamedLocal (string name)
259 int i = current_scope_depth;
260 while (ret == null && i >= 0) {
261 Hashtable current_named_table = (Hashtable) named_local_tables [i];
262 ret = (Local) current_named_table [name];
270 public int GetNamedLocalSlot (string name)
272 Local local = GetNamedLocal (name);
279 public int GetNamedParamPos (string name)
282 if (param_list == null)
287 foreach (ParamDef param in param_list) {
289 if (param.Name.CompareTo (name) == 0)
296 public LocalVariableEntry[] GetLocalVars()
298 ArrayList named_locals = new ArrayList ();
299 foreach (Local local in local_list) {
300 if (local.Name != null) { // only named variables
301 named_locals.Add (new LocalVariableEntry(local.Slot, local.Name, 0));
304 return (LocalVariableEntry []) named_locals.ToArray (typeof (LocalVariableEntry));
308 /* index - 0: return type
309 * 1: params start from this
311 public ParamDef GetParam (int index)
316 if ((param_list == null) || (index < 0) || (index > param_list.Count))
319 index --; /* param_list has params zero-based */
321 if (param_list [index] != null)
322 return (ParamDef)param_list [index];
327 public void InitLocals ()
332 public void EntryPoint ()
335 Report.Error ("Non-static method as entrypoint.");
339 public void ZeroInit ()
344 public void SetMaxStack (int max_stack)
346 this.max_stack = max_stack;
349 public void ResolveGenParam (PEAPI.GenParam gpar)
351 if (gpar.Index != -1)
354 if (gpar.Type == PEAPI.GenParamType.MVar)
355 gpar.Index = GetGenericParamNum (gpar.Name);
357 gpar.Index = type_def.GetGenericParamNum (gpar.Name);
360 Report.Error (String.Format ("Invalid {0}type parameter '{1}'",
361 (gpar.Type == PEAPI.GenParamType.MVar ? "method " : ""),
365 public void ResolveGenParams ()
367 GenericParameters type_params = (type_def != null) ? type_def.TypeParameters : null;
369 if (gen_params == null && type_params == null)
372 if (gen_params != null)
373 gen_params.ResolveConstraints (type_params, gen_params);
375 BaseGenericTypeRef gtr = RetType as BaseGenericTypeRef;
377 gtr.Resolve (type_params, gen_params);
379 if (param_list == null)
382 foreach (ParamDef param in param_list) {
383 gtr = param.Type as BaseGenericTypeRef;
385 gtr.Resolve (type_params, gen_params);
389 public PEAPI.MethodDef Resolve (CodeGen code_gen)
391 return Resolve (code_gen, null);
394 public PEAPI.MethodDef Resolve (CodeGen code_gen, PEAPI.ClassDef classdef)
399 PEAPI.Param [] param_array = GenerateParams (code_gen);
401 ret_param.Define (code_gen);
403 if (classdef == null)
404 methoddef = code_gen.PEFile.AddMethod (meth_attr, impl_attr,
405 name, ret_param.PeapiParam, param_array);
407 methoddef = classdef.AddMethod (meth_attr, impl_attr,
408 name, ret_param.PeapiParam, param_array);
410 methoddef.AddCallConv (call_conv);
417 private PEAPI.Param [] GenerateParams (CodeGen code_gen)
419 PEAPI.Param[] param_array;
421 if (param_list != null && param_list.Count > 0) {
422 int param_count = param_list.Count;
424 // Remove the last param if its the sentinel, not sure what
425 // should happen with more then one sentinel
426 ParamDef last = (ParamDef) param_list [param_count-1];
427 if (last.IsSentinel ())
430 param_array = new PEAPI.Param [param_count];
431 for (int i = 0; i < param_count; i++) {
432 ParamDef paramdef = (ParamDef) param_list [i];
433 paramdef.Define (code_gen);
434 param_array [i] = paramdef.PeapiParam;
438 param_array = new PEAPI.Param [0];
444 public PEAPI.MethodRef GetVarargSig (PEAPI.Type[] opt, string full_signature)
447 throw new InternalErrorException ("Methods must be resolved before a vararg sig can be created.");
449 PEAPI.MethodRef methref = null;
450 if (vararg_sig_table == null) {
451 vararg_sig_table = new Hashtable ();
453 methref = vararg_sig_table [full_signature] as PEAPI.MethodRef;
456 if (methref == null) {
457 methref = methoddef.MakeVarArgSignature (opt);
458 vararg_sig_table [full_signature] = methref;
465 /// Define a member method
467 public void Define (CodeGen code_gen)
472 if (type_def == null)
474 Resolve (code_gen, null);
476 Resolve (code_gen, (PEAPI.ClassDef) type_def.ClassDef);
478 WriteCode (code_gen, methoddef);
480 //code_gen.Report.Message (String.Format ("Assembled method {0}::{1}", typedef.FullName, name));
484 public void AddInstr (IInstr instr)
486 inst_list.Add (instr);
489 protected void WriteCode (CodeGen code_gen, PEAPI.MethodDef methoddef)
491 /// Add the custrom attributes to this method
492 if (customattr_list != null)
493 foreach (CustomAttr customattr in customattr_list) {
494 customattr.AddTo (code_gen, methoddef);
495 if (customattr.IsSuppressUnmanaged (code_gen))
496 methoddef.AddMethAttribute (PEAPI.MethAttr.HasSecurity);
499 /// Add declarative security to this method
500 if (decl_sec != null) {
501 decl_sec.AddTo (code_gen, methoddef);
502 methoddef.AddMethAttribute (PEAPI.MethAttr.HasSecurity);
505 // Generic type parameters
506 if (gen_params != null)
507 gen_params.Resolve (code_gen, methoddef);
509 if (type_def == null) {
511 meth_attr &= ~PEAPI.MethAttr.Abstract;
512 meth_attr |= PEAPI.MethAttr.Static;
514 if ((inst_list.Count > 0) && type_def.IsInterface && !IsStatic)
515 Report.Error (start, "Method cannot have body if it is non-static declared in an interface");
518 if (!type_def.IsAbstract)
519 Report.Error (start, String.Format ("Abstract method '{0}' in non-abstract class '{1}'",
520 Name, type_def.FullName));
521 if (inst_list.Count > 0)
522 Report.Error (start, "Method cannot have body if it is abstract.");
528 methoddef.DeclareEntryPoint ();
530 if (local_list.Count > 0) {
531 int ec = Report.ErrorCount;
532 PEAPI.Local[] local_array = new PEAPI.Local[local_list.Count];
534 foreach (Local local in local_list)
535 local_array[local.Slot] = local.GetPeapiLocal (code_gen);
537 if (Report.ErrorCount > ec)
543 methoddef.AddLocals (local_array, init_locals);
546 /// Nothing seems to work if maxstack is not set,
547 /// i need to find out if this NEEDs to be set
548 /// and what its default value should be
551 methoddef.SetMaxStack (max_stack);
554 methoddef.AddPInvokeInfo (pinvoke_mod.ModuleRef,
555 (pinvoke_name != null ? pinvoke_name : name), pinvoke_attr);
558 if ((impl_attr & PEAPI.ImplAttr.Runtime) == PEAPI.ImplAttr.Runtime) {
559 if (inst_list.Count > 0)
560 Report.Error (start, String.Format ("Method cannot have body if it is non-IL runtime-supplied, '{0}'",
563 if (((impl_attr & PEAPI.ImplAttr.Native) != 0) ||
564 ((impl_attr & PEAPI.ImplAttr.Unmanaged) != 0))
565 Report.Error (start, String.Format ("Cannot compile native/unmanaged method, '{0}'",
569 if (inst_list.Count > 0) {
571 if ((impl_attr & PEAPI.ImplAttr.InternalCall) != 0)
572 Report.Error (start, String.Format ("Method cannot have body if it is an internal call, '{0}'",
576 Report.Error (start, String.Format ("Method cannot have body if it is pinvoke, '{0}'",
580 ((impl_attr & PEAPI.ImplAttr.Runtime) != 0) ||
581 ((impl_attr & PEAPI.ImplAttr.InternalCall) != 0))
582 /* No body required */
585 Report.Warning (start, "Method has no body, 'ret' emitted.");
586 AddInstr (new SimpInstr (PEAPI.Op.ret, start));
589 PEAPI.CILInstructions cil = methoddef.CreateCodeBuffer ();
590 /// Create all the labels
591 /// TODO: Most labels don't actually need to be created so we could
592 /// probably only create the ones that need to be
593 LabelInfo[] label_info = new LabelInfo[label_table.Count + label_list.Count];
594 label_table.Values.CopyTo (label_info, 0);
595 label_list.CopyTo (label_info, label_table.Count);
596 int previous_pos = -1;
597 LabelInfo previous_label = null;
598 Array.Sort (label_info);
600 foreach (LabelInfo label in label_info) {
601 if (label.UseOffset) {
602 label.Define (new PEAPI.CILLabel (label.Offset, true));
605 if (label.Pos == previous_pos)
606 label.Label = previous_label.Label;
608 label.Define (cil.NewLabel ());
610 previous_label = label;
611 previous_pos = label.Pos;
614 // Set all the label refs
615 foreach (LabelInfo label in labelref_table.Values) {
616 LabelInfo def = (LabelInfo) label_table[label.Name];
618 Report.Error ("Undefined Label: " + label);
621 label.Label = def.Label;
625 int next_label_pos = (label_info.Length > 0 ? label_info[0].Pos : -1);
627 for (int i=0; i<inst_list.Count; i++) {
628 IInstr instr = (IInstr) inst_list[i];
629 if (next_label_pos == i) {
630 cil.CodeLabel (label_info[label_pos].Label);
631 if (label_pos < label_info.Length) {
632 while (next_label_pos == i && ++label_pos < label_info.Length) {
633 if (label_info[label_pos].UseOffset)
634 cil.CodeLabel (label_info[label_pos].Label);
635 next_label_pos = label_info[label_pos].Pos;
638 if (label_pos >= label_info.Length)
642 source.MarkLocation (instr.Location.line, cil.Offset);
643 instr.Emit (code_gen, this, cil);
647 source.MarkLocation (source.EndLine, cil.Offset);
650 public LabelInfo AddLabel (string name)
652 LabelInfo label_info = (LabelInfo) label_table[name];
653 if (label_info != null)
654 Report.Error ("Duplicate label '" + name + "'");
656 label_info = new LabelInfo (name, inst_list.Count);
657 label_table [name] = label_info;
661 public LabelInfo AddLabelRef (string name)
663 LabelInfo label_info = (LabelInfo) label_table[name];
664 if (label_info != null)
666 label_info = (LabelInfo) labelref_table[name];
667 if (label_info != null)
669 label_info = new LabelInfo (name, -1);
670 labelref_table.Add (name, label_info);
674 public LabelInfo AddLabel (int offset)
676 // We go pos + 1 so this line is not counted
677 LabelInfo label_info = new LabelInfo (null, inst_list.Count+1, (uint) offset);
678 label_list.Add (label_info);
682 public LabelInfo AddLabel ()
684 LabelInfo label_info = new LabelInfo (null, inst_list.Count);
685 label_list.Add (label_info);
689 public PEAPI.CILLabel GetLabelDef (string name)
691 LabelInfo label_info = (LabelInfo) label_table[name];
693 return label_info.Label;
696 public PEAPI.CILLabel GetLabelDef (int pos)
698 foreach (LabelInfo li in label_list) {
705 private void CreateSignature ()
708 signature = CreateVarargSignature (RetType, name, param_list);
710 signature = CreateSignature (RetType, name, param_list, GenParamCount, Attributes);
713 static string CreateSignature (BaseTypeRef RetType, string name, IList param_list, int gen_param_count, PEAPI.MethAttr attrs)
715 StringBuilder builder = new StringBuilder ();
717 if ((attrs & PEAPI.MethAttr.Static) == 0)
718 builder.Append ("instance ");
720 builder.Append (RetType.FullName);
721 builder.Append (" ");
722 builder.Append (name);
723 if (gen_param_count > 0)
724 builder.AppendFormat ("`{0}", gen_param_count);
725 builder.Append ('(');
727 if (param_list != null) {
729 foreach (ParamDef paramdef in param_list) {
731 builder.Append (',');
732 builder.Append (paramdef.TypeName);
736 builder.Append (')');
738 return builder.ToString ();
741 static string CreateVarargSignature (BaseTypeRef RetType, string name, IList param_list)
743 StringBuilder builder = new StringBuilder ();
744 ParamDef last = null;
746 builder.Append (RetType.FullName);
747 builder.Append (" ");
748 builder.Append (name);
749 builder.Append ('(');
752 if (param_list != null) {
753 foreach (ParamDef paramdef in param_list) {
755 builder.Append (',');
756 builder.Append (paramdef.TypeName);
759 last = (ParamDef) param_list[param_list.Count - 1];
763 if (last == null || !last.IsSentinel ()) {
765 builder.Append (',');
766 builder.Append ("...");
769 builder.Append (')');
771 return builder.ToString ();
774 // @include_optional: include optional parameters for vararg methods
775 // This will be true mostly for *Ref use, eg. methodrefs at call sites
776 // and false for *Def (include only the required params)
777 public static string CreateSignature (BaseTypeRef RetType, PEAPI.CallConv call_conv, string name,
778 BaseTypeRef[] param_list, int gen_param_count, bool include_optional)
780 if ((call_conv & PEAPI.CallConv.Vararg) != 0)
781 return CreateVarargSignature (RetType, name, param_list, include_optional);
783 return CreateSignature (RetType, name, param_list, gen_param_count, include_optional, call_conv);
786 static string CreateVarargSignature (BaseTypeRef RetType, string name, BaseTypeRef [] param_list, bool include_optional)
788 StringBuilder builder = new StringBuilder ();
789 BaseTypeRef last = null;
791 builder.Append (RetType.FullName);
792 builder.Append (" ");
793 builder.Append (name);
794 builder.Append ('(');
797 if (param_list != null && param_list.Length > 0) {
798 foreach (BaseTypeRef param in param_list) {
800 builder.Append (',');
801 builder.Append (param.FullName);
804 if (!include_optional && param is SentinelTypeRef)
810 if (!include_optional && (last == null || !(last is SentinelTypeRef))) {
812 builder.Append (',');
813 builder.Append ("...");
816 builder.Append (')');
818 return builder.ToString ();
821 static string CreateSignature (BaseTypeRef RetType, string name, BaseTypeRef[] param_list, int gen_param_count, bool include_optional, PEAPI.CallConv call_conv)
823 StringBuilder builder = new StringBuilder ();
825 if ((call_conv & PEAPI.CallConv.Instance) != 0)
826 builder.Append ("instance ");
829 builder.Append (RetType.FullName);
830 builder.Append (" ");
831 builder.Append (name);
832 if (gen_param_count > 0)
833 builder.AppendFormat ("`{0}", gen_param_count);
834 builder.Append ('(');
836 if (param_list != null) {
838 foreach (BaseTypeRef param in param_list) {
840 builder.Append (',');
841 builder.Append (param.FullName);
843 if (!include_optional && param is SentinelTypeRef)
847 builder.Append (')');
849 return builder.ToString ();
852 private void FixAttributes ()
854 if (name == ".ctor" || name == ".cctor")
855 meth_attr |= PEAPI.MethAttr.SpecialName | PEAPI.MethAttr.RTSpecialName;
856 // If methods aren't flagged as static they are instance
857 if ((PEAPI.MethAttr.Static & meth_attr) == 0)
858 call_conv |= PEAPI.CallConv.Instance;