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;
15 namespace System.Reflection.Emit {
17 internal struct ILExceptionBlock {
18 public const int CATCH = 0;
19 public const int FILTER = 1;
20 public const int FINALLY = 2;
21 public const int FAULT = 4;
27 internal int filter_offset;
29 internal void Debug () {
30 System.Console.Write ("\ttype="+type.ToString()+" start="+start.ToString()+" len="+len.ToString());
32 System.Console.WriteLine (" extype="+extype.ToString());
34 System.Console.WriteLine ("");
37 internal struct ILExceptionInfo {
38 ILExceptionBlock[] handlers;
43 internal void AddCatch (Type extype, int offset) {
47 i = handlers.Length - 1;
48 handlers [i].type = ILExceptionBlock.CATCH;
49 handlers [i].start = offset;
50 handlers [i].extype = extype;
53 internal void AddFinally (int offset) {
57 i = handlers.Length - 1;
58 handlers [i].type = ILExceptionBlock.FINALLY;
59 handlers [i].start = offset;
60 handlers [i].extype = null;
63 internal void End (int offset) {
66 int i = handlers.Length - 1;
68 handlers [i].len = offset - handlers [i].start;
71 internal int LastClauseType () {
73 return handlers [handlers.Length-1].type;
75 return ILExceptionBlock.CATCH;
78 internal void Debug () {
80 System.Console.WriteLine ("Handler at "+start.ToString()+ " len: "+len.ToString());
81 for (int i = 0; i < handlers.Length; ++i)
82 handlers [i].Debug ();
86 void add_block (int offset) {
87 if (handlers != null) {
88 int i = handlers.Length;
89 ILExceptionBlock[] new_b = new ILExceptionBlock [i + 1];
90 System.Array.Copy (handlers, new_b, i);
92 handlers [i].len = offset - handlers [i].start;
94 handlers = new ILExceptionBlock [1];
100 internal struct ILTokenInfo {
101 public MemberInfo member;
105 public class ILGenerator: Object {
106 private struct LabelFixup {
109 public int label_idx;
111 static Type void_type = typeof (void);
113 private MethodBase mbuilder; /* a MethodBuilder or ConstructorBuilder */
114 private int code_len;
115 private int max_stack;
116 private int cur_stack;
117 private LocalBuilder[] locals;
118 private ILExceptionInfo[] ex_handlers;
119 private int num_token_fixups;
120 private ILTokenInfo[] token_fixups;
121 private int[] label_to_addr;
122 private int num_labels;
123 private LabelFixup[] fixups;
124 private int num_fixups;
125 private ModuleBuilder module;
126 private AssemblyBuilder abuilder;
127 private ISymbolWriter sym_writer;
128 private Stack scopes;
129 private int cur_block;
130 private int open_blocks;
132 internal ILGenerator (MethodBase mb, int size) {
136 code = new byte [size];
138 cur_stack = max_stack = 0;
139 num_fixups = num_labels = 0;
140 label_to_addr = new int [16];
141 fixups = new LabelFixup [16];
142 token_fixups = new ILTokenInfo [16];
143 scopes = new Stack ();
144 num_token_fixups = 0;
145 if (mb is MethodBuilder) {
146 module = (ModuleBuilder)((MethodBuilder)mb).TypeBuilder.Module;
147 } else if (mb is ConstructorBuilder) {
148 module = (ModuleBuilder)((ConstructorBuilder)mb).TypeBuilder.Module;
150 abuilder = (AssemblyBuilder)module.Assembly;
151 sym_writer = module.GetSymWriter ();
154 private void add_token_fixup (MemberInfo mi) {
155 if (num_token_fixups == token_fixups.Length) {
156 ILTokenInfo[] ntf = new ILTokenInfo [num_token_fixups * 2];
157 token_fixups.CopyTo (ntf, 0);
160 token_fixups [num_token_fixups].member = mi;
161 token_fixups [num_token_fixups++].code_pos = code_len;
164 private void make_room (int nbytes) {
165 if (code_len + nbytes < code.Length)
167 byte[] new_code = new byte [code.Length * 2 + 128];
168 System.Array.Copy (code, 0, new_code, 0, code.Length);
171 private void emit_int (int val) {
172 code [code_len++] = (byte) (val & 0xFF);
173 code [code_len++] = (byte) ((val >> 8) & 0xFF);
174 code [code_len++] = (byte) ((val >> 16) & 0xFF);
175 code [code_len++] = (byte) ((val >> 24) & 0xFF);
177 /* change to pass by ref to avoid copy */
178 private void ll_emit (OpCode opcode) {
180 * there is already enough room allocated in code.
182 // access op1 and op2 directly since the Value property is useless
183 if (opcode.Size == 2)
184 code [code_len++] = opcode.op1;
185 code [code_len++] = opcode.op2;
187 * We should probably keep track of stack needs here.
188 * Or we may want to run the verifier on the code before saving it
189 * (this may be needed anyway when the ILGenerator is not used...).
191 switch (opcode.StackBehaviourPush) {
192 case StackBehaviour.Push1:
193 case StackBehaviour.Pushi:
194 case StackBehaviour.Pushi8:
195 case StackBehaviour.Pushr4:
196 case StackBehaviour.Pushr8:
197 case StackBehaviour.Pushref:
198 case StackBehaviour.Varpush: /* again we are conservative and assume it pushes 1 */
201 case StackBehaviour.Push1_push1:
205 if (max_stack < cur_stack)
206 max_stack = cur_stack;
208 * Note that we adjust for the pop behaviour _after_ setting max_stack.
210 switch (opcode.StackBehaviourPop) {
211 case StackBehaviour.Varpop:
212 break; /* we are conservative and assume it doesn't decrease the stack needs */
213 case StackBehaviour.Pop1:
214 case StackBehaviour.Popi:
215 case StackBehaviour.Popref:
218 case StackBehaviour.Pop1_pop1:
219 case StackBehaviour.Popi_pop1:
220 case StackBehaviour.Popi_popi:
221 case StackBehaviour.Popi_popi8:
222 case StackBehaviour.Popi_popr4:
223 case StackBehaviour.Popi_popr8:
224 case StackBehaviour.Popref_pop1:
225 case StackBehaviour.Popref_popi:
228 case StackBehaviour.Popi_popi_popi:
229 case StackBehaviour.Popref_popi_popi:
230 case StackBehaviour.Popref_popi_popi8:
231 case StackBehaviour.Popref_popi_popr4:
232 case StackBehaviour.Popref_popi_popr8:
233 case StackBehaviour.Popref_popi_popref:
239 private static int target_len (OpCode opcode) {
240 if (opcode.operandType == OperandType.InlineBrTarget)
245 private void InternalEndClause () {
246 switch (ex_handlers [cur_block].LastClauseType ()) {
247 case ILExceptionBlock.CATCH:
248 // how could we optimize code size here?
249 Emit (OpCodes.Leave, ex_handlers [cur_block].end);
251 case ILExceptionBlock.FAULT:
252 case ILExceptionBlock.FINALLY:
253 Emit (OpCodes.Endfinally);
255 case ILExceptionBlock.FILTER:
256 Emit (OpCodes.Endfilter);
261 public virtual void BeginCatchBlock (Type exceptionType) {
262 if (open_blocks <= 0)
263 throw new NotSupportedException ("Not in an exception block");
264 InternalEndClause ();
265 ex_handlers [cur_block].AddCatch (exceptionType, code_len);
266 //System.Console.WriteLine ("Begin catch Block: "+exceptionType.ToString());
267 //throw new NotImplementedException ();
269 public virtual void BeginExceptFilterBlock () {
270 throw new NotImplementedException ();
272 public virtual Label BeginExceptionBlock () {
273 //System.Console.WriteLine ("Begin Block");
275 if (ex_handlers != null) {
276 cur_block = ex_handlers.Length;
277 ILExceptionInfo[] new_ex = new ILExceptionInfo [cur_block + 1];
278 System.Array.Copy (ex_handlers, new_ex, cur_block);
279 ex_handlers = new_ex;
281 ex_handlers = new ILExceptionInfo [1];
285 ex_handlers [cur_block].start = code_len;
286 return ex_handlers [cur_block].end = DefineLabel ();
288 public virtual void BeginFaultBlock() {
289 if (open_blocks <= 0)
290 throw new NotSupportedException ("Not in an exception block");
291 //System.Console.WriteLine ("Begin fault Block");
292 //throw new NotImplementedException ();
294 public virtual void BeginFinallyBlock() {
295 if (open_blocks <= 0)
296 throw new NotSupportedException ("Not in an exception block");
297 //System.Console.WriteLine ("Begin finally Block");
298 InternalEndClause ();
299 ex_handlers [cur_block].AddFinally (code_len);
300 //throw new NotImplementedException ();
302 public virtual void BeginScope () {
303 if (sym_writer != null)
304 scopes.Push (sym_writer.OpenScope (code_len));
306 public LocalBuilder DeclareLocal (Type localType) {
307 LocalBuilder res = new LocalBuilder (module, localType);
308 if (locals != null) {
309 LocalBuilder[] new_l = new LocalBuilder [locals.Length + 1];
310 System.Array.Copy (locals, new_l, locals.Length);
311 new_l [locals.Length] = res;
314 locals = new LocalBuilder [1];
317 res.position = (uint)(locals.Length - 1);
320 public virtual Label DefineLabel () {
321 if (num_labels >= label_to_addr.Length) {
322 int[] new_l = new int [label_to_addr.Length * 2];
323 System.Array.Copy (label_to_addr, new_l, label_to_addr.Length);
324 label_to_addr = new_l;
326 label_to_addr [num_labels] = -1;
327 return new Label (num_labels++);
329 public virtual void Emit (OpCode opcode) {
333 public virtual void Emit (OpCode opcode, Byte val) {
336 code [code_len++] = val;
338 public virtual void Emit (OpCode opcode, ConstructorInfo constructor) {
339 int token = abuilder.GetToken (constructor);
342 if (constructor is ConstructorBuilder)
343 add_token_fixup (constructor);
345 ParameterInfo[] mparams = constructor.GetParameters();
347 cur_stack -= mparams.Length;
349 public virtual void Emit (OpCode opcode, Double val) {
350 byte[] s = System.BitConverter.GetBytes (val);
353 System.Array.Copy (s, 0, code, code_len, 8);
356 public virtual void Emit (OpCode opcode, FieldInfo field) {
357 int token = abuilder.GetToken (field);
360 if (field is FieldBuilder)
361 add_token_fixup (field);
364 public virtual void Emit (OpCode opcode, Int16 val) {
367 code [code_len++] = (byte) (val & 0xFF);
368 code [code_len++] = (byte) ((val >> 8) & 0xFF);
370 public virtual void Emit (OpCode opcode, Int32 val) {
375 public virtual void Emit (OpCode opcode, Int64 val) {
378 code [code_len++] = (byte) (val & 0xFF);
379 code [code_len++] = (byte) ((val >> 8) & 0xFF);
380 code [code_len++] = (byte) ((val >> 16) & 0xFF);
381 code [code_len++] = (byte) ((val >> 24) & 0xFF);
382 code [code_len++] = (byte) ((val >> 32) & 0xFF);
383 code [code_len++] = (byte) ((val >> 40) & 0xFF);
384 code [code_len++] = (byte) ((val >> 48) & 0xFF);
385 code [code_len++] = (byte) ((val >> 56) & 0xFF);
387 public virtual void Emit (OpCode opcode, Label label) {
388 int tlen = target_len (opcode);
391 if (num_fixups >= fixups.Length) {
392 LabelFixup[] newf = new LabelFixup [fixups.Length + 16];
393 System.Array.Copy (fixups, newf, fixups.Length);
396 fixups [num_fixups].size = tlen;
397 fixups [num_fixups].pos = code_len;
398 fixups [num_fixups].label_idx = label.label;
403 public virtual void Emit (OpCode opcode, Label[] labels) {
404 /* opcode needs to be switch. */
405 int count = labels.Length;
406 make_room (6 + count * 4);
409 if (num_fixups + count >= fixups.Length) {
410 LabelFixup[] newf = new LabelFixup [fixups.Length + count + 16];
411 System.Array.Copy (fixups, newf, fixups.Length);
414 for (int i = 0; i < count; ++i) {
415 fixups [num_fixups].size = 4;
416 fixups [num_fixups].pos = code_len;
417 fixups [num_fixups].label_idx = labels [i].label;
422 public virtual void Emit (OpCode opcode, LocalBuilder lbuilder) {
423 uint pos = lbuilder.position;
424 bool load_addr = false;
425 bool is_store = false;
427 /* inline the code from ll_emit () to optimize il code size */
428 if (opcode.StackBehaviourPop == StackBehaviour.Pop1) {
433 if (cur_stack > max_stack)
434 max_stack = cur_stack;
435 load_addr = opcode.StackBehaviourPush == StackBehaviour.Pushi;
439 code [code_len++] = (byte)0x12;
440 code [code_len++] = (byte)pos;
442 code [code_len++] = (byte)0xfe;
443 code [code_len++] = (byte)0x0d;
444 code [code_len++] = (byte)(pos & 0xff);
445 code [code_len++] = (byte)((pos >> 8) & 0xff);
450 code [code_len++] = (byte)(0x0a + pos);
451 } else if (pos < 256) {
452 code [code_len++] = (byte)0x13;
453 code [code_len++] = (byte)pos;
455 code [code_len++] = (byte)0xfe;
456 code [code_len++] = (byte)0x0e;
457 code [code_len++] = (byte)(pos & 0xff);
458 code [code_len++] = (byte)((pos >> 8) & 0xff);
462 code [code_len++] = (byte)(0x06 + pos);
463 } else if (pos < 256) {
464 code [code_len++] = (byte)0x11;
465 code [code_len++] = (byte)pos;
467 code [code_len++] = (byte)0xfe;
468 code [code_len++] = (byte)0x0c;
469 code [code_len++] = (byte)(pos & 0xff);
470 code [code_len++] = (byte)((pos >> 8) & 0xff);
475 public virtual void Emit (OpCode opcode, MethodInfo method) {
476 int token = abuilder.GetToken (method);
479 if (method is MethodBuilder)
480 add_token_fixup (method);
482 if (method.ReturnType == void_type)
484 ParameterInfo[] mparams = method.GetParameters();
486 cur_stack -= mparams.Length;
488 [CLSCompliant(false)]
489 public void Emit (OpCode opcode, sbyte val) {
492 code [code_len++] = (byte)val;
496 public virtual void Emit (OpCode opcode, SignatureHelper shelper) {
497 int token = 0; // FIXME: request a token from the modulebuilder
502 public virtual void Emit (OpCode opcode, float val) {
503 byte[] s = System.BitConverter.GetBytes (val);
506 System.Array.Copy (s, 0, code, code_len, 4);
509 public virtual void Emit (OpCode opcode, string val) {
510 int token = abuilder.GetToken (val);
515 public virtual void Emit (OpCode opcode, Type type) {
518 emit_int (abuilder.GetToken (type));
521 public void EmitCall (OpCode opcode, MethodInfo methodinfo, Type[] optionalParamTypes) {
522 throw new NotImplementedException ();
524 public void EmitCalli (OpCode opcode, CallingConventions call_conv, Type returnType, Type[] paramTypes, Type[] optionalParamTypes) {
525 throw new NotImplementedException ();
528 public virtual void EmitWriteLine (FieldInfo field) {
529 throw new NotImplementedException ();
531 public virtual void EmitWriteLine (LocalBuilder lbuilder) {
532 throw new NotImplementedException ();
534 public virtual void EmitWriteLine (string val) {
535 throw new NotImplementedException ();
538 public virtual void EndExceptionBlock () {
539 if (open_blocks <= 0)
540 throw new NotSupportedException ("Not in an exception block");
541 InternalEndClause ();
542 MarkLabel (ex_handlers [cur_block].end);
543 ex_handlers [cur_block].End (code_len);
544 ex_handlers [cur_block].Debug ();
547 //System.Console.WriteLine ("End Block");
548 //throw new NotImplementedException ();
550 public virtual void EndScope () {
551 if (sym_writer != null) {
552 sym_writer.CloseScope (code_len);
556 public virtual void MarkLabel (Label loc) {
557 if (loc.label < 0 || loc.label >= num_labels)
558 throw new System.ArgumentException ("The label is not valid");
559 if (label_to_addr [loc.label] >= 0)
560 throw new System.ArgumentException ("The label was already defined");
561 label_to_addr [loc.label] = code_len;
563 public virtual void MarkSequencePoint (ISymbolDocumentWriter document, int startLine,
564 int startColumn, int endLine, int endColumn) {
565 if (sym_writer == null)
568 int[] offsets = { code_len };
569 int[] startLines = { startLine };
570 int[] startColumns = { startColumn };
571 int[] endLines = { endLine };
572 int[] endColumns = { endColumn };
574 sym_writer.DefineSequencePoints (document, offsets, startLines, startColumns,
575 endLines, endColumns);
577 public virtual void ThrowException (Type exceptionType) {
578 throw new NotImplementedException ();
580 public void UsingNamespace (String usingNamespace) {
581 throw new NotImplementedException ();
584 internal void label_fixup () {
586 for (i = 0; i < num_fixups; ++i) {
587 int diff = label_to_addr [fixups [i].label_idx] - fixups [i].pos;
588 if (fixups [i].size == 1) {
589 code [fixups [i].pos] = (byte)((sbyte) diff - 1);
591 int old_cl = code_len;
592 code_len = fixups [i].pos;