Sun Feb 10 12:54:05 CET 2002 Paolo Molaro <lupus@ximian.com>
[mono.git] / mono / jit / emit-x86.c
1 /*
2  * emit-x86.c: Support functions for emitting x86 code
3  *
4  * Authors:
5  *   Dietmar Maurer (dietmar@ximian.com)
6  *   Miguel de Icaza (miguel@ximian.com)
7  *
8  * (C) 2001 Ximian, Inc.
9  */
10
11 #include <config.h>
12 #include <glib.h>
13
14 #include <mono/metadata/assembly.h>
15 #include <mono/metadata/loader.h>
16 #include <mono/metadata/cil-coff.h>
17 #include <mono/metadata/tabledefs.h>
18 #include <mono/metadata/class.h>
19 #include <mono/metadata/mono-endian.h>
20 #include <mono/arch/x86/x86-codegen.h>
21
22 #include "jit.h"
23 #include "codegen.h"
24 #include "debug.h"
25
26 static void
27 enter_method (MonoMethod *method, gpointer ebp)
28 {
29         int i, j;
30         MonoClass *class;
31         MonoObject *o;
32
33         printf ("ENTER: %s.%s::%s\n(", method->klass->name_space,
34                 method->klass->name, method->name);
35
36         
37         if (((int)ebp & 3) != 0) {
38                 g_error ("unaligned stack detected (%p)", ebp);
39         }
40
41         ebp += 8;
42
43         if (ISSTRUCT (method->signature->ret)) {
44                 int size, align;
45                 
46                 g_assert (!method->signature->ret->byref);
47
48                 size = mono_type_stack_size (method->signature->ret, &align);
49
50                 printf ("VALUERET:%p, ", *((gpointer *)ebp));
51                 ebp += sizeof (gpointer);
52         }
53
54         if (method->signature->hasthis) {
55                 if (method->klass->valuetype) {
56                         printf ("value:%p, ", *((gpointer *)ebp));
57                 } else {
58                         o = *((MonoObject **)ebp);
59
60                         g_assert (o);
61
62                         class = o->klass;
63
64                         if (class == mono_defaults.string_class) {
65                                 printf ("this:[STRING:%p:%s], ", o, mono_string_to_utf8 ((MonoString *)o));
66                         } else {
67                                 printf ("this:%p[%s.%s], ", o, class->name_space, class->name);
68                         }
69                 }
70                 ebp += sizeof (gpointer);
71         }
72
73         for (i = 0; i < method->signature->param_count; ++i) {
74                 MonoType *type = method->signature->params [i];
75                 int size, align;
76                 size = mono_type_stack_size (type, &align);
77
78                 if (type->byref) {
79                         printf ("[BYREF:%p], ", *((gpointer *)ebp)); 
80                 } else switch (type->type) {
81                         
82                 case MONO_TYPE_BOOLEAN:
83                 case MONO_TYPE_CHAR:
84                 case MONO_TYPE_I1:
85                 case MONO_TYPE_U1:
86                 case MONO_TYPE_I2:
87                 case MONO_TYPE_U2:
88                 case MONO_TYPE_I4:
89                 case MONO_TYPE_U4:
90                 case MONO_TYPE_I:
91                 case MONO_TYPE_U:
92                         printf ("%d, ", *((int *)(ebp)));
93                         break;
94                 case MONO_TYPE_STRING: {
95                         MonoString *s = *((MonoString **)ebp);
96                         if (s) {
97                                 g_assert (((MonoObject *)s)->klass == mono_defaults.string_class);
98                                 printf ("[STRING:%p:%s], ", s, mono_string_to_utf8 (s));
99                         } else 
100                                 printf ("[STRING:null], ");
101                         break;
102                 }
103                 case MONO_TYPE_CLASS:
104                 case MONO_TYPE_OBJECT: {
105                         o = *((MonoObject **)ebp);
106                         if (o) {
107                                 class = o->klass;
108                     
109                                 if (class == mono_defaults.string_class) {
110                                         printf ("[STRING:%p:%s], ", o, mono_string_to_utf8 ((MonoString *)o));
111                                 } else if (class == mono_defaults.int32_class) {
112                                         printf ("[INT32:%p:%d], ", o, *(gint32 *)((gpointer)o + sizeof (MonoObject)));
113                                 } else
114                                         printf ("[%s.%s:%p], ", class->name_space, class->name, o);
115                         } else {
116                                 printf ("%p, ", *((gpointer *)(ebp)));                          
117                         }
118                         break;
119                 }
120                 case MONO_TYPE_PTR:
121                 case MONO_TYPE_FNPTR:
122                 case MONO_TYPE_ARRAY:
123                 case MONO_TYPE_SZARRAY:
124                         printf ("%p, ", *((gpointer *)(ebp)));
125                         break;
126                 case MONO_TYPE_I8:
127                         printf ("%lld, ", *((gint64 *)(ebp)));
128                         break;
129                 case MONO_TYPE_R4:
130                         printf ("%f, ", *((float *)(ebp)));
131                         break;
132                 case MONO_TYPE_R8:
133                         printf ("%f, ", *((double *)(ebp)));
134                         break;
135                 case MONO_TYPE_VALUETYPE: 
136                         printf ("[");
137                         for (j = 0; j < size; j++)
138                                 printf ("%02x,", *((guint8*)ebp +j));
139                         printf ("], ");
140                         break;
141                 default:
142                         printf ("XX, ");
143                 }
144
145                 g_assert (align == 4);
146                 ebp += size + 3;
147                 ebp = (gpointer)((unsigned)ebp & ~(3));
148         }
149
150         printf (")\n");
151 }
152
153 static void
154 leave_method (MonoMethod *method, int edx, int eax, double test)
155 {
156         gint64 l;
157
158         printf ("LEAVE: %s.%s::%s ", method->klass->name_space,
159                 method->klass->name, method->name);
160
161         switch (method->signature->ret->type) {
162         case MONO_TYPE_VOID:
163                 break;
164         case MONO_TYPE_BOOLEAN:
165                 if (eax)
166                         printf ("TRUE:%d", eax);
167                 else 
168                         printf ("FALSE");
169                         
170                 break;
171         case MONO_TYPE_CHAR:
172         case MONO_TYPE_I1:
173         case MONO_TYPE_U1:
174         case MONO_TYPE_I2:
175         case MONO_TYPE_U2:
176         case MONO_TYPE_I4:
177         case MONO_TYPE_U4:
178         case MONO_TYPE_I:
179         case MONO_TYPE_U:
180                 printf ("EAX=%d", eax);
181                 break;
182         case MONO_TYPE_STRING: {
183                 MonoString *s = (MonoString *)eax;
184
185                 if (s) {
186                         g_assert (((MonoObject *)s)->klass == mono_defaults.string_class);
187                         printf ("[STRING:%p:%s]", s, mono_string_to_utf8 (s));
188                 } else 
189                         printf ("[STRING:null], ");
190                 break;
191         }
192         case MONO_TYPE_OBJECT: {
193                 MonoObject *o = (MonoObject *)eax;
194
195                 if (o) {
196                         if (o->klass == mono_defaults.boolean_class) {
197                                 printf ("[BOOLEAN:%p:%d]", o, *((guint8 *)o + sizeof (MonoObject)));            
198                         } else if  (o->klass == mono_defaults.int32_class) {
199                                 printf ("[INT32:%p:%d]", o, *((gint32 *)((gpointer)o + sizeof (MonoObject))));  
200                         } else
201                                 printf ("[%s.%s:%p]", o->klass->name_space, o->klass->name, o);
202                 } else
203                         printf ("[OBJECT:%p]", o);
204                
205                 break;
206         }
207         case MONO_TYPE_CLASS:
208         case MONO_TYPE_PTR:
209         case MONO_TYPE_FNPTR:
210         case MONO_TYPE_ARRAY:
211         case MONO_TYPE_SZARRAY:
212                 printf ("EAX=%p", (gpointer)eax);
213                 break;
214         case MONO_TYPE_I8:
215                 *((gint32 *)&l) = eax;
216                 *((gint32 *)&l + 1) = edx;
217                 printf ("EAX/EDX=%lld", l);
218                 break;
219         case MONO_TYPE_R8:
220                 printf ("FP=%f\n", test);
221                 break;
222         default:
223                 printf ("(unknown return type)");
224         }
225
226         printf ("\n");
227 }
228
229 /**
230  * arch_emit_prologue:
231  * @cfg: pointer to status information
232  *
233  * Emits the function prolog.
234  */
235 static void
236 arch_emit_prologue (MonoFlowGraph *cfg)
237 {
238         x86_push_reg (cfg->code, X86_EBP);
239         x86_mov_reg_reg (cfg->code, X86_EBP, X86_ESP, 4);
240
241         if (cfg->locals_size)
242                 x86_alu_reg_imm (cfg->code, X86_SUB, X86_ESP, cfg->locals_size);
243
244         if (mono_regset_reg_used (cfg->rs, X86_EBX)) 
245                 x86_push_reg (cfg->code, X86_EBX);
246
247         if (mono_regset_reg_used (cfg->rs, X86_EDI)) 
248                 x86_push_reg (cfg->code, X86_EDI);
249
250         if (mono_regset_reg_used (cfg->rs, X86_ESI))
251                 x86_push_reg (cfg->code, X86_ESI);
252
253         if (mono_jit_trace_calls) {
254                 x86_push_reg (cfg->code, X86_EBP);
255                 x86_push_imm (cfg->code, cfg->method);
256                 x86_mov_reg_imm (cfg->code, X86_EAX, enter_method);
257                 x86_call_reg (cfg->code, X86_EAX);
258                 x86_alu_reg_imm (cfg->code, X86_ADD, X86_ESP, 8);
259         }
260 }
261
262 /**
263  * arch_emit_epilogue:
264  * @cfg: pointer to status information
265  *
266  * Emits the function epilog.
267  */
268 static void
269 arch_emit_epilogue (MonoFlowGraph *cfg)
270 {
271         if (mono_jit_trace_calls) {
272                 x86_fld_reg (cfg->code, 0);
273                 x86_alu_reg_imm (cfg->code, X86_SUB, X86_ESP, 8);
274                 x86_fst_membase (cfg->code, X86_ESP, 0, TRUE, TRUE);
275                 x86_push_reg (cfg->code, X86_EAX);
276                 x86_push_reg (cfg->code, X86_EDX);
277                 x86_push_imm (cfg->code, cfg->method);
278                 x86_mov_reg_imm (cfg->code, X86_EAX, leave_method);
279                 x86_call_reg (cfg->code, X86_EAX);
280                 x86_alu_reg_imm (cfg->code, X86_ADD, X86_ESP, 4);
281                 x86_pop_reg (cfg->code, X86_EDX);
282                 x86_pop_reg (cfg->code, X86_EAX);
283                 x86_alu_reg_imm (cfg->code, X86_ADD, X86_ESP, 8);
284         }
285
286         if (mono_regset_reg_used (cfg->rs, X86_ESI))
287                 x86_pop_reg (cfg->code, X86_ESI);
288
289         if (mono_regset_reg_used (cfg->rs, X86_EDI))
290                 x86_pop_reg (cfg->code, X86_EDI);
291
292         if (mono_regset_reg_used (cfg->rs, X86_EBX))
293                 x86_pop_reg (cfg->code, X86_EBX);
294
295         x86_leave (cfg->code);
296         x86_ret (cfg->code);
297 }
298
299 /*
300  * get_unbox_trampoline:
301  * @m: method pointer
302  *
303  * when value type methods are called through the vtable we need to unbox the
304  * this argument. This method returns a pointer to a trampoline which does
305  * unboxing before calling the method
306  */
307 static gpointer
308 get_unbox_trampoline (MonoMethod *m)
309 {
310         gpointer p = arch_compile_method (m);
311         guint8 *code, *start;
312         int this_pos = 4;
313
314         if (!m->signature->ret->byref && m->signature->ret->type == MONO_TYPE_VALUETYPE)
315                 this_pos = 8;
316             
317         start = code = g_malloc (16);
318
319         x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
320         x86_jump_code (code, p);
321         g_assert ((code - start) < 16);
322
323         return start;
324 }
325
326 /**
327  * x86_magic_trampoline:
328  * @eax: saved x86 register 
329  * @ecx: saved x86 register 
330  * @edx: saved x86 register 
331  * @esi: saved x86 register 
332  * @edi: saved x86 register 
333  * @ebx: saved x86 register
334  * @code: pointer into caller code
335  * @method: the method to translate
336  *
337  * This method is called by the trampoline functions for virtual
338  * methods. It inspects the caller code to find the address of the
339  * vtable slot, then calls the JIT compiler and writes the address
340  * of the compiled method back to the vtable. All virtual methods 
341  * are called with: x86_call_membase (inst, basereg, disp). We always
342  * use 32 bit displacement to ensure that the length of the call 
343  * instruction is 6 bytes. We need to get the value of the basereg 
344  * and the constant displacement.
345  */
346 static gpointer
347 x86_magic_trampoline (int eax, int ecx, int edx, int esi, int edi, 
348                       int ebx, const guint8 *code, MonoMethod *m)
349 {
350         guint8 ab, reg;
351         gint32 disp;
352         gpointer o;
353
354         /* go to the start of the call instruction
355          *
356          * address_byte = (m << 6) | (o << 3) | reg
357          * call opcode: 0xff address_byte displacement
358          * 0xff m=1,o=2 imm8
359          * 0xff m=2,o=2 imm32
360          */
361         code -= 6;
362         if ((code [3] == 0xff) && ((code [4] & 0x18) == 0x10) && ((code [4] >> 6) == 1)) {
363                 reg = code [4] & 0x07;
364                 disp = (signed char)code [5];
365         } else {
366                 if ((code [0] == 0xff) && ((code [1] & 0x18) == 0x10) && ((code [1] >> 6) == 2)) {
367                         reg = code [1] & 0x07;
368                         disp = *((gint32*)(code + 2));
369                 } else {
370                         g_assert_not_reached ();
371                 }
372         }
373
374         switch (reg) {
375         case X86_EAX:
376                 o = (gpointer)eax;
377                 break;
378         case X86_EDX:
379                 o = (gpointer)edx;
380                 break;
381         case X86_ECX:
382                 o = (gpointer)ecx;
383                 break;
384         case X86_ESI:
385                 o = (gpointer)esi;
386                 break;
387         case X86_EDI:
388                 o = (gpointer)edi;
389                 break;
390         case X86_EBX:
391                 o = (gpointer)ebx;
392                 break;
393         default:
394                 g_assert_not_reached ();
395         }
396
397         o += disp;
398
399         if (m->klass->valuetype) {
400                 return *((gpointer *)o) = get_unbox_trampoline (m);
401         } else
402                 return *((gpointer *)o) = arch_compile_method (m);
403 }
404
405 /**
406  * arch_create_jit_trampoline:
407  * @method: pointer to the method info
408  *
409  * Creates a trampoline function for virtual methods. If the created
410  * code is called it first starts JIT compilation of method,
411  * and then calls the newly created method. I also replaces the
412  * corresponding vtable entry (see x86_magic_trampoline).
413  * 
414  * Returns: a pointer to the newly created code 
415  */
416 gpointer
417 arch_create_jit_trampoline (MonoMethod *method)
418 {
419         guint8 *code, *buf;
420         static guint8 *vc = NULL;
421
422         if (method->addr)
423                 return method->addr;
424
425         if (!vc) {
426                 vc = buf = g_malloc (24);
427
428                 /* push the return address onto the stack */
429                 x86_push_membase (buf, X86_ESP, 4);
430
431                 /* save all register values */
432                 x86_push_reg (buf, X86_EBX);
433                 x86_push_reg (buf, X86_EDI);
434                 x86_push_reg (buf, X86_ESI);
435                 x86_push_reg (buf, X86_EDX);
436                 x86_push_reg (buf, X86_ECX);
437                 x86_push_reg (buf, X86_EAX);
438
439                 x86_call_code (buf, x86_magic_trampoline);
440                 x86_alu_reg_imm (buf, X86_ADD, X86_ESP, 8*4);
441
442                 /* call the compiled method */
443                 x86_jump_reg (buf, X86_EAX);
444
445                 g_assert ((buf - vc) <= 24);
446         }
447
448         code = buf = g_malloc (16);
449         x86_push_imm (buf, method);
450         x86_jump_code (buf, vc);
451         g_assert ((buf - code) <= 16);
452
453         return code;
454 }
455
456 /**
457  * arch_create_simple_jit_trampoline:
458  * @method: pointer to the method info
459  *
460  * Creates a trampoline function for method. If the created
461  * code is called it first starts JIT compilation of method,
462  * and then calls the newly created method. I also replaces the
463  * address in method->addr with the result of the JIT 
464  * compilation step (in arch_compile_method).
465  * 
466  * Returns: a pointer to the newly created code 
467  */
468 gpointer
469 arch_create_simple_jit_trampoline (MonoMethod *method)
470 {
471         guint8 *code, *buf;
472
473         if (method->addr)
474                 return method->addr;
475
476         /* we never free the allocated code buffer */
477         code = buf = g_malloc (16);
478         x86_push_imm (buf, method);
479         x86_call_code (buf, arch_compile_method);
480         x86_alu_reg_imm (buf, X86_ADD, X86_ESP, 4);
481         /* jump to the compiled method */
482         x86_jump_reg (buf, X86_EAX);
483         g_assert ((buf - code) < 16);
484
485         return code;
486 }
487
488 static void
489 mono_label_cfg (MonoFlowGraph *cfg)
490 {
491         int i, j;
492         
493         for (i = 0; i < cfg->block_count; i++) {
494                 GPtrArray *forest = cfg->bblocks [i].forest;
495                 const int top = forest->len;
496
497                 for (j = 0; j < top; j++) {
498                         MBTree *t1 = (MBTree *) g_ptr_array_index (forest, j);
499                         MBState *mbstate;
500
501                         mbstate =  mono_burg_label (t1, cfg);
502                         if (!mbstate) {
503                                 cfg->invalid = 1;
504                                 if (mono_debug_handle)
505                                         return;
506                                 g_warning ("tree does not match");
507                                 mono_print_ctree (t1); printf ("\n\n");
508
509                                 mono_print_forest (forest);
510                                 g_assert_not_reached ();
511                         }
512                 }
513         }
514 }
515
516 static void
517 tree_preallocate_regs (MBTree *tree, int goal, MonoRegSet *rs) 
518 {
519         switch (tree->op) {
520         case MB_TERM_CALL_I4:
521         case MB_TERM_CALL_I8:
522         case MB_TERM_CALL_R8:
523 //      case MB_TERM_CALL_VOID :
524                 tree->reg1 = mono_regset_alloc_reg (rs, X86_EAX, tree->exclude_mask);
525                 tree->reg2 = mono_regset_alloc_reg (rs, X86_EDX, tree->exclude_mask);
526                 tree->reg3 = mono_regset_alloc_reg (rs, X86_ECX, tree->exclude_mask);
527                 return;
528         default: break;
529         }
530
531         switch (goal) {
532         case MB_NTERM_reg:
533         case MB_NTERM_lreg: {
534                 switch (tree->op) {
535                 case MB_TERM_SHL:
536                 case MB_TERM_SHR:
537                 case MB_TERM_SHR_UN:
538                         tree->exclude_mask |= (1 << X86_ECX);
539                         tree->left->exclude_mask |= (1 << X86_ECX);
540                         break;
541                 case MB_TERM_MUL:
542                 case MB_TERM_MUL_OVF:
543                 case MB_TERM_MUL_OVF_UN:
544                 case MB_TERM_DIV:
545                 case MB_TERM_DIV_UN:
546                 case MB_TERM_REM:
547                 case MB_TERM_REM_UN:
548                         tree->reg1 = mono_regset_alloc_reg (rs, X86_EAX, tree->exclude_mask);
549                         tree->reg2 = mono_regset_alloc_reg (rs, X86_EDX, tree->exclude_mask);
550                         if (goal == MB_NTERM_reg) {
551                                 tree->left->exclude_mask |= (1 << X86_EDX);
552                                 tree->right->exclude_mask |= (1 << X86_EDX) | (1 << X86_EAX);
553                         }
554                         break;
555                 default:
556                         break;
557                 }
558                 break;
559         }
560         default:
561                 break;
562         }
563 }
564
565 static void
566 tree_allocate_regs (MBTree *tree, int goal, MonoRegSet *rs) 
567 {
568         MBTree *kids[10];
569         int ern = mono_burg_rule (tree->state, goal);
570         guint16 *nts = mono_burg_nts [ern];
571         int i;
572         
573         mono_burg_kids (tree, ern, kids);
574
575         //printf ("RALLOC START %d %p %d\n",  tree->op, rs->free_mask, goal);
576
577         if (nts [0] && kids [0] == tree) {
578                 /* chain rule */
579                 tree_allocate_regs (kids [0], nts [0], rs);
580                 return;
581         }
582
583         for (i = 0; nts [i]; i++)
584                 tree_preallocate_regs (kids [i], nts [i], rs);
585
586         for (i = 0; nts [i]; i++)
587                 tree_allocate_regs (kids [i], nts [i], rs);
588
589         for (i = 0; nts [i]; i++) {
590                 mono_regset_free_reg (rs, kids [i]->reg1);
591                 mono_regset_free_reg (rs, kids [i]->reg2);
592                 mono_regset_free_reg (rs, kids [i]->reg3);
593         }
594
595         switch (goal) {
596         case MB_NTERM_reg:
597                 if (tree->reg1 < 0) { 
598                         tree->reg1 = mono_regset_alloc_reg (rs, -1, tree->exclude_mask);
599                         g_assert (tree->reg1 != -1);
600                 }
601                 break;
602
603         case MB_NTERM_lreg:
604                 if (tree->reg1 < 0) { 
605                         tree->reg1 = mono_regset_alloc_reg (rs, -1, tree->exclude_mask);
606                         g_assert (tree->reg1 != -1);
607                 }
608                 if (tree->reg2 < 0) { 
609                         tree->reg2 = mono_regset_alloc_reg (rs, -1, tree->exclude_mask);
610                         g_assert (tree->reg2 != -1);
611                 }
612                 break;
613
614         case MB_NTERM_freg:
615                 /* fixme: allocate floating point registers */
616                 break;
617       
618         case MB_NTERM_addr:
619                 if (tree->op == MB_TERM_ADD) {
620                         tree->reg1 = mono_regset_alloc_reg (rs, tree->left->reg1, tree->exclude_mask);
621                         tree->reg2 = mono_regset_alloc_reg (rs, tree->right->reg1, tree->exclude_mask);
622                 }
623                 break;
624                 
625         case MB_NTERM_base:
626                 if (tree->op == MB_TERM_ADD) {
627                         tree->reg1 = mono_regset_alloc_reg (rs, tree->left->reg1, tree->exclude_mask);
628                 }
629                 break;
630                
631         case MB_NTERM_index:
632                 if (tree->op == MB_TERM_SHL ||
633                     tree->op == MB_TERM_MUL) {
634                         tree->reg1 = mono_regset_alloc_reg (rs, tree->left->reg1, tree->exclude_mask);
635                 }
636                 break;
637                
638         default:
639                 /* do nothing */
640         }
641
642         //printf ("RALLOC END %d %p\n",  tree->op, rs->free_mask);
643         tree->emit = mono_burg_func [ern];
644 }
645
646 static void
647 arch_allocate_regs (MonoFlowGraph *cfg)
648 {
649         int i, j;
650         
651         for (i = 0; i < cfg->block_count; i++) {
652                 GPtrArray *forest = cfg->bblocks [i].forest;
653                 const int top = forest->len;
654
655                 for (j = 0; j < top; j++) {
656                         MBTree *t1 = (MBTree *) g_ptr_array_index (forest, j);
657                         //printf ("AREGSTART %d:%d %p\n", i, j, cfg->rs->free_mask);
658                         tree_allocate_regs (t1, 1, cfg->rs);
659                         //printf ("AREGENDT %d:%d %p\n", i, j, cfg->rs->free_mask);
660                         g_assert (cfg->rs->free_mask == 0xffffffff);
661                 }
662         }
663 }
664
665 static void
666 tree_emit (int goal, MonoFlowGraph *cfg, MBTree *tree) 
667 {
668         MBTree *kids[10];
669         int i, ern = mono_burg_rule (tree->state, goal);
670         guint16 *nts = mono_burg_nts [ern];
671         MBEmitFunc emit;
672         int offset;
673
674         mono_burg_kids (tree, ern, kids);
675
676         for (i = 0; nts [i]; i++) 
677                 tree_emit (nts [i], cfg, kids [i]);
678
679         tree->addr = offset = cfg->code - cfg->start;
680
681         // we assume an instruction uses a maximum of 128 bytes
682         if ((cfg->code_size - offset) <= 128) {
683                 int add = MIN ((cfg->code_size * 2), 1024);
684
685                 cfg->code_size += add;
686                 cfg->start = g_realloc (cfg->start, cfg->code_size);
687                 g_assert (cfg->start);
688                 cfg->code = cfg->start + offset;
689         }
690
691         if ((emit = mono_burg_func [ern]))
692                 emit (tree, cfg);
693
694         g_assert ((cfg->code - cfg->start) < cfg->code_size);
695 }
696
697 static void
698 mono_emit_cfg (MonoFlowGraph *cfg)
699 {
700         int i, j;
701
702         for (i = 0; i < cfg->block_count; i++) {
703                 MonoBBlock *bb = &cfg->bblocks [i];
704                 GPtrArray *forest = bb->forest;
705                 const int top = forest->len;
706
707                 bb->addr = cfg->code - cfg->start;
708           
709                 for (j = 0; j < top; j++) {
710                         MBTree *t1 = (MBTree *) g_ptr_array_index (forest, j);
711                         
712                         tree_emit (1, cfg, t1);
713                 }
714         }
715                 
716         cfg->epilog = cfg->code - cfg->start;
717 }
718
719 static void
720 mono_compute_branches (MonoFlowGraph *cfg)
721 {
722         guint8 *end;
723         int i, j;
724
725         end = cfg->code;
726
727         for (j = 0; j < cfg->block_count; j++) {
728                 MonoBBlock *bb = &cfg->bblocks [j];
729                 GPtrArray *forest = bb->forest;
730                 const int top = forest->len;
731         
732                 for (i = 0; i < top; i++) {
733                         MBTree *t1 = (MBTree *) g_ptr_array_index (forest, i);
734
735                         if (t1->is_jump) {
736
737                                 if (t1->op == MB_TERM_SWITCH) {
738                                         MonoBBlock **jt = (MonoBBlock **)t1->data.p;
739                                         guint32 *rt = (guint32 *)t1->data.p;
740
741                                         int m = *((guint32 *)t1->data.p) + 1;
742                                         int j;
743                                         
744                                         for (j = 1; j <= m; j++)
745                                                 rt [j] = (int)(jt [j]->addr + cfg->start);
746                                 }
747
748                                 /* emit the jump instruction again to update addresses */
749                                 cfg->code = cfg->start + t1->addr;
750                                 ((MBEmitFunc)t1->emit) (t1, cfg);
751
752                         }
753                 }
754         }
755
756         cfg->code = end;
757 }
758
759 static int
760 match_debug_method (MonoMethod* method)
761 {
762         GList *tmp = mono_debug_methods;
763
764         for (; tmp; tmp = tmp->next) {
765                 if (strcmp (method->name, tmp->data) == 0) {
766                         return 1;
767                 }
768         }
769         return 0;
770 }
771
772 /**
773  * arch_compile_method:
774  * @method: pointer to the method info
775  *
776  * JIT compilation of a single method. This method also writes the result 
777  * back to method->addr, an thus overwrites the trampoline function.
778  *
779  * Returns: a pointer to the newly created code.
780  */
781 gpointer
782 arch_compile_method (MonoMethod *method)
783 {
784         MonoFlowGraph *cfg;
785         MonoMemPool *mp = mono_mempool_new ();
786
787         g_assert (!(method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL));
788         g_assert (!(method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL));
789
790         if (mono_jit_trace_calls || mono_jit_dump_asm || mono_jit_dump_forest) {
791                 printf ("Start JIT compilation of %s.%s:%s\n", method->klass->name_space,
792                         method->klass->name, method->name);
793         }
794
795         if (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) {
796                 MonoClassField *field;
797                 const char *name = method->name;
798                 static guint target_offset = 0;
799                 static guint method_offset = 0;
800                 guint8 *code;
801                 gboolean delegate = FALSE;
802
803                 if (method->klass->parent && 
804                     method->klass->parent->parent == mono_defaults.delegate_class)
805                         delegate = TRUE;
806                                 
807                 if (!target_offset) {
808                         mono_class_init (mono_defaults.delegate_class);
809
810                         field = mono_class_get_field_from_name (mono_defaults.delegate_class, "m_target");
811                         target_offset = field->offset;
812                         field = mono_class_get_field_from_name (mono_defaults.delegate_class, "method_ptr");
813                         method_offset = field->offset;
814                 }
815                 
816                 if (delegate && *name == '.' && (strcmp (name, ".ctor") == 0)) {
817                         method->addr = code = g_malloc (32);
818                         x86_push_reg (code, X86_EBP);
819                         x86_mov_reg_reg (code, X86_EBP, X86_ESP, 4);
820                         
821                         /* load the this pointer */
822                         x86_mov_reg_membase (code, X86_EAX, X86_EBP, 8, 4); 
823                         /* load m_target arg */
824                         x86_mov_reg_membase (code, X86_EDX, X86_EBP, 12, 4);
825                         /* store mtarget */
826                         x86_mov_membase_reg (code, X86_EAX, target_offset, X86_EDX, 4); 
827                         /* load method_ptr arg */
828                         x86_mov_reg_membase (code, X86_EDX, X86_EBP, 16, 4);
829                         /* store method_ptr */
830                         x86_mov_membase_reg (code, X86_EAX, method_offset, X86_EDX, 4); 
831
832                         x86_leave (code);
833                         x86_ret (code);
834
835                         g_assert ((code - (guint8*)method->addr) < 32);
836
837                 } else if (delegate && *name == 'I' && (strcmp (name, "Invoke") == 0)) {
838                         MonoMethodSignature *csig = method->signature;
839                         int i, target, this_pos = 4;
840                         guint8 *source;
841
842                         method->addr = g_malloc (64);
843
844                         if (csig->ret->type == MONO_TYPE_VALUETYPE) {
845                                 g_assert (!csig->ret->byref);
846                                 this_pos = 8;
847                         }
848
849                         for (i = 0; i < 2; i ++) {
850                                 code = method->addr;
851                                 /* load the this pointer */
852                                 x86_mov_reg_membase (code, X86_EAX, X86_ESP, this_pos, 4);
853                                 /* load mtarget */
854                                 x86_mov_reg_membase (code, X86_EDX, X86_EAX, target_offset, 4); 
855                                 /* check if zero (static method call without this pointer) */
856                                 x86_alu_reg_imm (code, X86_CMP, X86_EDX, 0);
857                                 x86_branch32 (code, X86_CC_EQ, target, TRUE); 
858                                 source = code;
859
860                                 /* virtual delegate methods: we have to replace the this pointer 
861                                  * withe the actual target */
862                                 x86_mov_membase_reg (code, X86_ESP, this_pos, X86_EDX, 4); 
863                                 /* jump to method_ptr() */
864                                 x86_jump_membase (code, X86_EAX, method_offset);
865
866                                 /* static delegate methods: we have to remove the this pointer 
867                                  * from the activation frame */
868                                 target = code - source;
869                                 if (this_pos == 8) {
870                                         x86_mov_reg_membase (code, X86_EDX, X86_ESP, 4, 4);
871                                         x86_mov_membase_reg (code, X86_ESP, 8, X86_EDX, 4);
872                                 }
873                                 x86_mov_reg_membase (code, X86_EDX, X86_ESP, 0, 4);
874                                 x86_mov_membase_reg (code, X86_ESP, 4, X86_EDX, 4);
875                                 x86_alu_reg_imm (code, X86_ADD, X86_ESP, 4);
876
877                                 /* jump to method_ptr() */
878                                 x86_jump_membase (code, X86_EAX, method_offset);
879                         }
880
881                         g_assert ((code - (guint8*)method->addr) < 64);
882
883                 } else {
884                         if (mono_debug_handle)
885                                 return NULL;
886                         g_error ("Don't know how to exec runtime method %s.%s::%s", 
887                                  method->klass->name_space, method->klass->name, method->name);
888                 }
889         
890         } else {
891                 MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
892                 MonoJitInfo *ji = g_new0 (MonoJitInfo, 1);
893                 
894                 cfg = mono_cfg_new (method, mp);
895
896                 mono_analyze_flow (cfg);
897                 if (cfg->invalid)
898                         return NULL;
899
900                 mono_analyze_stack (cfg);
901                 if (cfg->invalid)
902                         return NULL;
903         
904                 cfg->rs = mono_regset_new (X86_NREG);
905                 mono_regset_reserve_reg (cfg->rs, X86_ESP);
906                 mono_regset_reserve_reg (cfg->rs, X86_EBP);
907
908                 cfg->code_size = 256;
909                 cfg->start = cfg->code = g_malloc (cfg->code_size);
910
911                 if (match_debug_method (method))
912                         x86_breakpoint (cfg->code);
913
914                 if (mono_jit_dump_forest) {
915                         int i;
916                         printf ("FOREST %s.%s:%s\n", method->klass->name_space,
917                                 method->klass->name, method->name);
918                         for (i = 0; i < cfg->block_count; i++) {
919                                 printf ("BLOCK %d:\n", i);
920                                 mono_print_forest (cfg->bblocks [i].forest);
921                         }
922                 }
923         
924                 mono_label_cfg (cfg);
925                 if (cfg->invalid)
926                         return NULL;
927
928                 arch_allocate_regs (cfg);
929
930                 /* align to 8 byte boundary */
931                 cfg->locals_size += 7;
932                 cfg->locals_size &= ~7;
933
934                 arch_emit_prologue (cfg);
935                 mono_emit_cfg (cfg);
936                 arch_emit_epilogue (cfg);               
937
938                 method->addr = cfg->start;
939
940                 mono_compute_branches (cfg);
941                 
942                 if (mono_jit_dump_asm) {
943                         char *id = g_strdup_printf ("%s.%s_%s", method->klass->name_space,
944                                                     method->klass->name, method->name);
945                         mono_disassemble_code (cfg->start, cfg->code - cfg->start, id);
946                         g_free (id);
947                 }
948                 if (mono_debug_handle)
949                         mono_debug_add_method (mono_debug_handle, cfg);
950
951                 ji->code_size = cfg->code - cfg->start;
952                 ji->used_regs = cfg->rs->used_mask;
953                 ji->method = method;
954                 ji->code_start = method->addr;
955                 mono_jit_info_table_add (mono_jit_info_table, ji);
956
957                 if (header->num_clauses) {
958                         int i, start_block, end_block;
959
960                         ji->num_clauses = header->num_clauses;
961                         ji->clauses = g_new0 (MonoJitExceptionInfo, header->num_clauses);
962
963                         for (i = 0; i < header->num_clauses; i++) {
964                                 MonoExceptionClause *ec = &header->clauses [i];
965                                 MonoJitExceptionInfo *ei = &ji->clauses [i];
966                         
967                                 ei->flags = ec->flags;
968                                 ei->token_or_filter = ec->token_or_filter;
969
970                                 g_assert (cfg->bcinfo [ec->try_offset].is_block_start);
971                                 start_block = cfg->bcinfo [ec->try_offset].block_id;
972                                 end_block = cfg->bcinfo [ec->try_offset + ec->try_len].block_id;
973                                 g_assert (cfg->bcinfo [ec->try_offset + ec->try_len].is_block_start);
974                                 
975                                 ei->try_start = cfg->start + cfg->bblocks [start_block].addr;
976                                 ei->try_end = cfg->start + cfg->bblocks [end_block].addr;
977                                 
978                                 g_assert (cfg->bcinfo [ec->handler_offset].is_block_start);
979                                 start_block = cfg->bcinfo [ec->handler_offset].block_id;
980                                 ei->handler_start = cfg->start + cfg->bblocks [start_block].addr;       
981                                 
982                                 //printf ("TEST %x %x %x\n", ei->try_start, ei->try_end, ei->handler_start);
983                         }
984                 }
985                 
986                 mono_regset_free (cfg->rs);
987
988                 mono_cfg_free (cfg);
989
990                 mono_mempool_destroy (mp);
991
992         }
993
994         if (mono_jit_trace_calls || mono_jit_dump_asm || mono_jit_dump_forest) {
995                 printf ("END JIT compilation of %s.%s:%s %p %p\n", method->klass->name_space,
996                         method->klass->name, method->name, method, method->addr);
997         }
998
999
1000         return method->addr;
1001 }
1002
1003 /*
1004  * arch_get_restore_context:
1005  *
1006  * Returns a pointer to a method which restores a previously saved sigcontext.
1007  */
1008 static gpointer
1009 arch_get_restore_context ()
1010 {
1011         static guint8 *start = NULL;
1012         guint8 *code;
1013
1014         if (start)
1015                 return start;
1016
1017         /* restore_contect (struct sigcontext *ctx) */
1018         /* we do not restore X86_EAX, X86_EDX */
1019
1020         start = code = malloc (1024);
1021         
1022         /* load ctx */
1023         x86_mov_reg_membase (code, X86_EAX, X86_ESP, 4, 4);
1024
1025         /* get return address, stored in EDX */
1026         x86_mov_reg_membase (code, X86_EDX, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, eip), 4);
1027
1028         /* restore EBX */
1029         x86_mov_reg_membase (code, X86_EBX, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, ebx), 4);
1030         /* restore EDI */
1031         x86_mov_reg_membase (code, X86_EDI, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, edi), 4);
1032         /* restore ESI */
1033         x86_mov_reg_membase (code, X86_ESI, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, esi), 4);
1034         /* restore ESP */
1035         x86_mov_reg_membase (code, X86_ESP, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, esp), 4);
1036         /* restore EBP */
1037         x86_mov_reg_membase (code, X86_EBP, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, ebp), 4);
1038         /* restore ECX. the exception object is passed here to the catch handler */
1039         x86_mov_reg_membase (code, X86_ECX, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, ecx), 4);
1040
1041         /* jump to the saved IP */
1042         x86_jump_reg (code, X86_EDX);
1043
1044         return start;
1045 }
1046
1047 /*
1048  * arch_get_call_finally:
1049  *
1050  * Returns a pointer to a method which calls a finally handler.
1051  */
1052 static gpointer
1053 arch_get_call_finally ()
1054 {
1055         static guint8 *start = NULL;
1056         guint8 *code;
1057
1058         if (start)
1059                 return start;
1060
1061         /* call_finally (struct sigcontext *ctx, unsigned long eip) */
1062         start = code = malloc (1024);
1063
1064         x86_push_reg (code, X86_EBP);
1065         x86_mov_reg_reg (code, X86_EBP, X86_ESP, 4);
1066         x86_push_reg (code, X86_EBX);
1067         x86_push_reg (code, X86_EDI);
1068         x86_push_reg (code, X86_ESI);
1069
1070         /* load ctx */
1071         x86_mov_reg_membase (code, X86_EAX, X86_EBP, 8, 4);
1072         /* load eip */
1073         x86_mov_reg_membase (code, X86_ECX, X86_EBP, 12, 4);
1074         /* save EBP */
1075         x86_push_reg (code, X86_EBP);
1076         /* set new EBP */
1077         x86_mov_reg_membase (code, X86_EBP, X86_EAX,  G_STRUCT_OFFSET (struct sigcontext, ebp), 4);
1078         /* call the handler */
1079         x86_call_reg (code, X86_ECX);
1080         /* restore EBP */
1081         x86_pop_reg (code, X86_EBP);
1082         /* restore saved regs */
1083         x86_pop_reg (code, X86_ESI);
1084         x86_pop_reg (code, X86_EDI);
1085         x86_pop_reg (code, X86_EBX);
1086         x86_leave (code);
1087         x86_ret (code);
1088
1089         return start;
1090 }
1091
1092 /**
1093  * arch_handle_exception:
1094  * @ctx: saved processor state
1095  * @obj:
1096  */
1097 void
1098 arch_handle_exception (struct sigcontext *ctx, gpointer obj)
1099 {
1100         MonoJitInfo *ji;
1101         gpointer ip = (gpointer)ctx->eip;
1102         static void (*restore_context) (struct sigcontext *);
1103         static void (*call_finally) (struct sigcontext *, unsigned long);
1104        
1105         g_assert (ctx != NULL);
1106         g_assert (obj != NULL);
1107
1108         ji = mono_jit_info_table_find (mono_jit_info_table, ip);
1109
1110         if (!restore_context)
1111                 restore_context = arch_get_restore_context ();
1112         
1113         if (!call_finally)
1114                 call_finally = arch_get_call_finally ();
1115
1116         if (ji) { /* we are inside managed code */
1117                 MonoMethod *m = ji->method;
1118                 unsigned next_bp;
1119                 int offset = 2;
1120
1121                 if (ji->num_clauses) {
1122                         int i;
1123
1124                         g_assert (ji->clauses);
1125                         
1126                         for (i = 0; i < ji->num_clauses; i++) {
1127                                 MonoJitExceptionInfo *ei = &ji->clauses [i];
1128
1129                                 if (ei->try_start <= ip && ip <= (ei->try_end)) { 
1130                                         /* catch block */
1131                                         if (ei->flags == 0 && mono_object_isinst (obj, 
1132                                                 mono_class_get (m->klass->image, ei->token_or_filter))) {
1133                                         
1134                                                 ctx->eip = (unsigned long)ei->handler_start;
1135                                                 ctx->ecx = (unsigned long)obj;
1136                                                 restore_context (ctx);
1137                                                 g_assert_not_reached ();
1138                                         }
1139                                 }
1140                         }
1141
1142                         /* no handler found - we need to call all finally handlers */
1143                         for (i = 0; i < ji->num_clauses; i++) {
1144                                 MonoJitExceptionInfo *ei = &ji->clauses [i];
1145
1146                                 if (ei->try_start <= ip && ip < (ei->try_end) &&
1147                                     (ei->flags & MONO_EXCEPTION_CLAUSE_FINALLY)) {
1148                                         call_finally (ctx, (unsigned long)ei->handler_start);
1149                                 }
1150                         }
1151                 }
1152
1153                 if (mono_object_isinst (obj, mono_defaults.exception_class)) {
1154                         char  *strace = mono_string_to_utf8 (((MonoException*)obj)->stack_trace);
1155                         char  *tmp;
1156
1157                         if (!strcmp (strace, "TODO: implement stack traces")){
1158                                 g_free (strace);
1159                                 strace = g_strdup ("");
1160                         }
1161
1162                         tmp = g_strdup_printf ("%sin %s.%s:%s ()\n", strace, m->klass->name_space,  
1163                                                m->klass->name, m->name);
1164
1165                         g_free (strace);
1166
1167                         ((MonoException*)obj)->stack_trace = mono_string_new (tmp);
1168                         g_free (tmp);
1169                 }
1170
1171                 /* continue unwinding */
1172
1173                 /* restore caller saved registers */
1174                 if (ji->used_regs & X86_ESI_MASK) {
1175                         ctx->esi = *((int *)ctx->ebp + offset);
1176                         offset++;
1177                 }
1178                 if (ji->used_regs & X86_EDI_MASK) {
1179                         ctx->edi = *((int *)ctx->ebp + offset);
1180                         offset++;
1181                 }
1182                 if (ji->used_regs & X86_EBX_MASK) {
1183                         ctx->ebx = *((int *)ctx->ebp + offset);
1184                 }
1185
1186                 ctx->esp = ctx->ebp;
1187                 ctx->eip = *((int *)ctx->ebp + 1);
1188                 ctx->ebp = *((int *)ctx->ebp);
1189                 
1190                 if (next_bp < (unsigned)mono_end_of_stack)
1191                         arch_handle_exception (ctx, obj);
1192                 else
1193                         mono_jit_abort (obj);
1194
1195         } else {
1196                 gpointer *lmf_addr = TlsGetValue (lmf_thread_id);
1197                 MonoLMF *lmf;
1198                 MonoMethod *m;
1199
1200                 g_assert (lmf_addr);
1201                 lmf = *((MonoLMF **)lmf_addr);
1202
1203                 if (!lmf)
1204                         mono_jit_abort (obj);
1205
1206                 m = lmf->method;
1207
1208                 *lmf_addr = lmf->previous_lmf;
1209
1210                 ctx->esi = lmf->esi;
1211                 ctx->edi = lmf->edi;
1212                 ctx->ebx = lmf->ebx;
1213                 ctx->ebp = lmf->ebp;
1214                 ctx->eip = lmf->eip;
1215                 ctx->esp = (unsigned long)lmf;
1216
1217                 if (mono_object_isinst (obj, mono_defaults.exception_class)) {
1218                         char  *strace = mono_string_to_utf8 (((MonoException*)obj)->stack_trace);
1219                         char  *tmp;
1220
1221                         if (!strcmp (strace, "TODO: implement stack traces"))
1222                                 strace = g_strdup ("");
1223
1224                         tmp = g_strdup_printf ("%sin (unmanaged) %s.%s:%s ()\n", strace, m->klass->name_space,  
1225                                                m->klass->name, m->name);
1226
1227                         g_free (strace);
1228
1229                         ((MonoException*)obj)->stack_trace = mono_string_new (tmp);
1230                         g_free (tmp);
1231                 }
1232
1233                 if (ctx->eip < (unsigned)mono_end_of_stack)
1234                         arch_handle_exception (ctx, obj);
1235                 else
1236                         mono_jit_abort (obj);
1237         }
1238
1239         g_assert_not_reached ();
1240 }
1241
1242 static void
1243 throw_exception (unsigned long eax, unsigned long ecx, unsigned long edx, unsigned long ebx,
1244                  unsigned long esi, unsigned long edi, unsigned long ebp, MonoObject *exc,
1245                  unsigned long eip,  unsigned long esp)
1246 {
1247         struct sigcontext ctx;
1248         
1249         ctx.esp = esp;
1250         ctx.eip = eip;
1251         ctx.ebp = ebp;
1252         ctx.edi = edi;
1253         ctx.esi = esi;
1254         ctx.ebx = ebx;
1255         ctx.edx = edx;
1256         ctx.ecx = ecx;
1257         ctx.eax = eax;
1258         
1259         arch_handle_exception (&ctx, exc);
1260
1261         g_assert_not_reached ();
1262 }
1263
1264 gpointer 
1265 arch_get_throw_exception (void)
1266 {
1267         static guint8 *start = NULL;
1268         guint8 *code;
1269
1270         if (start)
1271                 return start;
1272
1273         code = start = g_malloc (1024);
1274
1275         x86_push_reg (code, X86_ESP);
1276         x86_push_membase (code, X86_ESP, 4); /* IP */
1277         x86_push_membase (code, X86_ESP, 12); /* exception */
1278         x86_push_reg (code, X86_EBP);
1279         x86_push_reg (code, X86_EDI);
1280         x86_push_reg (code, X86_ESI);
1281         x86_push_reg (code, X86_EBX);
1282         x86_push_reg (code, X86_EDX);
1283         x86_push_reg (code, X86_ECX);
1284         x86_push_reg (code, X86_EAX);
1285         x86_call_code (code, throw_exception);
1286         /* we should never reach this breakpoint */
1287         x86_breakpoint (code);
1288
1289         return start;
1290 }
1291
1292
1293
1294