3 // System.Reflection.Emit/ILGenerator.cs
6 // Paolo Molaro (lupus@ximian.com)
8 // (C) 2001 Ximian, Inc. http://www.ximian.com
12 using System.Collections;
13 using System.Diagnostics.SymbolStore;
14 using System.Runtime.InteropServices;
15 using Mono.CSharp.Debugger;
17 namespace System.Reflection.Emit {
19 internal struct ILExceptionBlock {
20 public const int CATCH = 0;
21 public const int FILTER = 1;
22 public const int FINALLY = 2;
23 public const int FAULT = 4;
29 internal int filter_offset;
31 internal void Debug () {
33 System.Console.Write ("\ttype="+type.ToString()+" start="+start.ToString()+" len="+len.ToString());
35 System.Console.WriteLine (" extype="+extype.ToString());
37 System.Console.WriteLine ("");
41 internal struct ILExceptionInfo {
42 ILExceptionBlock[] handlers;
47 internal int NumHandlers () {
48 return handlers.Length;
51 internal void AddCatch (Type extype, int offset) {
55 i = handlers.Length - 1;
56 handlers [i].type = ILExceptionBlock.CATCH;
57 handlers [i].start = offset;
58 handlers [i].extype = extype;
61 internal void AddFinally (int offset) {
65 i = handlers.Length - 1;
66 handlers [i].type = ILExceptionBlock.FINALLY;
67 handlers [i].start = offset;
68 handlers [i].extype = null;
71 internal void End (int offset) {
74 int i = handlers.Length - 1;
76 handlers [i].len = offset - handlers [i].start;
79 internal int LastClauseType () {
81 return handlers [handlers.Length-1].type;
83 return ILExceptionBlock.CATCH;
86 internal void Debug (int b) {
88 System.Console.WriteLine ("Handler {0} at {1}, len: {2}", b, start, len);
89 for (int i = 0; i < handlers.Length; ++i)
90 handlers [i].Debug ();
94 void add_block (int offset) {
95 if (handlers != null) {
96 int i = handlers.Length;
97 ILExceptionBlock[] new_b = new ILExceptionBlock [i + 1];
98 System.Array.Copy (handlers, new_b, i);
100 handlers [i].len = offset - handlers [i].start;
102 handlers = new ILExceptionBlock [1];
103 len = offset - start;
108 internal struct ILTokenInfo {
109 public MemberInfo member;
113 public class ILGenerator: Object {
114 private struct LabelFixup {
116 public int pos; // the location of the fixup
117 public int label_base; // the base address for this fixup
118 public int label_idx;
120 static Type void_type = typeof (void);
122 private MethodBase mbuilder; /* a MethodBuilder or ConstructorBuilder */
123 private int code_len;
124 private int max_stack;
125 private int cur_stack;
126 private LocalBuilder[] locals;
127 private ILExceptionInfo[] ex_handlers;
128 private int num_token_fixups;
129 private ILTokenInfo[] token_fixups;
130 private int[] label_to_addr;
131 private int num_labels;
132 private LabelFixup[] fixups;
133 private int num_fixups;
134 private ModuleBuilder module;
135 private AssemblyBuilder abuilder;
136 private IMonoSymbolWriter sym_writer;
137 private Stack scopes;
138 private int cur_block;
139 private Stack open_blocks;
141 internal ILGenerator (MethodBase mb, int size) {
145 code = new byte [size];
147 cur_stack = max_stack = 0;
148 num_fixups = num_labels = 0;
149 label_to_addr = new int [8];
150 fixups = new LabelFixup [8];
151 token_fixups = new ILTokenInfo [8];
152 num_token_fixups = 0;
153 if (mb is MethodBuilder) {
154 module = (ModuleBuilder)((MethodBuilder)mb).TypeBuilder.Module;
155 } else if (mb is ConstructorBuilder) {
156 module = (ModuleBuilder)((ConstructorBuilder)mb).TypeBuilder.Module;
158 abuilder = (AssemblyBuilder)module.Assembly;
159 sym_writer = module.symbol_writer;
160 open_blocks = new Stack ();
163 private void add_token_fixup (MemberInfo mi) {
164 if (num_token_fixups == token_fixups.Length) {
165 ILTokenInfo[] ntf = new ILTokenInfo [num_token_fixups * 2];
166 token_fixups.CopyTo (ntf, 0);
169 token_fixups [num_token_fixups].member = mi;
170 token_fixups [num_token_fixups++].code_pos = code_len;
173 private void make_room (int nbytes) {
174 if (code_len + nbytes < code.Length)
176 byte[] new_code = new byte [(code_len + nbytes) * 2 + 128];
177 System.Array.Copy (code, 0, new_code, 0, code.Length);
180 private void emit_int (int val) {
181 code [code_len++] = (byte) (val & 0xFF);
182 code [code_len++] = (byte) ((val >> 8) & 0xFF);
183 code [code_len++] = (byte) ((val >> 16) & 0xFF);
184 code [code_len++] = (byte) ((val >> 24) & 0xFF);
186 /* change to pass by ref to avoid copy */
187 private void ll_emit (OpCode opcode) {
189 * there is already enough room allocated in code.
191 // access op1 and op2 directly since the Value property is useless
192 if (opcode.Size == 2)
193 code [code_len++] = opcode.op1;
194 code [code_len++] = opcode.op2;
196 * We should probably keep track of stack needs here.
197 * Or we may want to run the verifier on the code before saving it
198 * (this may be needed anyway when the ILGenerator is not used...).
200 switch (opcode.StackBehaviourPush) {
201 case StackBehaviour.Push1:
202 case StackBehaviour.Pushi:
203 case StackBehaviour.Pushi8:
204 case StackBehaviour.Pushr4:
205 case StackBehaviour.Pushr8:
206 case StackBehaviour.Pushref:
207 case StackBehaviour.Varpush: /* again we are conservative and assume it pushes 1 */
210 case StackBehaviour.Push1_push1:
214 if (max_stack < cur_stack)
215 max_stack = cur_stack;
217 * Note that we adjust for the pop behaviour _after_ setting max_stack.
219 switch (opcode.StackBehaviourPop) {
220 case StackBehaviour.Varpop:
221 break; /* we are conservative and assume it doesn't decrease the stack needs */
222 case StackBehaviour.Pop1:
223 case StackBehaviour.Popi:
224 case StackBehaviour.Popref:
227 case StackBehaviour.Pop1_pop1:
228 case StackBehaviour.Popi_pop1:
229 case StackBehaviour.Popi_popi:
230 case StackBehaviour.Popi_popi8:
231 case StackBehaviour.Popi_popr4:
232 case StackBehaviour.Popi_popr8:
233 case StackBehaviour.Popref_pop1:
234 case StackBehaviour.Popref_popi:
237 case StackBehaviour.Popi_popi_popi:
238 case StackBehaviour.Popref_popi_popi:
239 case StackBehaviour.Popref_popi_popi8:
240 case StackBehaviour.Popref_popi_popr4:
241 case StackBehaviour.Popref_popi_popr8:
242 case StackBehaviour.Popref_popi_popref:
248 private static int target_len (OpCode opcode) {
249 if (opcode.operandType == OperandType.InlineBrTarget)
254 private void InternalEndClause () {
255 switch (ex_handlers [cur_block].LastClauseType ()) {
256 case ILExceptionBlock.CATCH:
257 // how could we optimize code size here?
258 Emit (OpCodes.Leave, ex_handlers [cur_block].end);
260 case ILExceptionBlock.FAULT:
261 case ILExceptionBlock.FINALLY:
262 Emit (OpCodes.Endfinally);
264 case ILExceptionBlock.FILTER:
265 Emit (OpCodes.Endfilter);
270 public virtual void BeginCatchBlock (Type exceptionType) {
271 if (open_blocks.Count <= 0)
272 throw new NotSupportedException ("Not in an exception block");
273 InternalEndClause ();
274 ex_handlers [cur_block].AddCatch (exceptionType, code_len);
275 cur_stack = 1; // the exception object is on the stack by default
276 if (max_stack < cur_stack)
277 max_stack = cur_stack;
278 //System.Console.WriteLine ("Begin catch Block: {0} {1}",exceptionType.ToString(), max_stack);
279 //throw new NotImplementedException ();
281 public virtual void BeginExceptFilterBlock () {
282 throw new NotImplementedException ();
284 public virtual Label BeginExceptionBlock () {
285 //System.Console.WriteLine ("Begin Block");
287 if (ex_handlers != null) {
288 cur_block = ex_handlers.Length;
289 ILExceptionInfo[] new_ex = new ILExceptionInfo [cur_block + 1];
290 System.Array.Copy (ex_handlers, new_ex, cur_block);
291 ex_handlers = new_ex;
293 ex_handlers = new ILExceptionInfo [1];
296 open_blocks.Push (cur_block);
297 ex_handlers [cur_block].start = code_len;
298 return ex_handlers [cur_block].end = DefineLabel ();
300 public virtual void BeginFaultBlock() {
301 if (open_blocks.Count <= 0)
302 throw new NotSupportedException ("Not in an exception block");
303 //System.Console.WriteLine ("Begin fault Block");
304 //throw new NotImplementedException ();
306 public virtual void BeginFinallyBlock() {
307 if (open_blocks.Count <= 0)
308 throw new NotSupportedException ("Not in an exception block");
309 InternalEndClause ();
310 //System.Console.WriteLine ("Begin finally Block");
311 ex_handlers [cur_block].AddFinally (code_len);
313 public virtual void BeginScope () {
314 if (sym_writer != null) {
316 scopes = new Stack ();
317 scopes.Push (sym_writer.OpenScope (code_len));
320 public LocalBuilder DeclareLocal (Type localType) {
321 LocalBuilder res = new LocalBuilder (module, localType, this);
322 if (locals != null) {
323 LocalBuilder[] new_l = new LocalBuilder [locals.Length + 1];
324 System.Array.Copy (locals, new_l, locals.Length);
325 new_l [locals.Length] = res;
328 locals = new LocalBuilder [1];
331 res.position = (uint)(locals.Length - 1);
334 public virtual Label DefineLabel () {
335 if (num_labels >= label_to_addr.Length) {
336 int[] new_l = new int [label_to_addr.Length * 2];
337 System.Array.Copy (label_to_addr, new_l, label_to_addr.Length);
338 label_to_addr = new_l;
340 label_to_addr [num_labels] = -1;
341 return new Label (num_labels++);
343 public virtual void Emit (OpCode opcode) {
347 public virtual void Emit (OpCode opcode, Byte val) {
350 code [code_len++] = val;
352 public virtual void Emit (OpCode opcode, ConstructorInfo constructor) {
353 int token = abuilder.GetToken (constructor);
356 if (constructor.DeclaringType.Module == module)
357 add_token_fixup (constructor);
359 ParameterInfo[] mparams = constructor.GetParameters();
361 cur_stack -= mparams.Length;
363 public virtual void Emit (OpCode opcode, double val) {
364 byte[] s = System.BitConverter.GetBytes (val);
367 if (BitConverter.IsLittleEndian){
368 System.Array.Copy (s, 0, code, code_len, 8);
371 code [code_len++] = s [7];
372 code [code_len++] = s [6];
373 code [code_len++] = s [5];
374 code [code_len++] = s [4];
375 code [code_len++] = s [3];
376 code [code_len++] = s [2];
377 code [code_len++] = s [1];
378 code [code_len++] = s [0];
381 public virtual void Emit (OpCode opcode, FieldInfo field) {
382 int token = abuilder.GetToken (field);
385 if (field.DeclaringType.Module == module)
386 add_token_fixup (field);
389 public virtual void Emit (OpCode opcode, Int16 val) {
392 code [code_len++] = (byte) (val & 0xFF);
393 code [code_len++] = (byte) ((val >> 8) & 0xFF);
395 public virtual void Emit (OpCode opcode, int val) {
400 public virtual void Emit (OpCode opcode, long val) {
403 code [code_len++] = (byte) (val & 0xFF);
404 code [code_len++] = (byte) ((val >> 8) & 0xFF);
405 code [code_len++] = (byte) ((val >> 16) & 0xFF);
406 code [code_len++] = (byte) ((val >> 24) & 0xFF);
407 code [code_len++] = (byte) ((val >> 32) & 0xFF);
408 code [code_len++] = (byte) ((val >> 40) & 0xFF);
409 code [code_len++] = (byte) ((val >> 48) & 0xFF);
410 code [code_len++] = (byte) ((val >> 56) & 0xFF);
412 public virtual void Emit (OpCode opcode, Label label) {
413 int tlen = target_len (opcode);
416 if (num_fixups >= fixups.Length) {
417 LabelFixup[] newf = new LabelFixup [fixups.Length + 16];
418 System.Array.Copy (fixups, newf, fixups.Length);
421 fixups [num_fixups].size = tlen;
422 fixups [num_fixups].pos = code_len;
423 fixups [num_fixups].label_base = code_len;
424 fixups [num_fixups].label_idx = label.label;
429 public virtual void Emit (OpCode opcode, Label[] labels) {
430 /* opcode needs to be switch. */
431 int count = labels.Length;
432 make_room (6 + count * 4);
434 int switch_base = code_len + count*4;
436 if (num_fixups + count >= fixups.Length) {
437 LabelFixup[] newf = new LabelFixup [fixups.Length + count + 16];
438 System.Array.Copy (fixups, newf, fixups.Length);
441 for (int i = 0; i < count; ++i) {
442 fixups [num_fixups].size = 4;
443 fixups [num_fixups].pos = code_len;
444 fixups [num_fixups].label_base = switch_base;
445 fixups [num_fixups].label_idx = labels [i].label;
450 public virtual void Emit (OpCode opcode, LocalBuilder lbuilder) {
451 uint pos = lbuilder.position;
452 bool load_addr = false;
453 bool is_store = false;
456 if (lbuilder.ilgen != this)
457 throw new Exception ("Trying to emit a local from a different ILGenerator.");
459 /* inline the code from ll_emit () to optimize il code size */
460 if (opcode.StackBehaviourPop == StackBehaviour.Pop1) {
465 if (cur_stack > max_stack)
466 max_stack = cur_stack;
467 load_addr = opcode.StackBehaviourPush == StackBehaviour.Pushi;
471 code [code_len++] = (byte)0x12;
472 code [code_len++] = (byte)pos;
474 code [code_len++] = (byte)0xfe;
475 code [code_len++] = (byte)0x0d;
476 code [code_len++] = (byte)(pos & 0xff);
477 code [code_len++] = (byte)((pos >> 8) & 0xff);
482 code [code_len++] = (byte)(0x0a + pos);
483 } else if (pos < 256) {
484 code [code_len++] = (byte)0x13;
485 code [code_len++] = (byte)pos;
487 code [code_len++] = (byte)0xfe;
488 code [code_len++] = (byte)0x0e;
489 code [code_len++] = (byte)(pos & 0xff);
490 code [code_len++] = (byte)((pos >> 8) & 0xff);
494 code [code_len++] = (byte)(0x06 + pos);
495 } else if (pos < 256) {
496 code [code_len++] = (byte)0x11;
497 code [code_len++] = (byte)pos;
499 code [code_len++] = (byte)0xfe;
500 code [code_len++] = (byte)0x0c;
501 code [code_len++] = (byte)(pos & 0xff);
502 code [code_len++] = (byte)((pos >> 8) & 0xff);
507 public virtual void Emit (OpCode opcode, MethodInfo method) {
509 throw new ArgumentNullException ("method");
511 int token = abuilder.GetToken (method);
514 if (method.DeclaringType.Module == module)
515 add_token_fixup (method);
517 if (method.ReturnType != void_type)
519 ParameterInfo[] mparams = method.GetParameters();
521 cur_stack -= mparams.Length;
523 [CLSCompliant(false)]
524 public void Emit (OpCode opcode, sbyte val) {
527 code [code_len++] = (byte)val;
530 public virtual void Emit (OpCode opcode, SignatureHelper shelper) {
531 int token = abuilder.GetToken (shelper);
536 public virtual void Emit (OpCode opcode, float val) {
537 byte[] s = System.BitConverter.GetBytes (val);
540 if (BitConverter.IsLittleEndian){
541 System.Array.Copy (s, 0, code, code_len, 4);
544 code [code_len++] = s [3];
545 code [code_len++] = s [2];
546 code [code_len++] = s [1];
547 code [code_len++] = s [0];
550 public virtual void Emit (OpCode opcode, string val) {
551 int token = abuilder.GetToken (val);
556 public virtual void Emit (OpCode opcode, Type type) {
559 emit_int (abuilder.GetToken (type));
562 public void EmitCall (OpCode opcode, MethodInfo methodinfo, Type[] optionalParamTypes) {
563 throw new NotImplementedException ();
566 public void EmitCalli (OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] paramTypes) {
567 SignatureHelper helper
568 = SignatureHelper.GetMethodSigHelper (module, 0, unmanagedCallConv, returnType, paramTypes);
569 Emit (opcode, helper);
572 public void EmitCalli (OpCode opcode, CallingConventions callConv, Type returnType, Type[] paramTypes, Type[] optionalParamTypes) {
573 if (optionalParamTypes != null)
574 throw new NotImplementedException ();
576 SignatureHelper helper
577 = SignatureHelper.GetMethodSigHelper (module, callConv, 0, returnType, paramTypes);
578 Emit (opcode, helper);
581 public virtual void EmitWriteLine (FieldInfo field) {
582 throw new NotImplementedException ();
584 public virtual void EmitWriteLine (LocalBuilder lbuilder) {
585 throw new NotImplementedException ();
587 public virtual void EmitWriteLine (string val) {
588 Emit (OpCodes.Ldstr, val);
590 typeof (Console).GetMethod ("WriteLine",
591 new Type[1] { typeof(string)}));
594 public virtual void EndExceptionBlock () {
595 if (open_blocks.Count <= 0)
596 throw new NotSupportedException ("Not in an exception block");
597 InternalEndClause ();
598 MarkLabel (ex_handlers [cur_block].end);
599 ex_handlers [cur_block].End (code_len);
600 ex_handlers [cur_block].Debug (cur_block);
601 //System.Console.WriteLine ("End Block {0} (handlers: {1})", cur_block, ex_handlers [cur_block].NumHandlers ());
603 if (open_blocks.Count > 0)
604 cur_block = (int)open_blocks.Peek ();
605 //Console.WriteLine ("curblock restored to {0}", cur_block);
606 //throw new NotImplementedException ();
608 public virtual void EndScope () {
609 if (sym_writer != null) {
610 sym_writer.CloseScope (code_len);
612 throw new InvalidOperationException ();
616 public virtual void MarkLabel (Label loc) {
617 if (loc.label < 0 || loc.label >= num_labels)
618 throw new System.ArgumentException ("The label is not valid");
619 if (label_to_addr [loc.label] >= 0)
620 throw new System.ArgumentException ("The label was already defined");
621 label_to_addr [loc.label] = code_len;
623 public virtual void MarkSequencePoint (ISymbolDocumentWriter document, int startLine,
624 int startColumn, int endLine, int endColumn) {
625 if (sym_writer == null)
628 sym_writer.MarkSequencePoint (code_len, startLine, startColumn);
630 public virtual void ThrowException (Type exceptionType) {
631 throw new NotImplementedException ();
633 public void UsingNamespace (String usingNamespace) {
634 throw new NotImplementedException ();
637 internal void label_fixup () {
639 for (i = 0; i < num_fixups; ++i) {
640 int diff = label_to_addr [fixups [i].label_idx] - fixups [i].label_base;
641 if (fixups [i].size == 1) {
642 code [fixups [i].pos] = (byte)((sbyte) diff - 1);
644 int old_cl = code_len;
645 code_len = fixups [i].pos;