Tue Jan 15 22:46:21 CET 2002 Paolo Molaro <lupus@ximian.com>
[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.Diagnostics.SymbolStore;
13
14 namespace System.Reflection.Emit {
15
16         internal struct ILExceptionBlock {
17                 public const int CATCH = 0;
18                 public const int FILTER = 1;
19                 public const int FINALLY = 2;
20                 public const int FAULT = 4;
21
22                 internal Type extype;
23                 internal int type;
24                 internal int start;
25                 internal int len;
26                 internal int filter_offset;
27                 
28                 internal void Debug () {
29                         System.Console.Write ("\ttype="+type.ToString()+" start="+start.ToString());
30                         System.Console.WriteLine (" len="+len.ToString()+" extype="+extype.ToString());
31                 }
32         }
33         internal struct ILExceptionInfo {
34                 ILExceptionBlock[] handlers;
35                 internal int start;
36                 int len;
37                 internal Label end;
38
39                 internal void AddCatch (Type extype, int offset) {
40                         int i;
41                         add_block (offset);
42                         i = handlers.Length - 1;
43                         handlers [i].type = ILExceptionBlock.CATCH;
44                         handlers [i].start = offset;
45                         handlers [i].extype = extype;
46                 }
47
48                 internal void End (int offset) {
49                         int i = handlers.Length - 1;
50                         handlers [i].len = offset - handlers [i].start;
51                 }
52
53                 internal void Debug () {
54                         System.Console.WriteLine ("Handler at "+start.ToString()+ " len: "+len.ToString());
55                         for (int i = 0; i < handlers.Length; ++i)
56                                 handlers [i].Debug ();
57                 }
58
59                 void add_block (int offset) {
60                         if (handlers != null) {
61                                 int i = handlers.Length;
62                                 ILExceptionBlock[] new_b = new ILExceptionBlock [i + 1];
63                                 System.Array.Copy (handlers, new_b, i);
64                                 handlers = new_b;
65                                 handlers [i].len = offset - handlers [i].start;
66                         } else {
67                                 handlers = new ILExceptionBlock [1];
68                                 len = offset - start;
69                         }
70                 }
71         }
72         
73         public class ILGenerator: Object {
74                 private struct LabelFixup {
75                         public int size;
76                         public int pos;
77                         public int label_idx;
78                 };
79                 private byte[] code;
80                 private MethodBase mbuilder; /* a MethodBuilder or ConstructorBuilder */
81                 private int code_len;
82                 private int max_stack;
83                 private int cur_stack;
84                 private LocalBuilder[] locals;
85                 private ILExceptionInfo[] ex_handlers;
86                 private int[] label_to_addr;
87                 private int num_labels;
88                 private LabelFixup[] fixups;
89                 private int num_fixups;
90                 private AssemblyBuilder abuilder;
91                 private int cur_block;
92
93                 internal ILGenerator (MethodBase mb, int size) {
94                         if (size < 0)
95                                 size = 256;
96                         code_len = 0;
97                         code = new byte [size];
98                         mbuilder = mb;
99                         cur_stack = max_stack = 0;
100                         num_fixups = num_labels = 0;
101                         cur_block = -1;
102                         label_to_addr = new int [16];
103                         fixups = new LabelFixup [16];
104                         if (mb is MethodBuilder) {
105                                 abuilder = (AssemblyBuilder)((MethodBuilder)mb).TypeBuilder.Module.Assembly;
106                         } else if (mb is ConstructorBuilder) {
107                                 abuilder = (AssemblyBuilder)((ConstructorBuilder)mb).TypeBuilder.Module.Assembly;
108                         }
109                 }
110
111                 private void make_room (int nbytes) {
112                         if (code_len + nbytes < code.Length)
113                                 return;
114                         byte[] new_code = new byte [code.Length + 128];
115                         System.Array.Copy (code, new_code, code.Length);
116                         code = new_code;
117                 }
118                 private void emit_int (int val) {
119                         code [code_len++] = (byte) (val & 0xFF);
120                         code [code_len++] = (byte) ((val >> 8) & 0xFF);
121                         code [code_len++] = (byte) ((val >> 16) & 0xFF);
122                         code [code_len++] = (byte) ((val >> 24) & 0xFF);
123                 }
124                 /* change to pass by ref to avoid copy */
125                 private void ll_emit (OpCode opcode) {
126                         /* 
127                          * there is already enough room allocated in code.
128                          */
129                         // access op1 and op2 directly since the Value property is useless
130                         if (opcode.Size == 2)
131                                 code [code_len++] = opcode.op1;
132                         code [code_len++] = opcode.op2;
133                         /*
134                          * We should probably keep track of stack needs here.
135                          * Or we may want to run the verifier on the code before saving it
136                          * (this may be needed anyway when the ILGenerator is not used...).
137                          */
138                         switch (opcode.StackBehaviourPush) {
139                         case StackBehaviour.Push1:
140                         case StackBehaviour.Pushi:
141                         case StackBehaviour.Pushi8:
142                         case StackBehaviour.Pushr4:
143                         case StackBehaviour.Pushr8:
144                         case StackBehaviour.Pushref:
145                         case StackBehaviour.Varpush: /* again we are conservative and assume it pushes 1 */
146                                 cur_stack ++;
147                                 break;
148                         case StackBehaviour.Push1_push1:
149                                 cur_stack += 2;
150                                 break;
151                         }
152                         if (max_stack < cur_stack)
153                                 max_stack = cur_stack;
154                         /* 
155                          * Note that we adjust for the pop behaviour _after_ setting max_stack.
156                          */
157                         switch (opcode.StackBehaviourPop) {
158                         case StackBehaviour.Varpop:
159                                 break; /* we are conservative and assume it doesn't decrease the stack needs */
160                         case StackBehaviour.Pop1:
161                         case StackBehaviour.Popi:
162                         case StackBehaviour.Popref:
163                                 cur_stack --;
164                                 break;
165                         case StackBehaviour.Pop1_pop1:
166                         case StackBehaviour.Popi_pop1:
167                         case StackBehaviour.Popi_popi:
168                         case StackBehaviour.Popi_popi8:
169                         case StackBehaviour.Popi_popr4:
170                         case StackBehaviour.Popi_popr8:
171                         case StackBehaviour.Popref_pop1:
172                         case StackBehaviour.Popref_popi:
173                                 cur_stack -= 2;
174                                 break;
175                         case StackBehaviour.Popi_popi_popi:
176                         case StackBehaviour.Popref_popi_popi:
177                         case StackBehaviour.Popref_popi_popi8:
178                         case StackBehaviour.Popref_popi_popr4:
179                         case StackBehaviour.Popref_popi_popr8:
180                         case StackBehaviour.Popref_popi_popref:
181                                 cur_stack -= 3;
182                                 break;
183                         }
184                 }
185
186                 private static int target_len (OpCode opcode) {
187                         if (opcode.operandType == OperandType.InlineBrTarget)
188                                 return 4;
189                         return 1;
190                 }
191
192                 public virtual void BeginCatchBlock (Type exceptionType) {
193                         if (cur_block < 0)
194                                 throw new NotSupportedException ("Not in an exception block");
195                         // how could we optimize code size here?
196                         Emit (OpCodes.Leave, ex_handlers [cur_block].end);
197                         ex_handlers [cur_block].AddCatch (exceptionType, code_len);
198                         System.Console.WriteLine ("Begin catch Block: "+exceptionType.ToString());
199                         //throw new NotImplementedException ();
200                 }
201                 public virtual void BeginExceptFilterBlock () {
202                         throw new NotImplementedException ();
203                 }
204                 public virtual Label BeginExceptionBlock () {
205                         System.Console.WriteLine ("Begin Block");
206                         
207                         ++ cur_block;
208                         if (ex_handlers != null) {
209                                 ILExceptionInfo[] new_ex = new ILExceptionInfo [cur_block + 1];
210                                 System.Array.Copy (ex_handlers, new_ex, cur_block);
211                                 ex_handlers = new_ex;
212                         } else {
213                                 ex_handlers = new ILExceptionInfo [1];
214                         }
215                         ex_handlers [cur_block].start = code_len;
216                         return ex_handlers [cur_block].end = DefineLabel ();
217                 }
218                 public virtual void BeginFaultBlock() {
219                         if (cur_block < 0)
220                                 throw new NotSupportedException ("Not in an exception block");
221                         System.Console.WriteLine ("Begin fault Block");
222                         //throw new NotImplementedException ();
223                 }
224                 public virtual void BeginFinallyBlock() {
225                         if (cur_block < 0)
226                                 throw new NotSupportedException ("Not in an exception block");
227                         System.Console.WriteLine ("Begin finally Block");
228                         //throw new NotImplementedException ();
229                 }
230                 public virtual void BeginScope () {
231                         throw new NotImplementedException ();
232                 }
233                 public virtual LocalBuilder DeclareLocal (Type localType) {
234                         LocalBuilder res = new LocalBuilder (localType);
235                         if (locals != null) {
236                                 LocalBuilder[] new_l = new LocalBuilder [locals.Length + 1];
237                                 System.Array.Copy (locals, new_l, locals.Length);
238                                 new_l [locals.Length] = res;
239                                 locals = new_l;
240                         } else {
241                                 locals = new LocalBuilder [1];
242                                 locals [0] = res;
243                         }
244                         res.position = locals.Length - 1;
245                         return res;
246                 }
247                 public virtual Label DefineLabel () {
248                         if (num_labels >= label_to_addr.Length) {
249                                 int[] new_l = new int [label_to_addr.Length + 16];
250                                 System.Array.Copy (label_to_addr, new_l, label_to_addr.Length);
251                                 label_to_addr = new_l;
252                         }
253                         label_to_addr [num_labels] = -1;
254                         return new Label (num_labels++);
255                 }
256                 public virtual void Emit (OpCode opcode) {
257                         make_room (2);
258                         ll_emit (opcode);
259                 }
260                 public virtual void Emit (OpCode opcode, Byte val) {
261                         make_room (3);
262                         ll_emit (opcode);
263                         code [code_len++] = val;
264                 }
265                 public virtual void Emit (OpCode opcode, ConstructorInfo constructor) {
266                         int token = abuilder.GetToken (constructor);
267                         make_room (6);
268                         ll_emit (opcode);
269                         emit_int (token);
270                 }
271                 public virtual void Emit (OpCode opcode, Double val) {
272                         byte[] s = System.BitConverter.GetBytes (val);
273                         make_room (10);
274                         ll_emit (opcode);
275                         System.Array.Copy (s, 0, code, code_len, 8);
276                         code_len += 8;
277                 }
278                 public virtual void Emit (OpCode opcode, FieldInfo field) {
279                         int token = abuilder.GetToken (field);
280                         make_room (6);
281                         ll_emit (opcode);
282                         emit_int (token);
283                 }
284                 public virtual void Emit (OpCode opcode, Int16 val) {
285                         make_room (4);
286                         ll_emit (opcode);
287                         code [code_len++] = (byte) (val & 0xFF);
288                         code [code_len++] = (byte) ((val >> 8) & 0xFF);
289                 }
290                 public virtual void Emit (OpCode opcode, Int32 val) {
291                         make_room (6);
292                         ll_emit (opcode);
293                         emit_int (val);
294                 }
295                 public virtual void Emit (OpCode opcode, Int64 val) {
296                         make_room (10);
297                         ll_emit (opcode);
298                         code [code_len++] = (byte) (val & 0xFF);
299                         code [code_len++] = (byte) ((val >> 8) & 0xFF);
300                         code [code_len++] = (byte) ((val >> 16) & 0xFF);
301                         code [code_len++] = (byte) ((val >> 24) & 0xFF);
302                         code [code_len++] = (byte) ((val >> 32) & 0xFF);
303                         code [code_len++] = (byte) ((val >> 40) & 0xFF);
304                         code [code_len++] = (byte) ((val >> 48) & 0xFF);
305                         code [code_len++] = (byte) ((val >> 56) & 0xFF);
306                 }
307                 public virtual void Emit (OpCode opcode, Label label) {
308                         int tlen = target_len (opcode);
309                         make_room (6);
310                         ll_emit (opcode);
311                         if (num_fixups >= fixups.Length) {
312                                 LabelFixup[] newf = new LabelFixup [fixups.Length + 16];
313                                 System.Array.Copy (fixups, newf, fixups.Length);
314                                 fixups = newf;
315                         }
316                         fixups [num_fixups].size = tlen;
317                         fixups [num_fixups].pos = code_len;
318                         fixups [num_fixups].label_idx = label.label;
319                         num_fixups++;
320                         code_len += tlen;
321
322                 }
323                 public virtual void Emit (OpCode opcode, Label[] labels) {
324                         /* opcode needs to be switch. */
325                         int count = labels.Length;
326                         make_room (6 + count * 4);
327                         ll_emit (opcode);
328                         emit_int (count);
329                         if (num_fixups + count >= fixups.Length) {
330                                 LabelFixup[] newf = new LabelFixup [fixups.Length + count + 16];
331                                 System.Array.Copy (fixups, newf, fixups.Length);
332                                 fixups = newf;
333                         }
334                         for (int i = 0; i < count; ++i) {
335                                 fixups [num_fixups].size = 4;
336                                 fixups [num_fixups].pos = code_len;
337                                 fixups [num_fixups].label_idx = labels [i].label;
338                                 num_fixups++;
339                                 code_len += 4;
340                         }
341                 }
342                 public virtual void Emit (OpCode opcode, LocalBuilder lbuilder) {
343                         make_room (6);
344                         ll_emit (opcode);
345                         code [code_len++] = (byte) (lbuilder.position & 0xFF);
346                         if (opcode.operandType == OperandType.InlineVar) {
347                                 code [code_len++] = (byte) ((lbuilder.position >> 8) & 0xFF);
348                         }
349                 }
350                 public virtual void Emit (OpCode opcode, MethodInfo method) {
351                         int token = abuilder.GetToken (method);
352                         make_room (6);
353                         ll_emit (opcode);
354                         emit_int (token);
355                 }
356                 [CLSCompliant(false)]
357                 public virtual void Emit (OpCode opcode, sbyte val) {
358                         make_room (3);
359                         ll_emit (opcode);
360                         code [code_len++] = (byte)val;
361                 }
362
363                 [MonoTODO]
364                 public virtual void Emit (OpCode opcode, SignatureHelper shelper) {
365                         int token = 0; // FIXME: request a token from the modulebuilder
366                         make_room (6);
367                         ll_emit (opcode);
368                         emit_int (token);
369                 }
370                 public virtual void Emit (OpCode opcode, float val) {
371                         byte[] s = System.BitConverter.GetBytes (val);
372                         make_room (6);
373                         ll_emit (opcode);
374                         System.Array.Copy (s, 0, code, code_len, 4);
375                         code_len += 4;
376                 }
377                 public virtual void Emit (OpCode opcode, string val) {
378                         int token = abuilder.GetToken (val);
379                         make_room (3);
380                         ll_emit (opcode);
381                         emit_int (token);
382                 }
383                 public virtual void Emit (OpCode opcode, Type type) {
384                         make_room (6);
385                         ll_emit (opcode);
386                         emit_int (abuilder.GetToken (type));
387                 }
388
389                 public void EmitCall (OpCode opcode, MethodInfo methodinfo, Type[] optionalParamTypes) {
390                         throw new NotImplementedException ();
391                 }
392                 public void EmitCalli (OpCode opcode, CallingConventions call_conv, Type returnType, Type[] paramTypes, Type[] optionalParamTypes) {
393                         throw new NotImplementedException ();
394                 }
395
396                 public virtual void EmitWriteLine (FieldInfo field) {
397                         throw new NotImplementedException ();
398                 }
399                 public virtual void EmitWriteLine (LocalBuilder lbuilder) {
400                         throw new NotImplementedException ();
401                 }
402                 public virtual void EmitWriteLine (string val) {
403                         throw new NotImplementedException ();
404                 }
405
406                 public virtual void EndExceptionBlock () {
407                         if (cur_block < 0)
408                                 throw new NotSupportedException ("Not in an exception block");
409                         // how could we optimize code size here?
410                         Emit (OpCodes.Leave, ex_handlers [cur_block].end);
411                         MarkLabel (ex_handlers [cur_block].end);
412                         ex_handlers [cur_block].End (code_len);
413                         ex_handlers [cur_block].Debug ();
414                         System.Console.WriteLine ("End Block");
415                         //throw new NotImplementedException ();
416                 }
417                 public virtual void EndScope () {
418                         throw new NotImplementedException ();
419                 }
420                 public virtual void MarkLabel (Label loc) {
421                         if (loc.label < 0 || loc.label >= num_labels)
422                                 throw new System.ArgumentException ("The label is not valid");
423                         if (label_to_addr [loc.label] >= 0)
424                                 throw new System.ArgumentException ("The label was already defined");
425                         label_to_addr [loc.label] = code_len;
426                 }
427                 public virtual void MarkSequencePoint (ISymbolDocumentWriter document, int startLine, int startColumn, int endLine, int EndColumn) {
428                         throw new NotImplementedException ();
429                 }
430                 public virtual void ThrowException (Type exceptionType) {
431                         throw new NotImplementedException ();
432                 }
433                 public virtual void UsingNamespace (String usingNamespace) {
434                         throw new NotImplementedException ();
435                 }
436
437                 internal void label_fixup () {
438                         int i;
439                         for (i = 0; i < num_fixups; ++i) {
440                                 int diff = label_to_addr [fixups [i].label_idx] - fixups [i].pos;
441                                 if (fixups [i].size == 1) {
442                                         code [fixups [i].pos] = (byte)((sbyte) diff - 1);
443                                 } else {
444                                         int old_cl = code_len;
445                                         code_len = fixups [i].pos;
446                                         emit_int (diff - 4);
447                                         code_len = old_cl;
448                                 }
449                         }
450                 }
451         }
452 }