make_room() now always makes enough room!
[mono.git] / mcs / class / corlib / System.Reflection.Emit / ILGenerator.cs
1
2 //
3 // System.Reflection.Emit/ILGenerator.cs
4 //
5 // Author:
6 //   Paolo Molaro (lupus@ximian.com)
7 //
8 // (C) 2001 Ximian, Inc.  http://www.ximian.com
9 //
10
11 using System;
12 using System.Collections;
13 using System.Diagnostics.SymbolStore;
14
15 namespace System.Reflection.Emit {
16
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;
22
23                 internal Type extype;
24                 internal int type;
25                 internal int start;
26                 internal int len;
27                 internal int filter_offset;
28                 
29                 internal void Debug () {
30                         System.Console.Write ("\ttype="+type.ToString()+" start="+start.ToString()+" len="+len.ToString());
31                         if (extype != null)
32                                 System.Console.WriteLine (" extype="+extype.ToString());
33                         else
34                                 System.Console.WriteLine ("");
35                 }
36         }
37         internal struct ILExceptionInfo {
38                 ILExceptionBlock[] handlers;
39                 internal int start;
40                 int len;
41                 internal Label end;
42
43                 internal void AddCatch (Type extype, int offset) {
44                         int i;
45                         End (offset);
46                         add_block (offset);
47                         i = handlers.Length - 1;
48                         handlers [i].type = ILExceptionBlock.CATCH;
49                         handlers [i].start = offset;
50                         handlers [i].extype = extype;
51                 }
52
53                 internal void AddFinally (int offset) {
54                         int i;
55                         End (offset);
56                         add_block (offset);
57                         i = handlers.Length - 1;
58                         handlers [i].type = ILExceptionBlock.FINALLY;
59                         handlers [i].start = offset;
60                         handlers [i].extype = null;
61                 }
62
63                 internal void End (int offset) {
64                         if (handlers == null)
65                                 return;
66                         int i = handlers.Length - 1;
67                         if (i >= 0)
68                                 handlers [i].len = offset - handlers [i].start;
69                 }
70
71                 internal int LastClauseType () {
72                         if (handlers != null)
73                                 return handlers [handlers.Length-1].type;
74                         else
75                                 return ILExceptionBlock.CATCH;
76                 }
77
78                 internal void Debug () {
79 #if NO
80                         System.Console.WriteLine ("Handler at "+start.ToString()+ " len: "+len.ToString());
81                         for (int i = 0; i < handlers.Length; ++i)
82                                 handlers [i].Debug ();
83 #endif
84                 }
85
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);
91                                 handlers = new_b;
92                                 handlers [i].len = offset - handlers [i].start;
93                         } else {
94                                 handlers = new ILExceptionBlock [1];
95                                 len = offset - start;
96                         }
97                 }
98         }
99         
100         internal struct ILTokenInfo {
101                 public MemberInfo member;
102                 public int code_pos;
103         }
104
105         public class ILGenerator: Object {
106                 private struct LabelFixup {
107                         public int size;
108                         public int pos;
109                         public int label_idx;
110                 };
111                 static Type void_type = typeof (void);
112                 private byte[] code;
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;
131
132                 internal ILGenerator (MethodBase mb, int size) {
133                         if (size < 0)
134                                 size = 256;
135                         code_len = 0;
136                         code = new byte [size];
137                         mbuilder = mb;
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;
149                         }
150                         abuilder = (AssemblyBuilder)module.Assembly;
151                         sym_writer = module.GetSymWriter ();
152                 }
153
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);
158                                 token_fixups = ntf;
159                         }
160                         token_fixups [num_token_fixups].member = mi;
161                         token_fixups [num_token_fixups++].code_pos = code_len;
162                 }
163
164                 private void make_room (int nbytes) {
165                         if (code_len + nbytes < code.Length)
166                                 return;
167                         byte[] new_code = new byte [(code_len + nbytes) * 2 + 128];
168                         System.Array.Copy (code, 0, new_code, 0, code.Length);
169                         code = new_code;
170                 }
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);
176                 }
177                 /* change to pass by ref to avoid copy */
178                 private void ll_emit (OpCode opcode) {
179                         /* 
180                          * there is already enough room allocated in code.
181                          */
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;
186                         /*
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...).
190                          */
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 */
199                                 cur_stack ++;
200                                 break;
201                         case StackBehaviour.Push1_push1:
202                                 cur_stack += 2;
203                                 break;
204                         }
205                         if (max_stack < cur_stack)
206                                 max_stack = cur_stack;
207                         /* 
208                          * Note that we adjust for the pop behaviour _after_ setting max_stack.
209                          */
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:
216                                 cur_stack --;
217                                 break;
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:
226                                 cur_stack -= 2;
227                                 break;
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:
234                                 cur_stack -= 3;
235                                 break;
236                         }
237                 }
238
239                 private static int target_len (OpCode opcode) {
240                         if (opcode.operandType == OperandType.InlineBrTarget)
241                                 return 4;
242                         return 1;
243                 }
244
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);
250                                 break;
251                         case ILExceptionBlock.FAULT:
252                         case ILExceptionBlock.FINALLY:
253                                 Emit (OpCodes.Endfinally);
254                                 break;
255                         case ILExceptionBlock.FILTER:
256                                 Emit (OpCodes.Endfilter);
257                                 break;
258                         }
259                 }
260
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 ();
268                 }
269                 public virtual void BeginExceptFilterBlock () {
270                         throw new NotImplementedException ();
271                 }
272                 public virtual Label BeginExceptionBlock () {
273                         //System.Console.WriteLine ("Begin Block");
274                         
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;
280                         } else {
281                                 ex_handlers = new ILExceptionInfo [1];
282                                 cur_block = 0;
283                         }
284                         open_blocks++;
285                         ex_handlers [cur_block].start = code_len;
286                         return ex_handlers [cur_block].end = DefineLabel ();
287                 }
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 ();
293                 }
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 ();
301                 }
302                 public virtual void BeginScope () {
303                         if (sym_writer != null)
304                                 scopes.Push (sym_writer.OpenScope (code_len));
305                 }
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;
312                                 locals = new_l;
313                         } else {
314                                 locals = new LocalBuilder [1];
315                                 locals [0] = res;
316                         }
317                         res.position = (uint)(locals.Length - 1);
318                         return res;
319                 }
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;
325                         }
326                         label_to_addr [num_labels] = -1;
327                         return new Label (num_labels++);
328                 }
329                 public virtual void Emit (OpCode opcode) {
330                         make_room (2);
331                         ll_emit (opcode);
332                 }
333                 public virtual void Emit (OpCode opcode, Byte val) {
334                         make_room (3);
335                         ll_emit (opcode);
336                         code [code_len++] = val;
337                 }
338                 public virtual void Emit (OpCode opcode, ConstructorInfo constructor) {
339                         int token = abuilder.GetToken (constructor);
340                         make_room (6);
341                         ll_emit (opcode);
342                         if (constructor is ConstructorBuilder)
343                                 add_token_fixup (constructor);
344                         emit_int (token);
345                         ParameterInfo[] mparams = constructor.GetParameters();
346                         if (mparams != null)
347                                 cur_stack -= mparams.Length;
348                 }
349                 public virtual void Emit (OpCode opcode, Double val) {
350                         byte[] s = System.BitConverter.GetBytes (val);
351                         make_room (10);
352                         ll_emit (opcode);
353                         System.Array.Copy (s, 0, code, code_len, 8);
354                         code_len += 8;
355                 }
356                 public virtual void Emit (OpCode opcode, FieldInfo field) {
357                         int token = abuilder.GetToken (field);
358                         make_room (6);
359                         ll_emit (opcode);
360                         if (field is FieldBuilder)
361                                 add_token_fixup (field);
362                         emit_int (token);
363                 }
364                 public virtual void Emit (OpCode opcode, Int16 val) {
365                         make_room (4);
366                         ll_emit (opcode);
367                         code [code_len++] = (byte) (val & 0xFF);
368                         code [code_len++] = (byte) ((val >> 8) & 0xFF);
369                 }
370                 public virtual void Emit (OpCode opcode, Int32 val) {
371                         make_room (6);
372                         ll_emit (opcode);
373                         emit_int (val);
374                 }
375                 public virtual void Emit (OpCode opcode, Int64 val) {
376                         make_room (10);
377                         ll_emit (opcode);
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);
386                 }
387                 public virtual void Emit (OpCode opcode, Label label) {
388                         int tlen = target_len (opcode);
389                         make_room (6);
390                         ll_emit (opcode);
391                         if (num_fixups >= fixups.Length) {
392                                 LabelFixup[] newf = new LabelFixup [fixups.Length + 16];
393                                 System.Array.Copy (fixups, newf, fixups.Length);
394                                 fixups = newf;
395                         }
396                         fixups [num_fixups].size = tlen;
397                         fixups [num_fixups].pos = code_len;
398                         fixups [num_fixups].label_idx = label.label;
399                         num_fixups++;
400                         code_len += tlen;
401
402                 }
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);
407                         ll_emit (opcode);
408                         emit_int (count);
409                         if (num_fixups + count >= fixups.Length) {
410                                 LabelFixup[] newf = new LabelFixup [fixups.Length + count + 16];
411                                 System.Array.Copy (fixups, newf, fixups.Length);
412                                 fixups = newf;
413                         }
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;
418                                 num_fixups++;
419                                 code_len += 4;
420                         }
421                 }
422                 public virtual void Emit (OpCode opcode, LocalBuilder lbuilder) {
423                         uint pos = lbuilder.position;
424                         bool load_addr = false;
425                         bool is_store = false;
426                         make_room (6);
427                         /* inline the code from ll_emit () to optimize il code size */
428                         if (opcode.StackBehaviourPop == StackBehaviour.Pop1) {
429                                 cur_stack --;
430                                 is_store = true;
431                         } else {
432                                 cur_stack++;
433                                 if (cur_stack > max_stack)
434                                         max_stack = cur_stack;
435                                 load_addr = opcode.StackBehaviourPush == StackBehaviour.Pushi;
436                         }
437                         if (load_addr) {
438                                 if (pos < 256) {
439                                         code [code_len++] = (byte)0x12;
440                                         code [code_len++] = (byte)pos;
441                                 } else {
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);
446                                 }
447                         } else {
448                                 if (is_store) {
449                                         if (pos < 4) {
450                                                 code [code_len++] = (byte)(0x0a + pos);
451                                         } else if (pos < 256) {
452                                                 code [code_len++] = (byte)0x13;
453                                                 code [code_len++] = (byte)pos;
454                                         } else {
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);
459                                         }
460                                 } else {
461                                         if (pos < 4) {
462                                                 code [code_len++] = (byte)(0x06 + pos);
463                                         } else if (pos < 256) {
464                                                 code [code_len++] = (byte)0x11;
465                                                 code [code_len++] = (byte)pos;
466                                         } else {
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);
471                                         }
472                                 }
473                         }
474                 }
475                 public virtual void Emit (OpCode opcode, MethodInfo method) {
476                         int token = abuilder.GetToken (method);
477                         make_room (6);
478                         ll_emit (opcode);
479                         if (method is MethodBuilder)
480                                 add_token_fixup (method);
481                         emit_int (token);
482                         if (method.ReturnType == void_type)
483                                 cur_stack --;
484                         ParameterInfo[] mparams = method.GetParameters();
485                         if (mparams != null)
486                                 cur_stack -= mparams.Length;
487                 }
488                 [CLSCompliant(false)]
489                 public void Emit (OpCode opcode, sbyte val) {
490                         make_room (3);
491                         ll_emit (opcode);
492                         code [code_len++] = (byte)val;
493                 }
494
495                 [MonoTODO]
496                 public virtual void Emit (OpCode opcode, SignatureHelper shelper) {
497                         int token = 0; // FIXME: request a token from the modulebuilder
498                         make_room (6);
499                         ll_emit (opcode);
500                         emit_int (token);
501                 }
502                 public virtual void Emit (OpCode opcode, float val) {
503                         byte[] s = System.BitConverter.GetBytes (val);
504                         make_room (6);
505                         ll_emit (opcode);
506                         System.Array.Copy (s, 0, code, code_len, 4);
507                         code_len += 4;
508                 }
509                 public virtual void Emit (OpCode opcode, string val) {
510                         int token = abuilder.GetToken (val);
511                         make_room (6);
512                         ll_emit (opcode);
513                         emit_int (token);
514                 }
515                 public virtual void Emit (OpCode opcode, Type type) {
516                         make_room (6);
517                         ll_emit (opcode);
518                         emit_int (abuilder.GetToken (type));
519                 }
520
521                 public void EmitCall (OpCode opcode, MethodInfo methodinfo, Type[] optionalParamTypes) {
522                         throw new NotImplementedException ();
523                 }
524                 public void EmitCalli (OpCode opcode, CallingConventions call_conv, Type returnType, Type[] paramTypes, Type[] optionalParamTypes) {
525                         throw new NotImplementedException ();
526                 }
527
528                 public virtual void EmitWriteLine (FieldInfo field) {
529                         throw new NotImplementedException ();
530                 }
531                 public virtual void EmitWriteLine (LocalBuilder lbuilder) {
532                         throw new NotImplementedException ();
533                 }
534                 public virtual void EmitWriteLine (string val) {
535                         throw new NotImplementedException ();
536                 }
537
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 ();
545                         --cur_block;
546                         --open_blocks;
547                         //System.Console.WriteLine ("End Block");
548                         //throw new NotImplementedException ();
549                 }
550                 public virtual void EndScope () {
551                         if (sym_writer != null) {
552                                 sym_writer.CloseScope (code_len);
553                                 scopes.Pop ();
554                         }
555                 }
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;
562                 }
563                 public virtual void MarkSequencePoint (ISymbolDocumentWriter document, int startLine,
564                                                        int startColumn, int endLine, int endColumn) {
565                         if (sym_writer == null)
566                                 return;
567
568                         int[] offsets = { code_len };
569                         int[] startLines = { startLine };
570                         int[] startColumns = { startColumn };
571                         int[] endLines = { endLine };
572                         int[] endColumns = { endColumn };
573
574                         sym_writer.DefineSequencePoints (document, offsets, startLines, startColumns,
575                                                          endLines, endColumns);
576                 }
577                 public virtual void ThrowException (Type exceptionType) {
578                         throw new NotImplementedException ();
579                 }
580                 public void UsingNamespace (String usingNamespace) {
581                         throw new NotImplementedException ();
582                 }
583
584                 internal void label_fixup () {
585                         int i;
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);
590                                 } else {
591                                         int old_cl = code_len;
592                                         code_len = fixups [i].pos;
593                                         emit_int (diff - 4);
594                                         code_len = old_cl;
595                                 }
596                         }
597                 }
598         }
599 }