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