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;
16 namespace System.Reflection.Emit {
18 internal struct ILExceptionBlock {
19 public const int CATCH = 0;
20 public const int FILTER = 1;
21 public const int FINALLY = 2;
22 public const int FAULT = 4;
28 internal int filter_offset;
30 internal void Debug () {
32 System.Console.Write ("\ttype="+type.ToString()+" start="+start.ToString()+" len="+len.ToString());
34 System.Console.WriteLine (" extype="+extype.ToString());
36 System.Console.WriteLine ("");
40 internal struct ILExceptionInfo {
41 ILExceptionBlock[] handlers;
46 internal int NumHandlers () {
47 return handlers.Length;
50 internal void AddCatch (Type extype, int offset) {
54 i = handlers.Length - 1;
55 handlers [i].type = ILExceptionBlock.CATCH;
56 handlers [i].start = offset;
57 handlers [i].extype = extype;
60 internal void AddFinally (int offset) {
64 i = handlers.Length - 1;
65 handlers [i].type = ILExceptionBlock.FINALLY;
66 handlers [i].start = offset;
67 handlers [i].extype = null;
70 internal void End (int offset) {
73 int i = handlers.Length - 1;
75 handlers [i].len = offset - handlers [i].start;
78 internal int LastClauseType () {
80 return handlers [handlers.Length-1].type;
82 return ILExceptionBlock.CATCH;
85 internal void Debug (int b) {
87 System.Console.WriteLine ("Handler {0} at {1}, len: {2}", b, start, len);
88 for (int i = 0; i < handlers.Length; ++i)
89 handlers [i].Debug ();
93 void add_block (int offset) {
94 if (handlers != null) {
95 int i = handlers.Length;
96 ILExceptionBlock[] new_b = new ILExceptionBlock [i + 1];
97 System.Array.Copy (handlers, new_b, i);
99 handlers [i].len = offset - handlers [i].start;
101 handlers = new ILExceptionBlock [1];
102 len = offset - start;
107 internal struct ILTokenInfo {
108 public MemberInfo member;
112 public class ILGenerator: Object {
113 private struct LabelFixup {
115 public int pos; // the location of the fixup
116 public int label_base; // the base address for this fixup
117 public int label_idx;
119 static Type void_type = typeof (void);
121 private MethodBase mbuilder; /* a MethodBuilder or ConstructorBuilder */
122 private int code_len;
123 private int max_stack;
124 private int cur_stack;
125 private LocalBuilder[] locals;
126 private ILExceptionInfo[] ex_handlers;
127 private int num_token_fixups;
128 private ILTokenInfo[] token_fixups;
129 private int[] label_to_addr;
130 private int num_labels;
131 private LabelFixup[] fixups;
132 private int num_fixups;
133 private ModuleBuilder module;
134 private AssemblyBuilder abuilder;
135 private ISymbolWriter sym_writer;
136 private Stack scopes;
137 private int cur_block;
138 private Stack open_blocks;
140 internal ILGenerator (MethodBase mb, int size) {
144 code = new byte [size];
146 cur_stack = max_stack = 0;
147 num_fixups = num_labels = 0;
148 label_to_addr = new int [8];
149 fixups = new LabelFixup [8];
150 token_fixups = new ILTokenInfo [8];
151 num_token_fixups = 0;
152 if (mb is MethodBuilder) {
153 module = (ModuleBuilder)((MethodBuilder)mb).TypeBuilder.Module;
154 } else if (mb is ConstructorBuilder) {
155 module = (ModuleBuilder)((ConstructorBuilder)mb).TypeBuilder.Module;
157 abuilder = (AssemblyBuilder)module.Assembly;
158 sym_writer = module.GetSymWriter ();
159 open_blocks = new Stack ();
162 private void add_token_fixup (MemberInfo mi) {
163 if (num_token_fixups == token_fixups.Length) {
164 ILTokenInfo[] ntf = new ILTokenInfo [num_token_fixups * 2];
165 token_fixups.CopyTo (ntf, 0);
168 token_fixups [num_token_fixups].member = mi;
169 token_fixups [num_token_fixups++].code_pos = code_len;
172 private void make_room (int nbytes) {
173 if (code_len + nbytes < code.Length)
175 byte[] new_code = new byte [(code_len + nbytes) * 2 + 128];
176 System.Array.Copy (code, 0, new_code, 0, code.Length);
179 private void emit_int (int val) {
180 code [code_len++] = (byte) (val & 0xFF);
181 code [code_len++] = (byte) ((val >> 8) & 0xFF);
182 code [code_len++] = (byte) ((val >> 16) & 0xFF);
183 code [code_len++] = (byte) ((val >> 24) & 0xFF);
185 /* change to pass by ref to avoid copy */
186 private void ll_emit (OpCode opcode) {
188 * there is already enough room allocated in code.
190 // access op1 and op2 directly since the Value property is useless
191 if (opcode.Size == 2)
192 code [code_len++] = opcode.op1;
193 code [code_len++] = opcode.op2;
195 * We should probably keep track of stack needs here.
196 * Or we may want to run the verifier on the code before saving it
197 * (this may be needed anyway when the ILGenerator is not used...).
199 switch (opcode.StackBehaviourPush) {
200 case StackBehaviour.Push1:
201 case StackBehaviour.Pushi:
202 case StackBehaviour.Pushi8:
203 case StackBehaviour.Pushr4:
204 case StackBehaviour.Pushr8:
205 case StackBehaviour.Pushref:
206 case StackBehaviour.Varpush: /* again we are conservative and assume it pushes 1 */
209 case StackBehaviour.Push1_push1:
213 if (max_stack < cur_stack)
214 max_stack = cur_stack;
216 * Note that we adjust for the pop behaviour _after_ setting max_stack.
218 switch (opcode.StackBehaviourPop) {
219 case StackBehaviour.Varpop:
220 break; /* we are conservative and assume it doesn't decrease the stack needs */
221 case StackBehaviour.Pop1:
222 case StackBehaviour.Popi:
223 case StackBehaviour.Popref:
226 case StackBehaviour.Pop1_pop1:
227 case StackBehaviour.Popi_pop1:
228 case StackBehaviour.Popi_popi:
229 case StackBehaviour.Popi_popi8:
230 case StackBehaviour.Popi_popr4:
231 case StackBehaviour.Popi_popr8:
232 case StackBehaviour.Popref_pop1:
233 case StackBehaviour.Popref_popi:
236 case StackBehaviour.Popi_popi_popi:
237 case StackBehaviour.Popref_popi_popi:
238 case StackBehaviour.Popref_popi_popi8:
239 case StackBehaviour.Popref_popi_popr4:
240 case StackBehaviour.Popref_popi_popr8:
241 case StackBehaviour.Popref_popi_popref:
247 private static int target_len (OpCode opcode) {
248 if (opcode.operandType == OperandType.InlineBrTarget)
253 private void InternalEndClause () {
254 switch (ex_handlers [cur_block].LastClauseType ()) {
255 case ILExceptionBlock.CATCH:
256 // how could we optimize code size here?
257 Emit (OpCodes.Leave, ex_handlers [cur_block].end);
259 case ILExceptionBlock.FAULT:
260 case ILExceptionBlock.FINALLY:
261 Emit (OpCodes.Endfinally);
263 case ILExceptionBlock.FILTER:
264 Emit (OpCodes.Endfilter);
269 public virtual void BeginCatchBlock (Type exceptionType) {
270 if (open_blocks.Count <= 0)
271 throw new NotSupportedException ("Not in an exception block");
272 InternalEndClause ();
273 ex_handlers [cur_block].AddCatch (exceptionType, code_len);
274 cur_stack = 1; // the exception object is on the stack by default
275 if (max_stack < cur_stack)
276 max_stack = cur_stack;
277 //System.Console.WriteLine ("Begin catch Block: {0} {1}",exceptionType.ToString(), max_stack);
278 //throw new NotImplementedException ();
280 public virtual void BeginExceptFilterBlock () {
281 throw new NotImplementedException ();
283 public virtual Label BeginExceptionBlock () {
284 //System.Console.WriteLine ("Begin Block");
286 if (ex_handlers != null) {
287 cur_block = ex_handlers.Length;
288 ILExceptionInfo[] new_ex = new ILExceptionInfo [cur_block + 1];
289 System.Array.Copy (ex_handlers, new_ex, cur_block);
290 ex_handlers = new_ex;
292 ex_handlers = new ILExceptionInfo [1];
295 open_blocks.Push (cur_block);
296 ex_handlers [cur_block].start = code_len;
297 return ex_handlers [cur_block].end = DefineLabel ();
299 public virtual void BeginFaultBlock() {
300 if (open_blocks.Count <= 0)
301 throw new NotSupportedException ("Not in an exception block");
302 //System.Console.WriteLine ("Begin fault Block");
303 //throw new NotImplementedException ();
305 public virtual void BeginFinallyBlock() {
306 if (open_blocks.Count <= 0)
307 throw new NotSupportedException ("Not in an exception block");
308 InternalEndClause ();
309 //System.Console.WriteLine ("Begin finally Block");
310 ex_handlers [cur_block].AddFinally (code_len);
312 public virtual void BeginScope () {
313 if (sym_writer != null) {
315 scopes = new Stack ();
316 scopes.Push (sym_writer.OpenScope (code_len));
319 public LocalBuilder DeclareLocal (Type localType) {
320 LocalBuilder res = new LocalBuilder (module, localType, this);
321 if (locals != null) {
322 LocalBuilder[] new_l = new LocalBuilder [locals.Length + 1];
323 System.Array.Copy (locals, new_l, locals.Length);
324 new_l [locals.Length] = res;
327 locals = new LocalBuilder [1];
330 res.position = (uint)(locals.Length - 1);
333 public virtual Label DefineLabel () {
334 if (num_labels >= label_to_addr.Length) {
335 int[] new_l = new int [label_to_addr.Length * 2];
336 System.Array.Copy (label_to_addr, new_l, label_to_addr.Length);
337 label_to_addr = new_l;
339 label_to_addr [num_labels] = -1;
340 return new Label (num_labels++);
342 public virtual void Emit (OpCode opcode) {
346 public virtual void Emit (OpCode opcode, Byte val) {
349 code [code_len++] = val;
351 public virtual void Emit (OpCode opcode, ConstructorInfo constructor) {
352 int token = abuilder.GetToken (constructor);
355 if (constructor is ConstructorBuilder)
356 add_token_fixup (constructor);
358 ParameterInfo[] mparams = constructor.GetParameters();
360 cur_stack -= mparams.Length;
362 public virtual void Emit (OpCode opcode, double val) {
363 byte[] s = System.BitConverter.GetBytes (val);
366 if (BitConverter.IsLittleEndian){
367 System.Array.Copy (s, 0, code, code_len, 8);
370 code [code_len++] = s [7];
371 code [code_len++] = s [6];
372 code [code_len++] = s [5];
373 code [code_len++] = s [4];
374 code [code_len++] = s [3];
375 code [code_len++] = s [2];
376 code [code_len++] = s [1];
377 code [code_len++] = s [0];
380 public virtual void Emit (OpCode opcode, FieldInfo field) {
381 int token = abuilder.GetToken (field);
384 if (field is FieldBuilder)
385 add_token_fixup (field);
388 public virtual void Emit (OpCode opcode, Int16 val) {
391 code [code_len++] = (byte) (val & 0xFF);
392 code [code_len++] = (byte) ((val >> 8) & 0xFF);
394 public virtual void Emit (OpCode opcode, int val) {
399 public virtual void Emit (OpCode opcode, long val) {
402 code [code_len++] = (byte) (val & 0xFF);
403 code [code_len++] = (byte) ((val >> 8) & 0xFF);
404 code [code_len++] = (byte) ((val >> 16) & 0xFF);
405 code [code_len++] = (byte) ((val >> 24) & 0xFF);
406 code [code_len++] = (byte) ((val >> 32) & 0xFF);
407 code [code_len++] = (byte) ((val >> 40) & 0xFF);
408 code [code_len++] = (byte) ((val >> 48) & 0xFF);
409 code [code_len++] = (byte) ((val >> 56) & 0xFF);
411 public virtual void Emit (OpCode opcode, Label label) {
412 int tlen = target_len (opcode);
415 if (num_fixups >= fixups.Length) {
416 LabelFixup[] newf = new LabelFixup [fixups.Length + 16];
417 System.Array.Copy (fixups, newf, fixups.Length);
420 fixups [num_fixups].size = tlen;
421 fixups [num_fixups].pos = code_len;
422 fixups [num_fixups].label_base = code_len;
423 fixups [num_fixups].label_idx = label.label;
428 public virtual void Emit (OpCode opcode, Label[] labels) {
429 /* opcode needs to be switch. */
430 int count = labels.Length;
431 make_room (6 + count * 4);
433 int switch_base = code_len + count*4;
435 if (num_fixups + count >= fixups.Length) {
436 LabelFixup[] newf = new LabelFixup [fixups.Length + count + 16];
437 System.Array.Copy (fixups, newf, fixups.Length);
440 for (int i = 0; i < count; ++i) {
441 fixups [num_fixups].size = 4;
442 fixups [num_fixups].pos = code_len;
443 fixups [num_fixups].label_base = switch_base;
444 fixups [num_fixups].label_idx = labels [i].label;
449 public virtual void Emit (OpCode opcode, LocalBuilder lbuilder) {
450 uint pos = lbuilder.position;
451 bool load_addr = false;
452 bool is_store = false;
455 if (lbuilder.ilgen != this)
456 throw new Exception ("Trying to emit a local from a different ILGenerator.");
458 /* inline the code from ll_emit () to optimize il code size */
459 if (opcode.StackBehaviourPop == StackBehaviour.Pop1) {
464 if (cur_stack > max_stack)
465 max_stack = cur_stack;
466 load_addr = opcode.StackBehaviourPush == StackBehaviour.Pushi;
470 code [code_len++] = (byte)0x12;
471 code [code_len++] = (byte)pos;
473 code [code_len++] = (byte)0xfe;
474 code [code_len++] = (byte)0x0d;
475 code [code_len++] = (byte)(pos & 0xff);
476 code [code_len++] = (byte)((pos >> 8) & 0xff);
481 code [code_len++] = (byte)(0x0a + pos);
482 } else if (pos < 256) {
483 code [code_len++] = (byte)0x13;
484 code [code_len++] = (byte)pos;
486 code [code_len++] = (byte)0xfe;
487 code [code_len++] = (byte)0x0e;
488 code [code_len++] = (byte)(pos & 0xff);
489 code [code_len++] = (byte)((pos >> 8) & 0xff);
493 code [code_len++] = (byte)(0x06 + pos);
494 } else if (pos < 256) {
495 code [code_len++] = (byte)0x11;
496 code [code_len++] = (byte)pos;
498 code [code_len++] = (byte)0xfe;
499 code [code_len++] = (byte)0x0c;
500 code [code_len++] = (byte)(pos & 0xff);
501 code [code_len++] = (byte)((pos >> 8) & 0xff);
506 public virtual void Emit (OpCode opcode, MethodInfo method) {
508 throw new ArgumentNullException ("method");
510 int token = abuilder.GetToken (method);
513 if (method is MethodBuilder)
514 add_token_fixup (method);
516 if (method.ReturnType != void_type)
518 ParameterInfo[] mparams = method.GetParameters();
520 cur_stack -= mparams.Length;
522 [CLSCompliant(false)]
523 public void Emit (OpCode opcode, sbyte val) {
526 code [code_len++] = (byte)val;
529 public virtual void Emit (OpCode opcode, SignatureHelper shelper) {
530 int token = abuilder.GetToken (shelper);
535 public virtual void Emit (OpCode opcode, float val) {
536 byte[] s = System.BitConverter.GetBytes (val);
539 if (BitConverter.IsLittleEndian){
540 System.Array.Copy (s, 0, code, code_len, 4);
543 code [code_len++] = s [3];
544 code [code_len++] = s [2];
545 code [code_len++] = s [1];
546 code [code_len++] = s [0];
549 public virtual void Emit (OpCode opcode, string val) {
550 int token = abuilder.GetToken (val);
555 public virtual void Emit (OpCode opcode, Type type) {
558 if (type is TypeBuilder)
559 add_token_fixup (type);
560 emit_int (abuilder.GetToken (type));
563 public void EmitCall (OpCode opcode, MethodInfo methodinfo, Type[] optionalParamTypes) {
564 throw new NotImplementedException ();
567 public void EmitCalli (OpCode opcode, CallingConvention unmanagedCallConv, Type returnType, Type[] paramTypes) {
568 SignatureHelper helper
569 = SignatureHelper.GetMethodSigHelper (module, 0, unmanagedCallConv, returnType, paramTypes);
570 Emit (opcode, helper);
573 public void EmitCalli (OpCode opcode, CallingConventions callConv, Type returnType, Type[] paramTypes, Type[] optionalParamTypes) {
574 if (optionalParamTypes != null)
575 throw new NotImplementedException ();
577 SignatureHelper helper
578 = SignatureHelper.GetMethodSigHelper (module, callConv, 0, returnType, paramTypes);
579 Emit (opcode, helper);
582 public virtual void EmitWriteLine (FieldInfo field) {
583 throw new NotImplementedException ();
585 public virtual void EmitWriteLine (LocalBuilder lbuilder) {
586 throw new NotImplementedException ();
588 public virtual void EmitWriteLine (string val) {
589 Emit (OpCodes.Ldstr, val);
591 typeof (Console).GetMethod ("WriteLine",
592 new Type[1] { typeof(string)}));
595 public virtual void EndExceptionBlock () {
596 if (open_blocks.Count <= 0)
597 throw new NotSupportedException ("Not in an exception block");
598 InternalEndClause ();
599 MarkLabel (ex_handlers [cur_block].end);
600 ex_handlers [cur_block].End (code_len);
601 ex_handlers [cur_block].Debug (cur_block);
602 //System.Console.WriteLine ("End Block {0} (handlers: {1})", cur_block, ex_handlers [cur_block].NumHandlers ());
604 if (open_blocks.Count > 0)
605 cur_block = (int)open_blocks.Peek ();
606 //Console.WriteLine ("curblock restored to {0}", cur_block);
607 //throw new NotImplementedException ();
609 public virtual void EndScope () {
610 if (sym_writer != null) {
611 sym_writer.CloseScope (code_len);
613 throw new InvalidOperationException ();
617 public virtual void MarkLabel (Label loc) {
618 if (loc.label < 0 || loc.label >= num_labels)
619 throw new System.ArgumentException ("The label is not valid");
620 if (label_to_addr [loc.label] >= 0)
621 throw new System.ArgumentException ("The label was already defined");
622 label_to_addr [loc.label] = code_len;
624 public virtual void MarkSequencePoint (ISymbolDocumentWriter document, int startLine,
625 int startColumn, int endLine, int endColumn) {
626 if (sym_writer == null)
629 int[] offsets = { code_len };
630 int[] startLines = { startLine };
631 int[] startColumns = { startColumn };
632 int[] endLines = { endLine };
633 int[] endColumns = { endColumn };
635 sym_writer.DefineSequencePoints (document, offsets, startLines, startColumns,
636 endLines, endColumns);
638 public virtual void ThrowException (Type exceptionType) {
639 throw new NotImplementedException ();
641 public void UsingNamespace (String usingNamespace) {
642 throw new NotImplementedException ();
645 internal void label_fixup () {
647 for (i = 0; i < num_fixups; ++i) {
648 int diff = label_to_addr [fixups [i].label_idx] - fixups [i].label_base;
649 if (fixups [i].size == 1) {
650 code [fixups [i].pos] = (byte)((sbyte) diff - 1);
652 int old_cl = code_len;
653 code_len = fixups [i].pos;