Thu May 1 15:28:21 CEST 2003 Paolo Molaro <lupus@ximian.com>
[mono.git] / mono / mini / mini.c
1 /*
2  * mini.c: The new Mono code generator.
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * (C) 2002 Ximian, Inc.
9  */
10
11 #include <config.h>
12 #include <signal.h>
13 #include <unistd.h>
14
15 #include <mono/metadata/assembly.h>
16 #include <mono/metadata/loader.h>
17 #include <mono/metadata/cil-coff.h>
18 #include <mono/metadata/tabledefs.h>
19 #include <mono/metadata/class.h>
20 #include <mono/metadata/object.h>
21 #include <mono/metadata/exception.h>
22 #include <mono/metadata/opcodes.h>
23 #include <mono/metadata/mono-endian.h>
24 #include <mono/metadata/tokentype.h>
25 #include <mono/metadata/tabledefs.h>
26 #include <mono/metadata/threads.h>
27 #include <mono/metadata/marshal.h>
28 #include <mono/metadata/socket-io.h>
29 #include <mono/metadata/appdomain.h>
30 #include <mono/metadata/debug-helpers.h>
31 #include <mono/io-layer/io-layer.h>
32 #include "mono/metadata/profiler.h"
33 #include <mono/metadata/profiler-private.h>
34 #include <mono/metadata/mono-config.h>
35 #include <mono/metadata/environment.h>
36 #include <mono/metadata/mono-debug.h>
37 #include <mono/metadata/mono-debug-debugger.h>
38
39 #include "mini.h"
40 #include <string.h>
41 #include <ctype.h>
42 #include "inssel.h"
43
44 #include "jit-icalls.c"
45
46 #define MONO_CHECK_THIS(ins) (cfg->method->signature->hasthis && (ins)->ssa_op == MONO_SSA_LOAD && (ins)->inst_left->inst_c0 == 0)
47
48 static gpointer mono_jit_compile_method (MonoMethod *method);
49
50 static void handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, 
51                           const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native);
52
53 static int mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
54                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
55                    guint inline_offset, gboolean is_virtual_call);
56
57 extern guint8 mono_burg_arity [];
58 /* helper methods signature */
59 static MonoMethodSignature *helper_sig_long_long_long = NULL;
60 static MonoMethodSignature *helper_sig_long_long_int = NULL;
61 static MonoMethodSignature *helper_sig_newarr = NULL;
62 static MonoMethodSignature *helper_sig_ldstr = NULL;
63 static MonoMethodSignature *helper_sig_domain_get = NULL;
64 static MonoMethodSignature *helper_sig_object_new = NULL;
65 static MonoMethodSignature *helper_sig_compile = NULL;
66 static MonoMethodSignature *helper_sig_compile_virt = NULL;
67 static MonoMethodSignature *helper_sig_obj_ptr = NULL;
68 static MonoMethodSignature *helper_sig_ptr_void = NULL;
69 static MonoMethodSignature *helper_sig_void_ptr = NULL;
70 static MonoMethodSignature *helper_sig_void_obj = NULL;
71 static MonoMethodSignature *helper_sig_void_ptr_ptr = NULL;
72 static MonoMethodSignature *helper_sig_void_ptr_ptr_ptr = NULL;
73 static MonoMethodSignature *helper_sig_ptr_ptr_ptr = NULL;
74 static MonoMethodSignature *helper_sig_ptr_obj = NULL;
75 static MonoMethodSignature *helper_sig_initobj = NULL;
76 static MonoMethodSignature *helper_sig_memcpy = NULL;
77 static MonoMethodSignature *helper_sig_memset = NULL;
78 static MonoMethodSignature *helper_sig_ulong_double = NULL;
79 static MonoMethodSignature *helper_sig_long_double = NULL;
80 static MonoMethodSignature *helper_sig_uint_double = NULL;
81 static MonoMethodSignature *helper_sig_int_double = NULL;
82 static MonoMethodSignature *helper_sig_stelem_ref = NULL;
83
84 static guint32 default_opt = MONO_OPT_PEEPHOLE;
85
86 guint32 mono_jit_tls_id = 0;
87 gboolean mono_jit_trace_calls = FALSE;
88 gboolean mono_break_on_exc = FALSE;
89 gboolean mono_compile_aot = FALSE;
90 gboolean mono_trace_coverage = FALSE;
91 gboolean mono_jit_profile = FALSE;
92 MonoDebugFormat mono_debug_format = MONO_DEBUG_FORMAT_NONE;
93
94 CRITICAL_SECTION *metadata_section = NULL;
95
96 static int mini_verbose = 0;
97
98 #ifdef MONO_USE_EXC_TABLES
99 static gboolean
100 mono_type_blittable (MonoType *type)
101 {
102         if (type->byref)
103                 return FALSE;
104
105         switch (type->type){
106         case MONO_TYPE_VOID:
107         case MONO_TYPE_I1:
108         case MONO_TYPE_U1:
109         case MONO_TYPE_I2:
110         case MONO_TYPE_U2:
111         case MONO_TYPE_I4:
112         case MONO_TYPE_U4:
113         case MONO_TYPE_I8:
114         case MONO_TYPE_U8:
115         case MONO_TYPE_R4:
116         case MONO_TYPE_R8:
117         case MONO_TYPE_I:
118         case MONO_TYPE_U:
119         case MONO_TYPE_OBJECT:
120                 return TRUE;
121         case MONO_TYPE_VALUETYPE:
122         case MONO_TYPE_CLASS:
123                 return type->data.klass->blittable;
124                 break;
125         default:
126                 break;
127         }
128
129         return FALSE;
130 }
131
132 gboolean
133 mono_method_blittable (MonoMethod *method)
134 {
135         MonoMethodSignature *sig;
136         int i;
137
138         if (!method->addr)
139                 return FALSE;
140
141         if (!mono_arch_has_unwind_info (method->addr)) {
142                 return FALSE;
143         }
144
145         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
146                 return TRUE;
147
148         sig = method->signature;
149
150         if (!mono_type_blittable (sig->ret))
151                 return FALSE;
152
153         for (i = 0; i < sig->param_count; i++)
154                 if (!mono_type_blittable (sig->params [i]))
155                         return FALSE;
156
157         return TRUE;
158 }
159 #endif
160
161 /* debug function */
162 static void
163 print_method_from_ip (void *ip)
164 {
165         MonoJitInfo *ji;
166         char *method;
167         
168         ji = mono_jit_info_table_find (mono_domain_get (), ip);
169         if (!ji) {
170                 g_print ("No method at %p\n", ip);
171                 return;
172         }
173         method = mono_method_full_name (ji->method, TRUE);
174         g_print ("IP at offset 0x%x of method %s (%p %p)\n", (char*)ip - (char*)ji->code_start, method, ji->code_start, (char*)ji->code_start + ji->code_size);
175         g_free (method);
176
177 }
178
179 #define MONO_INIT_VARINFO(vi,id) do { \
180         (vi)->range.first_use.pos.bid = 0xffff; \
181         (vi)->reg = -1; \
182         (vi)->idx = (id); \
183 } while (0)
184
185 /*
186  * Basic blocks have two numeric identifiers:
187  * dfn: Depth First Number
188  * block_num: unique ID assigned at bblock creation
189  */
190 #define NEW_BBLOCK(cfg) (mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock)))
191 #define ADD_BBLOCK(cfg,bbhash,b) do {   \
192                 g_hash_table_insert (bbhash, (b)->cil_code, (b));       \
193                 (b)->block_num = cfg->num_bblocks++;    \
194                 (b)->real_offset = real_offset; \
195         } while (0)
196
197 #define GET_BBLOCK(cfg,bbhash,tblock,ip) do {   \
198                 (tblock) = g_hash_table_lookup (bbhash, (ip));  \
199                 if (!(tblock)) {        \
200                         if ((ip) >= end || (ip) < header->code) goto unverified; \
201                         (tblock) = NEW_BBLOCK (cfg);    \
202                         (tblock)->cil_code = (ip);      \
203                         ADD_BBLOCK (cfg, (bbhash), (tblock));   \
204                 }       \
205                 (tblock)->real_offset = real_offset; \
206         } while (0)
207
208 #define CHECK_BBLOCK(target,ip,tblock) do {     \
209                 if ((target) < (ip) && !(tblock)->code) {       \
210                         bb_recheck = g_list_prepend (bb_recheck, (tblock));     \
211                         if (cfg->verbose_level > 2) g_print ("queued block %d for check at IL%04x from IL%04x\n", (tblock)->block_num, (target) - header->code, (ip) - header->code);   \
212                 }       \
213         } while (0)
214
215 #define NEW_ICONST(cfg,dest,val) do {   \
216                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
217                 (dest)->opcode = OP_ICONST;     \
218                 (dest)->inst_c0 = (val);        \
219                 (dest)->type = STACK_I4;        \
220         } while (0)
221
222 /* FIXME: have a different definition of NEW_PCONST for 64 bit systems */
223 #define NEW_PCONST(cfg,dest,val) do {   \
224                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
225                 (dest)->opcode = OP_ICONST;     \
226                 (dest)->inst_p0 = (val);        \
227                 (dest)->type = STACK_PTR;       \
228         } while (0)
229
230 #define NEW_CLASSCONST(cfg,dest,val) do {       \
231                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
232                 (dest)->opcode = mono_compile_aot ? OP_AOTCONST : OP_ICONST;    \
233                 (dest)->inst_p0 = (val);        \
234                 (dest)->inst_i1 = (gpointer)MONO_PATCH_INFO_CLASS; \
235                 (dest)->type = STACK_PTR;       \
236         } while (0)
237
238 #define NEW_IMAGECONST(cfg,dest,val) do {       \
239                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
240                 (dest)->opcode = mono_compile_aot ? OP_AOTCONST : OP_ICONST;    \
241                 (dest)->inst_p0 = (val);        \
242                 (dest)->inst_i1 = (gpointer)MONO_PATCH_INFO_IMAGE; \
243                 (dest)->type = STACK_PTR;       \
244         } while (0)
245
246 #define NEW_FIELDCONST(cfg,dest,field) do {     \
247                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
248                 (dest)->opcode = mono_compile_aot ? OP_AOTCONST : OP_ICONST;    \
249                 (dest)->inst_p0 = (field);      \
250                 (dest)->inst_i1 = (gpointer)MONO_PATCH_INFO_FIELD; \
251                 (dest)->type = STACK_PTR;       \
252         } while (0)
253
254 #define NEW_METHODCONST(cfg,dest,val) do {      \
255                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
256                 (dest)->opcode = mono_compile_aot ? OP_AOTCONST : OP_ICONST;    \
257                 (dest)->inst_p0 = (val);        \
258                 (dest)->inst_i1 = (gpointer)MONO_PATCH_INFO_METHODCONST; \
259                 (dest)->type = STACK_PTR;       \
260         } while (0)
261
262 #define NEW_DOMAINCONST(cfg,dest) do { \
263                if ((cfg->opt & MONO_OPT_SAHRED) || mono_compile_aot) { \
264                        NEW_TEMPLOAD (cfg, dest, mono_get_domainvar (cfg)->inst_c0); \
265                } else { \
266                        NEW_PCONST (cfg, dest, (cfg)->domain); \
267                } \
268         } while (0)
269
270 #define GET_VARINFO_INST(cfg,num) ((cfg)->varinfo [(num)]->inst)
271
272 #define NEW_ARGLOAD(cfg,dest,num) do {  \
273                 if (arg_array [(num)]->opcode == OP_ICONST) (dest) = arg_array [(num)]; else { \
274                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
275                 (dest)->ssa_op = MONO_SSA_LOAD; \
276                 (dest)->inst_i0 = arg_array [(num)];    \
277                 (dest)->opcode = mono_type_to_ldind ((dest)->inst_i0->inst_vtype);      \
278                 type_to_eval_stack_type (param_types [(num)], (dest));  \
279                 (dest)->klass = (dest)->inst_i0->klass; \
280         }} while (0)
281
282 #define NEW_LOCLOAD(cfg,dest,num) do {  \
283                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
284                 (dest)->ssa_op = MONO_SSA_LOAD; \
285                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
286                 (dest)->opcode = mono_type_to_ldind ((dest)->inst_i0->inst_vtype);      \
287                 type_to_eval_stack_type (header->locals [(num)], (dest));       \
288                 (dest)->klass = (dest)->inst_i0->klass; \
289         } while (0)
290
291 #define NEW_LOCLOADA(cfg,dest,num) do { \
292                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
293                 (dest)->ssa_op = MONO_SSA_MAYBE_LOAD;   \
294                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
295                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
296                 (dest)->opcode = OP_LDADDR;     \
297                 (dest)->type = STACK_MP;        \
298                 (dest)->klass = (dest)->inst_i0->klass; \
299                 (cfg)->disable_ssa = TRUE; \
300         } while (0)
301
302 #define NEW_RETLOADA(cfg,dest) do {     \
303                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
304                 (dest)->ssa_op = MONO_SSA_MAYBE_LOAD;   \
305                 (dest)->inst_i0 = (cfg)->ret;   \
306                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
307                 (dest)->opcode = CEE_LDIND_I;   \
308                 (dest)->type = STACK_MP;        \
309                 (dest)->klass = (dest)->inst_i0->klass; \
310                 (cfg)->disable_ssa = TRUE; \
311         } while (0)
312
313 #define NEW_ARGLOADA(cfg,dest,num) do { \
314                 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
315                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
316                 (dest)->ssa_op = MONO_SSA_MAYBE_LOAD;   \
317                 (dest)->inst_i0 = arg_array [(num)];    \
318                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
319                 (dest)->opcode = OP_LDADDR;     \
320                 (dest)->type = STACK_MP;        \
321                 (dest)->klass = (dest)->inst_i0->klass; \
322                 (cfg)->disable_ssa = TRUE; \
323         } while (0)
324
325 #define NEW_TEMPLOAD(cfg,dest,num) do { \
326                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
327                 (dest)->ssa_op = MONO_SSA_LOAD; \
328                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
329                 (dest)->opcode = mono_type_to_ldind ((dest)->inst_i0->inst_vtype);      \
330                 type_to_eval_stack_type ((dest)->inst_i0->inst_vtype, (dest));  \
331                 (dest)->klass = (dest)->inst_i0->klass; \
332         } while (0)
333
334 #define NEW_TEMPLOADA(cfg,dest,num) do {        \
335                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
336                 (dest)->ssa_op = MONO_SSA_MAYBE_LOAD;   \
337                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
338                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
339                 (dest)->opcode = OP_LDADDR;     \
340                 (dest)->type = STACK_MP;        \
341                 (dest)->klass = (dest)->inst_i0->klass; \
342                 (cfg)->disable_ssa = TRUE; \
343         } while (0)
344
345
346 #define NEW_INDLOAD(cfg,dest,addr,vtype) do {   \
347                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
348                 (dest)->inst_left = addr;       \
349                 (dest)->opcode = mono_type_to_ldind (vtype);    \
350                 type_to_eval_stack_type (vtype, (dest));        \
351                 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/     \
352         } while (0)
353
354 #define NEW_INDSTORE(cfg,dest,addr,value,vtype) do {    \
355                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
356                 (dest)->inst_i0 = addr; \
357                 (dest)->opcode = mono_type_to_stind (vtype);    \
358                 (dest)->inst_i1 = (value);      \
359                 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/     \
360         } while (0)
361
362 #define NEW_TEMPSTORE(cfg,dest,num,inst) do {   \
363                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
364                 (dest)->ssa_op = MONO_SSA_STORE;        \
365                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
366                 (dest)->opcode = mono_type_to_stind ((dest)->inst_i0->inst_vtype);      \
367                 (dest)->inst_i1 = (inst);       \
368                 (dest)->klass = (dest)->inst_i0->klass; \
369         } while (0)
370
371 #define NEW_LOCSTORE(cfg,dest,num,inst) do {    \
372                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
373                 (dest)->opcode = mono_type_to_stind (header->locals [(num)]);   \
374                 (dest)->ssa_op = MONO_SSA_STORE;        \
375                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
376                 (dest)->inst_i1 = (inst);       \
377                 (dest)->klass = (dest)->inst_i0->klass; \
378         } while (0)
379
380 #define NEW_ARGSTORE(cfg,dest,num,inst) do {    \
381                 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
382                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
383                 (dest)->opcode = mono_type_to_stind (param_types [(num)]);      \
384                 (dest)->ssa_op = MONO_SSA_STORE;        \
385                 (dest)->inst_i0 = arg_array [(num)];    \
386                 (dest)->inst_i1 = (inst);       \
387                 (dest)->klass = (dest)->inst_i0->klass; \
388         } while (0)
389
390 #define ADD_BINOP(op) do {      \
391                 MONO_INST_NEW (cfg, ins, (op)); \
392                 ins->cil_code = ip;     \
393                 sp -= 2;        \
394                 ins->inst_i0 = sp [0];  \
395                 ins->inst_i1 = sp [1];  \
396                 *sp++ = ins;    \
397                 type_from_op (ins);     \
398                 CHECK_TYPE (ins);       \
399         } while (0)
400
401 #define ADD_UNOP(op) do {       \
402                 MONO_INST_NEW (cfg, ins, (op)); \
403                 ins->cil_code = ip;     \
404                 sp--;   \
405                 ins->inst_i0 = sp [0];  \
406                 *sp++ = ins;    \
407                 type_from_op (ins);     \
408                 CHECK_TYPE (ins);       \
409         } while (0)
410
411 #define ADD_BINCOND(next_block) do {    \
412                 MonoInst *cmp;  \
413                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
414                 sp -= 2;                \
415                 cmp->inst_i0 = sp [0];  \
416                 cmp->inst_i1 = sp [1];  \
417                 cmp->cil_code = ins->cil_code;  \
418                 type_from_op (cmp);     \
419                 CHECK_TYPE (cmp);       \
420                 ins->inst_i0 = cmp;     \
421                 MONO_ADD_INS (bblock, ins);     \
422                 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);      \
423                 GET_BBLOCK (cfg, bbhash, tblock, target);               \
424                 link_bblock (cfg, bblock, tblock);      \
425                 ins->inst_true_bb = tblock;     \
426                 CHECK_BBLOCK (target, ip, tblock);      \
427                 if ((next_block)) {     \
428                         link_bblock (cfg, bblock, (next_block));        \
429                         ins->inst_false_bb = (next_block);      \
430                         start_new_bblock = 1;   \
431                 } else {        \
432                         GET_BBLOCK (cfg, bbhash, tblock, ip);           \
433                         link_bblock (cfg, bblock, tblock);      \
434                         ins->inst_false_bb = tblock;    \
435                         start_new_bblock = 2;   \
436                 }       \
437         } while (0)
438
439 /* FIXME: handle float, long ... */
440 #define ADD_UNCOND(istrue) do { \
441                 MonoInst *cmp;  \
442                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
443                 sp--;           \
444                 cmp->inst_i0 = sp [0];  \
445                 switch (cmp->inst_i0->type) { \
446                 case STACK_I8: \
447                         cmp->inst_i1 = zero_int64; break; \
448                 case STACK_R8: \
449                         cmp->inst_i1 = zero_r8; break; \
450                 case STACK_PTR: \
451                 case STACK_MP: \
452                         cmp->inst_i1 = zero_ptr; break; \
453                 case STACK_OBJ: \
454                         cmp->inst_i1 = zero_obj; break; \
455                 default: \
456                         cmp->inst_i1 = zero_int32;  \
457                 }  \
458                 cmp->cil_code = ins->cil_code;  \
459                 type_from_op (cmp);     \
460                 CHECK_TYPE (cmp);       \
461                 ins->inst_i0 = cmp;     \
462                 ins->opcode = (istrue)? CEE_BNE_UN: CEE_BEQ;    \
463                 MONO_ADD_INS (bblock, ins);     \
464                 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);      \
465                 GET_BBLOCK (cfg, bbhash, tblock, target);               \
466                 link_bblock (cfg, bblock, tblock);      \
467                 ins->inst_true_bb = tblock;     \
468                 CHECK_BBLOCK (target, ip, tblock);      \
469                 GET_BBLOCK (cfg, bbhash, tblock, ip);           \
470                 link_bblock (cfg, bblock, tblock);      \
471                 ins->inst_false_bb = tblock;    \
472                 start_new_bblock = 2;   \
473         } while (0)
474
475 #define NEW_LDELEMA(cfg,dest,sp,k) do { \
476                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
477                 (dest)->opcode = CEE_LDELEMA;   \
478                 (dest)->inst_left = (sp) [0];   \
479                 (dest)->inst_right = (sp) [1];  \
480                 (dest)->type = STACK_MP;        \
481                 (dest)->klass = (k);    \
482         } while (0)
483
484 #define NEW_GROUP(cfg,dest,el1,el2) do {        \
485                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
486                 (dest)->opcode = OP_GROUP;      \
487                 (dest)->inst_left = (el1);      \
488                 (dest)->inst_right = (el2);     \
489         } while (0)
490
491 static GHashTable *coverage_hash = NULL;
492
493 MonoCoverageInfo *
494 mono_allocate_coverage_info (MonoMethod *method, int size)
495 {
496         MonoCoverageInfo *res;
497
498         if (!coverage_hash)
499                 coverage_hash = g_hash_table_new (NULL, NULL);
500
501         res = g_malloc0 (sizeof (MonoCoverageInfo) + sizeof (int) * size * 2);
502
503         res->entries = size;
504
505         g_hash_table_insert (coverage_hash, method, res);
506
507         return res;
508 }
509
510 MonoCoverageInfo *
511 mono_get_coverage_info (MonoMethod *method)
512 {
513         if (!coverage_hash)
514                 return NULL;
515
516         return g_hash_table_lookup (coverage_hash, method);
517 }
518                 
519 #if 0
520 static gint
521 compare_bblock (gconstpointer a, gconstpointer b)
522 {
523         const MonoBasicBlock *b1 = a;
524         const MonoBasicBlock *b2 = b;
525
526         return b2->cil_code - b1->cil_code;
527 }
528 #endif
529
530 /* *
531  * link_bblock: Links two basic blocks
532  *
533  * links two basic blocks in the control flow graph, the 'from'
534  * argument is the starting block and the 'to' argument is the block
535  * the control flow ends to after 'from'.
536  */
537 static void
538 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
539 {
540         MonoBasicBlock **newa;
541         int i, found;
542
543 #if 0
544         if (from->cil_code) {
545                 if (to->cil_code)
546                         g_print ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
547                 else
548                         g_print ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
549         } else {
550                 if (to->cil_code)
551                         g_print ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
552                 else
553                         g_print ("edge from entry to exit\n");
554         }
555 #endif
556         found = FALSE;
557         for (i = 0; i < from->out_count; ++i) {
558                 if (to == from->out_bb [i]) {
559                         found = TRUE;
560                         break;
561                 }
562         }
563         if (!found) {
564                 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
565                 for (i = 0; i < from->out_count; ++i) {
566                         newa [i] = from->out_bb [i];
567                 }
568                 newa [i] = to;
569                 from->out_count++;
570                 from->out_bb = newa;
571         }
572
573         found = FALSE;
574         for (i = 0; i < to->in_count; ++i) {
575                 if (from == to->in_bb [i]) {
576                         found = TRUE;
577                         break;
578                 }
579         }
580         if (!found) {
581                 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
582                 for (i = 0; i < to->in_count; ++i) {
583                         newa [i] = to->in_bb [i];
584                 }
585                 newa [i] = from;
586                 to->in_count++;
587                 to->in_bb = newa;
588         }
589 }
590
591 /*
592  * We mark each basic block with a region ID. We use that to avoid BB
593  * optimizations when blocks are in different regions. 
594  */
595 static int
596 mono_find_block_region (MonoCompile *cfg, int offset, int *filter_lengths)
597 {
598         MonoMethod *method = cfg->method;
599         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
600         MonoExceptionClause *clause;
601         int i;
602
603         /* first search for handlers and filters */
604         for (i = 0; i < header->num_clauses; ++i) {
605                 clause = &header->clauses [i];
606                 if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->token_or_filter) &&
607                     (offset < (clause->token_or_filter + filter_lengths [i])))
608                         return (i << 8) | 128 | clause->flags;
609                            
610                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
611                         return (i << 8) | 64 | clause->flags;
612                 }
613         }
614
615         /* search the try blocks */
616         for (i = 0; i < header->num_clauses; ++i) {
617                 clause = &header->clauses [i];
618                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
619                         return (i << 8) | clause->flags;
620         }
621
622         return -1;
623 }
624
625 static GList*
626 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
627 {
628         MonoMethod *method = cfg->method;
629         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
630         MonoExceptionClause *clause;
631         MonoBasicBlock *handler;
632         int i;
633         GList *res = NULL;
634
635         for (i = 0; i < header->num_clauses; ++i) {
636                 clause = &header->clauses [i];
637                 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) && 
638                     (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
639                         if (clause->flags == type) {
640                                 handler = g_hash_table_lookup (cfg->bb_hash, header->code + clause->handler_offset);
641                                 g_assert (handler);
642                                 res = g_list_append (res, handler);
643                         }
644                 }
645         }
646         return res;
647 }
648
649
650 static void
651 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
652 {
653         int i;
654
655         array [*dfn] = start;
656         /*g_print ("visit %d at %p\n", *dfn, start->cil_code);*/
657         for (i = 0; i < start->out_count; ++i) {
658                 if (start->out_bb [i]->dfn)
659                         continue;
660                 (*dfn)++;
661                 start->out_bb [i]->dfn = *dfn;
662                 start->out_bb [i]->df_parent = start;
663                 array [*dfn] = start->out_bb [i];
664                 df_visit (start->out_bb [i], dfn, array);
665         }
666 }
667
668 typedef struct {
669         const guchar *code;
670         MonoBasicBlock *best;
671 } PrevStruct;
672
673 static void
674 previous_foreach (gconstpointer key, gpointer val, gpointer data)
675 {
676         PrevStruct *p = data;
677         MonoBasicBlock *bb = val;
678         //printf ("FIDPREV %d %p  %p %p %p %p %d %d %d\n", bb->block_num, p->code, bb, p->best, bb->cil_code, p->best->cil_code,
679         //bb->method == p->best->method, bb->cil_code < p->code, bb->cil_code > p->best->cil_code);
680
681         if (bb->cil_code && bb->cil_code < p->code && bb->cil_code > p->best->cil_code)
682                 p->best = bb;
683 }
684
685 static MonoBasicBlock*
686 find_previous (GHashTable *bb_hash, MonoBasicBlock *start, const guchar *code) {
687         PrevStruct p;
688
689         p.code = code;
690         p.best = start;
691
692         g_hash_table_foreach (bb_hash, (GHFunc)previous_foreach, &p);
693         return p.best;
694 }
695
696 static void
697 split_bblock (MonoCompile *cfg, MonoBasicBlock *first, MonoBasicBlock *second) {
698         int i, j;
699         MonoInst *inst;
700         MonoBasicBlock *bb;
701
702         if (second->code)
703                 return;
704         
705         /* 
706          * FIXME: take into account all the details:
707          * second may have been the target of more than one bblock
708          */
709         second->out_count = first->out_count;
710         second->out_bb = first->out_bb;
711
712         for (i = 0; i < first->out_count; ++i) {
713                 bb = first->out_bb [i];
714                 for (j = 0; j < bb->in_count; ++j) {
715                         if (bb->in_bb [j] == first)
716                                 bb->in_bb [j] = second;
717                 }
718         }
719
720         first->out_count = 0;
721         first->out_bb = NULL;
722         link_bblock (cfg, first, second);
723
724         second->last_ins = first->last_ins;
725
726         /*g_print ("start search at %p for %p\n", first->cil_code, second->cil_code);*/
727         for (inst = first->code; inst && inst->next; inst = inst->next) {
728                 /*char *code = mono_disasm_code_one (NULL, cfg->method, inst->next->cil_code, NULL);
729                 g_print ("found %p: %s", inst->next->cil_code, code);
730                 g_free (code);*/
731                 if (inst->cil_code < second->cil_code && inst->next->cil_code >= second->cil_code) {
732                         second->code = inst->next;
733                         inst->next = NULL;
734                         first->last_ins = inst;
735                         second->next_bb = first->next_bb;
736                         first->next_bb = second;
737                         return;
738                 }
739         }
740         if (!second->code) {
741                 g_warning ("bblock split failed in %s::%s\n", cfg->method->klass->name, cfg->method->name);
742                 //G_BREAKPOINT ();
743         }
744 }
745
746 guint
747 mono_type_to_ldind (MonoType *type)
748 {
749         int t = type->type;
750
751         if (type->byref)
752                 return CEE_LDIND_I;
753
754 handle_enum:
755         switch (t) {
756         case MONO_TYPE_I1:
757                 return CEE_LDIND_I1;
758         case MONO_TYPE_U1:
759         case MONO_TYPE_BOOLEAN:
760                 return CEE_LDIND_U1;
761         case MONO_TYPE_I2:
762                 return CEE_LDIND_I2;
763         case MONO_TYPE_U2:
764         case MONO_TYPE_CHAR:
765                 return CEE_LDIND_U2;
766         case MONO_TYPE_I4:
767                 return CEE_LDIND_I4;
768         case MONO_TYPE_U4:
769                 return CEE_LDIND_U4;
770         case MONO_TYPE_I:
771         case MONO_TYPE_U:
772         case MONO_TYPE_PTR:
773         case MONO_TYPE_FNPTR:
774                 return CEE_LDIND_I;
775         case MONO_TYPE_CLASS:
776         case MONO_TYPE_STRING:
777         case MONO_TYPE_OBJECT:
778         case MONO_TYPE_SZARRAY:
779         case MONO_TYPE_ARRAY:    
780                 return CEE_LDIND_REF;
781         case MONO_TYPE_I8:
782         case MONO_TYPE_U8:
783                 return CEE_LDIND_I8;
784         case MONO_TYPE_R4:
785                 return CEE_LDIND_R4;
786         case MONO_TYPE_R8:
787                 return CEE_LDIND_R8;
788         case MONO_TYPE_VALUETYPE:
789                 if (type->data.klass->enumtype) {
790                         t = type->data.klass->enum_basetype->type;
791                         goto handle_enum;
792                 }
793                 return CEE_LDOBJ;
794         default:
795                 g_error ("unknown type 0x%02x in type_to_ldind", type->type);
796         }
797         return -1;
798 }
799
800 guint
801 mono_type_to_stind (MonoType *type)
802 {
803         int t = type->type;
804
805         if (type->byref)
806                 return CEE_STIND_I;
807
808 handle_enum:
809         switch (t) {
810         case MONO_TYPE_I1:
811         case MONO_TYPE_U1:
812         case MONO_TYPE_BOOLEAN:
813                 return CEE_STIND_I1;
814         case MONO_TYPE_I2:
815         case MONO_TYPE_U2:
816         case MONO_TYPE_CHAR:
817                 return CEE_STIND_I2;
818         case MONO_TYPE_I4:
819         case MONO_TYPE_U4:
820                 return CEE_STIND_I4;
821         case MONO_TYPE_I:
822         case MONO_TYPE_U:
823         case MONO_TYPE_PTR:
824         case MONO_TYPE_FNPTR:
825                 return CEE_STIND_I;
826         case MONO_TYPE_CLASS:
827         case MONO_TYPE_STRING:
828         case MONO_TYPE_OBJECT:
829         case MONO_TYPE_SZARRAY:
830         case MONO_TYPE_ARRAY:    
831                 return CEE_STIND_REF;
832         case MONO_TYPE_I8:
833         case MONO_TYPE_U8:
834                 return CEE_STIND_I8;
835         case MONO_TYPE_R4:
836                 return CEE_STIND_R4;
837         case MONO_TYPE_R8:
838                 return CEE_STIND_R8;
839         case MONO_TYPE_VALUETYPE:
840                 if (type->data.klass->enumtype) {
841                         t = type->data.klass->enum_basetype->type;
842                         goto handle_enum;
843                 }
844                 return CEE_STOBJ;
845                 /* fail right now */
846         default:
847                 g_error ("unknown type %02x in type_to_stind", type->type);
848         }
849         return -1;
850 }
851
852 /*
853  * Returns the type used in the eval stack when @type is loaded.
854  * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
855  */
856 static void
857 type_to_eval_stack_type (MonoType *type, MonoInst *inst) {
858         int t = type->type;
859
860         if (type->byref) {
861                 inst->type = STACK_MP;
862                 return;
863         }
864
865 handle_enum:
866         switch (t) {
867         case MONO_TYPE_I1:
868         case MONO_TYPE_U1:
869         case MONO_TYPE_BOOLEAN:
870         case MONO_TYPE_I2:
871         case MONO_TYPE_U2:
872         case MONO_TYPE_CHAR:
873         case MONO_TYPE_I4:
874         case MONO_TYPE_U4:
875                 inst->type = STACK_I4;
876                 return;
877         case MONO_TYPE_I:
878         case MONO_TYPE_U:
879         case MONO_TYPE_PTR:
880         case MONO_TYPE_FNPTR:
881                 inst->type = STACK_PTR;
882                 return;
883         case MONO_TYPE_CLASS:
884         case MONO_TYPE_STRING:
885         case MONO_TYPE_OBJECT:
886         case MONO_TYPE_SZARRAY:
887         case MONO_TYPE_ARRAY:    
888                 inst->type = STACK_OBJ;
889                 return;
890         case MONO_TYPE_I8:
891         case MONO_TYPE_U8:
892                 inst->type = STACK_I8;
893                 return;
894         case MONO_TYPE_R4:
895         case MONO_TYPE_R8:
896                 inst->type = STACK_R8;
897                 return;
898         case MONO_TYPE_VALUETYPE:
899                 if (type->data.klass->enumtype) {
900                         t = type->data.klass->enum_basetype->type;
901                         goto handle_enum;
902                 } else {
903                         inst->klass = type->data.klass;
904                         inst->type = STACK_VTYPE;
905                         return;
906                 }
907         default:
908                 g_error ("unknown type 0x%02x in eval stack type", type->type);
909         }
910 }
911
912 /*
913  * The following tables are used to quickly validate the IL code in type_from_op ().
914  */
915 static const char
916 bin_num_table [STACK_MAX] [STACK_MAX] = {
917         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
918         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
919         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
920         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
921         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8,  STACK_INV, STACK_INV, STACK_INV},
922         {STACK_INV, STACK_MP,  STACK_INV, STACK_MP,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
923         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
924         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
925 };
926
927 static const char 
928 neg_table [] = {
929         STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV
930 };
931
932 /* reduce the size of this table */
933 static const char
934 bin_int_table [STACK_MAX] [STACK_MAX] = {
935         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
936         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
937         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
938         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
939         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
940         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
941         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
942         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
943 };
944
945 static const char
946 bin_comp_table [STACK_MAX] [STACK_MAX] = {
947         {0},
948         {0, 1, 0, 1, 0, 0, 4, 0},
949         {0, 0, 1, 0, 0, 0, 0, 0},
950         {0, 1, 0, 1, 0, 2, 4, 0},
951         {0, 0, 0, 0, 1, 0, 0, 0},
952         {0, 0, 0, 2, 0, 1, 0, 0},
953         {0, 4, 0, 4, 0, 0, 3, 0},
954         {0, 0, 0, 0, 0, 0, 0, 0},
955 };
956
957 /* reduce the size of this table */
958 static const char
959 shift_table [STACK_MAX] [STACK_MAX] = {
960         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
961         {STACK_INV, STACK_I4,  STACK_INV, STACK_I4,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
962         {STACK_INV, STACK_I8,  STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
963         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
964         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
965         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
966         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
967         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
968 };
969
970 /*
971  * Tables to map from the non-specific opcode to the matching
972  * type-specific opcode.
973  */
974 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
975 static const guint16
976 binops_op_map [STACK_MAX] = {
977         0, 0, OP_LADD-CEE_ADD, OP_PADD-CEE_ADD, OP_FADD-CEE_ADD, 0
978 };
979
980 /* handles from CEE_NEG to CEE_CONV_U8 */
981 static const guint16
982 unops_op_map [STACK_MAX] = {
983         0, 0, OP_LNEG-CEE_NEG, OP_PNEG-CEE_NEG, OP_FNEG-CEE_NEG, 0
984 };
985
986 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
987 static const guint16
988 ovfops_op_map [STACK_MAX] = {
989         0, 0, OP_LCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, OP_FCONV_TO_U2-CEE_CONV_U2, 0
990 };
991
992 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
993 static const guint16
994 ovf2ops_op_map [STACK_MAX] = {
995         0, 0, OP_LCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_PCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_FCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, 0
996 };
997
998 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
999 static const guint16
1000 ovf3ops_op_map [STACK_MAX] = {
1001         0, 0, OP_LCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_PCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_FCONV_TO_OVF_I1-CEE_CONV_OVF_I1, 0
1002 };
1003
1004 /* handles from CEE_CEQ to CEE_CLT_UN */
1005 static const guint16
1006 ceqops_op_map [STACK_MAX] = {
1007         0, 0, OP_LCEQ-CEE_CEQ, OP_PCEQ-CEE_CEQ, OP_FCEQ-CEE_CEQ, 0
1008 };
1009
1010 /*
1011  * Sets ins->type (the type on the eval stack) according to the
1012  * type of the opcode and the arguments to it.
1013  * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
1014  *
1015  * FIXME: this function sets ins->type unconditionally in some cases, but
1016  * it should set it to invalid for some types (a conv.x on an object)
1017  */
1018 static void
1019 type_from_op (MonoInst *ins) {
1020         switch (ins->opcode) {
1021         /* binops */
1022         case CEE_ADD:
1023         case CEE_SUB:
1024         case CEE_MUL:
1025         case CEE_DIV:
1026         case CEE_REM:
1027                 /* FIXME: check unverifiable args for STACK_MP */
1028                 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1029                 ins->opcode += binops_op_map [ins->type];
1030                 return;
1031         case CEE_DIV_UN:
1032         case CEE_REM_UN:
1033         case CEE_AND:
1034         case CEE_OR:
1035         case CEE_XOR:
1036                 ins->type = bin_int_table [ins->inst_i0->type] [ins->inst_i1->type];
1037                 ins->opcode += binops_op_map [ins->type];
1038                 return;
1039         case CEE_SHL:
1040         case CEE_SHR:
1041         case CEE_SHR_UN:
1042                 ins->type = shift_table [ins->inst_i0->type] [ins->inst_i1->type];
1043                 ins->opcode += binops_op_map [ins->type];
1044                 return;
1045         case OP_COMPARE:
1046                 /* FIXME: handle some specifics with ins->next->type */
1047                 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1048                 return;
1049         case 256+CEE_CEQ:
1050         case 256+CEE_CGT:
1051         case 256+CEE_CGT_UN:
1052         case 256+CEE_CLT:
1053         case 256+CEE_CLT_UN:
1054                 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1055                 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1056                 return;
1057         /* unops */
1058         case CEE_NEG:
1059                 ins->type = neg_table [ins->inst_i0->type];
1060                 ins->opcode += unops_op_map [ins->type];
1061                 return;
1062         case CEE_NOT:
1063                 if (ins->inst_i0->type >= STACK_I4 && ins->inst_i0->type <= STACK_PTR)
1064                         ins->type = ins->inst_i0->type;
1065                 else
1066                         ins->type = STACK_INV;
1067                 ins->opcode += unops_op_map [ins->type];
1068                 return;
1069         case CEE_CONV_I1:
1070         case CEE_CONV_I2:
1071         case CEE_CONV_I4:
1072         case CEE_CONV_U4:
1073                 ins->type = STACK_I4;
1074                 ins->opcode += unops_op_map [ins->inst_i0->type];
1075                 return;
1076         case CEE_CONV_R_UN:
1077                 ins->type = STACK_R8;
1078                 switch (ins->inst_i0->type) {
1079                 case STACK_I4:
1080                 case STACK_PTR:
1081                         break;
1082                 case STACK_I8:
1083                         ins->opcode = OP_LCONV_TO_R_UN; 
1084                         break;
1085                 }
1086                 return;
1087         case CEE_CONV_OVF_I1:
1088         case CEE_CONV_OVF_U1:
1089         case CEE_CONV_OVF_I2:
1090         case CEE_CONV_OVF_U2:
1091         case CEE_CONV_OVF_I4:
1092         case CEE_CONV_OVF_U4:
1093                 ins->type = STACK_I4;
1094                 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1095                 return;
1096         case CEE_CONV_OVF_I_UN:
1097         case CEE_CONV_OVF_U_UN:
1098                 ins->type = STACK_PTR;
1099                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1100                 return;
1101         case CEE_CONV_OVF_I1_UN:
1102         case CEE_CONV_OVF_I2_UN:
1103         case CEE_CONV_OVF_I4_UN:
1104         case CEE_CONV_OVF_U1_UN:
1105         case CEE_CONV_OVF_U2_UN:
1106         case CEE_CONV_OVF_U4_UN:
1107                 ins->type = STACK_I4;
1108                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1109                 return;
1110         case CEE_CONV_U:
1111                 ins->type = STACK_PTR;
1112                 switch (ins->inst_i0->type) {
1113                 case STACK_I4:
1114                 case STACK_PTR:
1115                 case STACK_MP:
1116                         break;
1117                 case STACK_I8:
1118                         ins->opcode = OP_LCONV_TO_U;
1119                         break;
1120                 case STACK_R8:
1121                         ins->opcode = OP_FCONV_TO_U;
1122                         break;
1123                 }
1124                 return;
1125         case CEE_CONV_I8:
1126         case CEE_CONV_U8:
1127                 ins->type = STACK_I8;
1128                 ins->opcode += unops_op_map [ins->inst_i0->type];
1129                 return;
1130         case CEE_CONV_OVF_I8:
1131         case CEE_CONV_OVF_U8:
1132                 ins->type = STACK_I8;
1133                 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1134                 return;
1135         case CEE_CONV_OVF_U8_UN:
1136         case CEE_CONV_OVF_I8_UN:
1137                 ins->type = STACK_I8;
1138                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1139                 return;
1140         case CEE_CONV_R4:
1141         case CEE_CONV_R8:
1142                 ins->type = STACK_R8;
1143                 ins->opcode += unops_op_map [ins->inst_i0->type];
1144                 return;
1145         case CEE_CKFINITE:
1146                 ins->type = STACK_R8;           
1147                 return;
1148         case CEE_CONV_U2:
1149         case CEE_CONV_U1:
1150                 ins->type = STACK_I4;
1151                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1152                 break;
1153         case CEE_CONV_I:
1154         case CEE_CONV_OVF_I:
1155         case CEE_CONV_OVF_U:
1156                 ins->type = STACK_PTR;
1157                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1158                 return;
1159         case CEE_ADD_OVF:
1160         case CEE_ADD_OVF_UN:
1161         case CEE_MUL_OVF:
1162         case CEE_MUL_OVF_UN:
1163         case CEE_SUB_OVF:
1164         case CEE_SUB_OVF_UN:
1165                 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1166                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1167                 return;
1168         default:
1169                 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1170                 break;
1171         }
1172 }
1173
1174 static const char 
1175 ldind_type [] = {
1176         STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I8, STACK_MP, STACK_R8, STACK_R8, STACK_OBJ
1177 };
1178
1179 /* map ldelem.x to the matching ldind.x opcode */
1180 static const guchar
1181 ldelem_to_ldind [] = {
1182         CEE_LDIND_I1,
1183         CEE_LDIND_U1,
1184         CEE_LDIND_I2,
1185         CEE_LDIND_U2,
1186         CEE_LDIND_I4,
1187         CEE_LDIND_U4,
1188         CEE_LDIND_I8,
1189         CEE_LDIND_I,
1190         CEE_LDIND_R4,
1191         CEE_LDIND_R8,
1192         CEE_LDIND_REF
1193 };
1194
1195 /* map stelem.x to the matching stind.x opcode */
1196 static const guchar
1197 stelem_to_stind [] = {
1198         CEE_STIND_I,
1199         CEE_STIND_I1,
1200         CEE_STIND_I2,
1201         CEE_STIND_I4,
1202         CEE_STIND_I8,
1203         CEE_STIND_R4,
1204         CEE_STIND_R8,
1205         CEE_STIND_REF
1206 };
1207
1208 #if 0
1209
1210 static const char
1211 param_table [STACK_MAX] [STACK_MAX] = {
1212         {0},
1213 };
1214
1215 static int
1216 check_values_to_signature (MonoInst *args, MonoType *this, MonoMethodSignature *sig) {
1217         int i;
1218
1219         if (sig->hasthis) {
1220                 switch (args->type) {
1221                 case STACK_I4:
1222                 case STACK_I8:
1223                 case STACK_R8:
1224                 case STACK_VTYPE:
1225                 case STACK_INV:
1226                         return 0;
1227                 }
1228                 args++;
1229         }
1230         for (i = 0; i < sig->param_count; ++i) {
1231                 switch (args [i].type) {
1232                 case STACK_INV:
1233                         return 0;
1234                 case STACK_MP:
1235                         if (!sig->params [i]->byref)
1236                                 return 0;
1237                         continue;
1238                 case STACK_OBJ:
1239                         if (sig->params [i]->byref)
1240                                 return 0;
1241                         switch (sig->params [i]->type) {
1242                         case MONO_TYPE_CLASS:
1243                         case MONO_TYPE_STRING:
1244                         case MONO_TYPE_OBJECT:
1245                         case MONO_TYPE_SZARRAY:
1246                         case MONO_TYPE_ARRAY:
1247                                 break;
1248                         default:
1249                                 return 0;
1250                         }
1251                         continue;
1252                 case STACK_R8:
1253                         if (sig->params [i]->byref)
1254                                 return 0;
1255                         if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1256                                 return 0;
1257                         continue;
1258                 case STACK_PTR:
1259                 case STACK_I4:
1260                 case STACK_I8:
1261                 case STACK_VTYPE:
1262                         break;
1263                 }
1264                 /*if (!param_table [args [i].type] [sig->params [i]->type])
1265                         return 0;*/
1266         }
1267         return 1;
1268 }
1269 #endif
1270
1271 /*
1272  * When we need a pointer to the current domain many times in a method, we
1273  * call mono_domain_get() once and we store the result in a local variable.
1274  * This function returns the variable that represents the MonoDomain*.
1275  */
1276 inline static MonoInst *
1277 mono_get_domainvar (MonoCompile *cfg)
1278 {
1279         if (!cfg->domainvar)
1280                 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1281         return cfg->domainvar;
1282 }
1283
1284 MonoInst*
1285 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1286 {
1287         MonoInst *inst;
1288         int num = cfg->num_varinfo;
1289
1290         if ((num + 1) >= cfg->varinfo_count) {
1291                 cfg->varinfo_count = (cfg->varinfo_count + 2) * 2;
1292                 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
1293                 cfg->vars = (MonoMethodVar **)g_realloc (cfg->vars, sizeof (MonoMethodVar*) * cfg->varinfo_count);      
1294         }
1295
1296         mono_jit_stats.allocate_var++;
1297
1298         MONO_INST_NEW (cfg, inst, opcode);
1299         inst->inst_c0 = num;
1300         inst->inst_vtype = type;
1301         inst->klass = mono_class_from_mono_type (type);
1302         /* if set to 1 the variable is native */
1303         inst->unused = 0;
1304
1305         cfg->varinfo [num] = inst;
1306
1307         cfg->vars [num] = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoMethodVar));
1308         MONO_INIT_VARINFO (cfg->vars [num], num);
1309
1310         cfg->num_varinfo++;
1311         //g_print ("created temp %d of type %s\n", num, mono_type_get_name (type));
1312         return inst;
1313 }
1314
1315 static MonoType*
1316 type_from_stack_type (MonoInst *ins) {
1317         switch (ins->type) {
1318         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1319         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1320         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1321         case STACK_R8: return &mono_defaults.double_class->byval_arg;
1322         case STACK_MP: return &mono_defaults.int_class->byval_arg;
1323         case STACK_OBJ: return &mono_defaults.object_class->byval_arg;
1324         case STACK_VTYPE: return &ins->klass->byval_arg;
1325         default:
1326                 g_error ("stack type %d to montype not handled\n", ins->type);
1327         }
1328         return NULL;
1329 }
1330
1331 static MonoClass*
1332 array_access_to_klass (int opcode)
1333 {
1334         switch (opcode) {
1335         case CEE_LDELEM_U1:
1336                 return mono_defaults.byte_class;
1337         case CEE_LDELEM_U2:
1338                 return mono_defaults.uint16_class;
1339         case CEE_LDELEM_I:
1340         case CEE_STELEM_I:
1341                 return mono_defaults.int_class;
1342         case CEE_LDELEM_I1:
1343         case CEE_STELEM_I1:
1344                 return mono_defaults.sbyte_class;
1345         case CEE_LDELEM_I2:
1346         case CEE_STELEM_I2:
1347                 return mono_defaults.int16_class;
1348         case CEE_LDELEM_I4:
1349         case CEE_STELEM_I4:
1350                 return mono_defaults.int32_class;
1351         case CEE_LDELEM_U4:
1352                 return mono_defaults.uint32_class;
1353         case CEE_LDELEM_I8:
1354         case CEE_STELEM_I8:
1355                 return mono_defaults.int64_class;
1356         case CEE_LDELEM_R4:
1357         case CEE_STELEM_R4:
1358                 return mono_defaults.single_class;
1359         case CEE_LDELEM_R8:
1360         case CEE_STELEM_R8:
1361                 return mono_defaults.double_class;
1362         case CEE_LDELEM_REF:
1363         case CEE_STELEM_REF:
1364                 return mono_defaults.object_class;
1365         default:
1366                 g_assert_not_reached ();
1367         }
1368         return NULL;
1369 }
1370
1371 static void
1372 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
1373 {
1374         MonoInst *prev;
1375         if (!bb->code) {
1376                 MONO_ADD_INS (bb, inst);
1377                 return;
1378         }
1379         switch (bb->last_ins->opcode) {
1380         case CEE_BEQ:
1381         case CEE_BGE:
1382         case CEE_BGT:
1383         case CEE_BLE:
1384         case CEE_BLT:
1385         case CEE_BNE_UN:
1386         case CEE_BGE_UN:
1387         case CEE_BGT_UN:
1388         case CEE_BLE_UN:
1389         case CEE_BLT_UN:
1390         case CEE_BR:
1391                 prev = bb->code;
1392                 while (prev->next && prev->next != bb->last_ins)
1393                         prev = prev->next;
1394                 if (prev == bb->code) {
1395                         if (bb->last_ins == bb->code) {
1396                                 inst->next = bb->code;
1397                                 bb->code = inst;
1398                         } else {
1399                                 inst->next = prev->next;
1400                                 prev->next = inst;
1401                         }
1402                 } else {
1403                         inst->next = bb->last_ins;
1404                         prev->next = inst;
1405                 }
1406                 break;
1407         //      g_warning ("handle conditional jump in add_ins_to_end ()\n");
1408         default:
1409                 MONO_ADD_INS (bb, inst);
1410                 break;
1411         }
1412 }
1413
1414 void
1415 mono_add_varcopy_to_end (MonoCompile *cfg, MonoBasicBlock *bb, int src, int dest)
1416 {
1417         MonoInst *inst, *load;
1418
1419         NEW_TEMPLOAD (cfg, load, src);
1420
1421         NEW_TEMPSTORE (cfg, inst, dest, load);
1422         if (inst->opcode == CEE_STOBJ) {
1423                 NEW_TEMPLOADA (cfg, inst, dest);
1424                 handle_stobj (cfg, bb, inst, load, NULL, inst->klass, TRUE, FALSE);
1425         } else {
1426                 inst->cil_code = NULL;
1427                 mono_add_ins_to_end (bb, inst);
1428         }
1429 }
1430
1431 /*
1432  * This function is called to handle items that are left on the evaluation stack
1433  * at basic block boundaries. What happens is that we save the values to local variables
1434  * and we reload them later when first entering the target basic block (with the
1435  * handle_loaded_temps () function).
1436  * A single joint point will use the same variables (stored in the array bb->out_stack or
1437  * bb->in_stack, if the basic block is before or after the joint point).
1438  */
1439 static int
1440 handle_stack_args (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **sp, int count) {
1441         int i;
1442         MonoBasicBlock *outb;
1443         MonoInst *inst, **locals;
1444
1445         if (!count)
1446                 return 0;
1447         if (cfg->verbose_level > 3)
1448                 g_print ("%d item(s) on exit from B%d\n", count, bb->block_num);
1449         if (!bb->out_scount) {
1450                 int found = 0;
1451                 bb->out_scount = count;
1452                 //g_print ("bblock %d has out:", bb->block_num);
1453                 for (i = 0; i < bb->out_count; ++i) {
1454                         outb = bb->out_bb [i];
1455                         //g_print (" %d", outb->block_num);
1456                         if (outb->in_stack) {
1457                                 found = 1;
1458                                 bb->out_stack = outb->in_stack;
1459                                 break;
1460                         }
1461                 }
1462                 //g_print ("\n");
1463                 if (!found) {
1464                         bb->out_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
1465                         for (i = 0; i < count; ++i) {
1466                                 /* 
1467                                  * dietmar suggests that we can reuse temps already allocated 
1468                                  * for this purpouse, if they occupy the same stack slot and if 
1469                                  * they are of the same type.
1470                                  */
1471                                 bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
1472                         }
1473                 }
1474         }
1475         locals = bb->out_stack;
1476         for (i = 0; i < count; ++i) {
1477                 /* add store ops at the end of the bb, before the branch */
1478                 NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
1479                 if (inst->opcode == CEE_STOBJ) {
1480                         NEW_TEMPLOADA (cfg, inst, locals [i]->inst_c0);
1481                         handle_stobj (cfg, bb, inst, sp [i], sp [i]->cil_code, inst->klass, TRUE, FALSE);
1482                 } else {
1483                         inst->cil_code = sp [i]->cil_code;
1484                         mono_add_ins_to_end (bb, inst);
1485                 }
1486                 if (cfg->verbose_level > 3)
1487                         g_print ("storing %d to temp %d\n", i, locals [i]->inst_c0);
1488         }
1489         
1490         for (i = 0; i < bb->out_count; ++i) {
1491                 outb = bb->out_bb [i];
1492                 if (outb->in_scount)
1493                         continue; /* check they are the same locals */
1494                 outb->in_scount = count;
1495                 outb->in_stack = locals;
1496         }
1497         return 0;
1498 }
1499
1500 static int
1501 ret_type_to_call_opcode (MonoType *type, int calli, int virt)
1502 {
1503         int t = type->type;
1504
1505         if (type->byref)
1506                 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
1507
1508 handle_enum:
1509         switch (t) {
1510         case MONO_TYPE_VOID:
1511                 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALLVIRT: OP_VOIDCALL;
1512         case MONO_TYPE_I1:
1513         case MONO_TYPE_U1:
1514         case MONO_TYPE_BOOLEAN:
1515         case MONO_TYPE_I2:
1516         case MONO_TYPE_U2:
1517         case MONO_TYPE_CHAR:
1518         case MONO_TYPE_I4:
1519         case MONO_TYPE_U4:
1520                 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
1521         case MONO_TYPE_I:
1522         case MONO_TYPE_U:
1523         case MONO_TYPE_PTR:
1524                 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
1525         case MONO_TYPE_CLASS:
1526         case MONO_TYPE_STRING:
1527         case MONO_TYPE_OBJECT:
1528         case MONO_TYPE_SZARRAY:
1529         case MONO_TYPE_ARRAY:    
1530                 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
1531         case MONO_TYPE_I8:
1532         case MONO_TYPE_U8:
1533                 return calli? OP_LCALL_REG: virt? OP_LCALLVIRT: OP_LCALL;
1534         case MONO_TYPE_R4:
1535         case MONO_TYPE_R8:
1536                 return calli? OP_FCALL_REG: virt? OP_FCALLVIRT: OP_FCALL;
1537         case MONO_TYPE_VALUETYPE:
1538                 if (type->data.klass->enumtype) {
1539                         t = type->data.klass->enum_basetype->type;
1540                         goto handle_enum;
1541                 } else
1542                         return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
1543         default:
1544                 g_error ("unknown type %02x in ret_type_to_call_opcode", type->type);
1545         }
1546         return -1;
1547 }
1548
1549 void
1550 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
1551 {
1552         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
1553         
1554         ji->ip.label = label;
1555         ji->type = MONO_PATCH_INFO_SWITCH;
1556         ji->data.table = bbs;
1557         ji->next = cfg->patch_info;
1558         ji->table_size = num_blocks;
1559         cfg->patch_info = ji;
1560 }
1561
1562 /*
1563  * When we add a tree of instructions, we need to ensure the instructions currently
1564  * on the stack are executed before (like, if we load a value from a local).
1565  * We ensure this by saving the currently loaded values to temps and rewriting the
1566  * instructions to load the values.
1567  * This is not done for opcodes that terminate a basic block (because it's handled already
1568  * by handle_stack_args ()) and for opcodes that can't change values, like POP.
1569  */
1570 static void
1571 handle_loaded_temps (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst **stack, MonoInst **sp)
1572 {
1573         MonoInst *load, *store, *temp, *ins;
1574
1575         while (stack < sp) {
1576                 ins = *stack;
1577                 /* handle also other constants */
1578                 if (ins->opcode != OP_ICONST) {
1579                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1580                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
1581                         store->cil_code = ins->cil_code;
1582                         if (store->opcode == CEE_STOBJ) {
1583                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
1584                                 handle_stobj (cfg, bblock, store, ins, ins->cil_code, temp->klass, FALSE, FALSE);
1585                         } else
1586                                 MONO_ADD_INS (bblock, store);
1587                         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
1588                         load->cil_code = ins->cil_code;
1589                         *stack = load;
1590                 }
1591                 stack++;
1592         }
1593 }
1594
1595 inline static int
1596 mono_spill_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoCallInst *call, MonoMethodSignature *sig, gboolean ret_object, 
1597                  const guint8 *ip, gboolean to_end)
1598 {
1599         MonoInst *temp, *store, *ins = (MonoInst*)call;
1600         MonoType *ret = sig->ret;
1601
1602         if (!MONO_TYPE_IS_VOID (ret) || ret_object) {
1603                 if (ret_object) {
1604                         call->inst.type = STACK_OBJ;
1605                         call->inst.opcode = CEE_CALL;
1606                         temp = mono_compile_create_var (cfg, &mono_defaults.string_class->byval_arg, OP_LOCAL);
1607                 } else {
1608                         type_to_eval_stack_type (ret, ins);
1609                         temp = mono_compile_create_var (cfg, ret, OP_LOCAL);
1610                 }
1611
1612                 if (MONO_TYPE_ISSTRUCT (ret)) {
1613                         MonoInst *loada;
1614
1615                         /* we use this to allocate native sized structs */
1616                         temp->unused = sig->pinvoke;
1617
1618                         NEW_TEMPLOADA (cfg, loada, temp->inst_c0);
1619                         if (call->inst.opcode == OP_VCALL)
1620                                 ins->inst_left = loada;
1621                         else
1622                                 ins->inst_right = loada; /* a virtual or indirect call */
1623
1624                         if (to_end)
1625                                 mono_add_ins_to_end (bblock, ins);
1626                         else
1627                                 MONO_ADD_INS (bblock, ins);
1628                 } else {
1629                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
1630                         store->cil_code = ip;
1631                         if (to_end)
1632                                 mono_add_ins_to_end (bblock, store);
1633                         else
1634                                 MONO_ADD_INS (bblock, store);
1635                 }
1636                 return temp->inst_c0;
1637         } else {
1638                 if (to_end)
1639                         mono_add_ins_to_end (bblock, ins);
1640                 else
1641                         MONO_ADD_INS (bblock, ins);
1642                 return -1;
1643         }
1644 }
1645
1646 inline static MonoCallInst *
1647 mono_emit_call_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
1648                      MonoInst **args, int calli, int virtual, const guint8 *ip, gboolean to_end)
1649 {
1650         MonoCallInst *call;
1651         int i;
1652
1653         MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (sig->ret, calli, virtual));
1654         
1655         call->inst.cil_code = ip;
1656         call->args = args;
1657         call->signature = sig;
1658         call = mono_arch_call_opcode (cfg, bblock, call, virtual);
1659
1660         for (i = 0; i < (sig->param_count + sig->hasthis); ++i) {
1661                 if (call->args [i]) {
1662                         if (to_end)
1663                                 mono_add_ins_to_end (bblock, call->args [i]);
1664                         else
1665                                 MONO_ADD_INS (bblock, call->args [i]);
1666                 }
1667         }
1668         return call;
1669 }
1670
1671 inline static int
1672 mono_emit_calli (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
1673                  MonoInst **args, MonoInst *addr, const guint8 *ip)
1674 {
1675         MonoCallInst *call = mono_emit_call_args (cfg, bblock, sig, args, TRUE, FALSE, ip, FALSE);
1676
1677         call->inst.inst_i0 = addr;
1678
1679         return mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
1680 }
1681
1682 static MonoCallInst*
1683 mono_emit_method_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
1684                        MonoInst **args, const guint8 *ip, MonoInst *this)
1685 {
1686         gboolean virtual = this != NULL;
1687         MonoCallInst *call;
1688
1689         call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, virtual, ip, FALSE);
1690
1691         if (this && sig->hasthis && 
1692             (method->klass->marshalbyref || method->klass == mono_defaults.object_class) && 
1693             !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !MONO_CHECK_THIS (this)) {
1694                 call->method = mono_marshal_get_remoting_invoke_with_check (method);
1695         } else {
1696                 call->method = method;
1697         }
1698         call->inst.flags |= MONO_INST_HAS_METHOD;
1699         call->inst.inst_left = this;
1700
1701         return call;
1702 }
1703
1704 inline static int
1705 mono_emit_method_call_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
1706                        MonoInst **args, const guint8 *ip, MonoInst *this)
1707 {
1708         MonoCallInst *call = mono_emit_method_call (cfg, bblock, method, method->signature, args, ip, this);
1709
1710         return mono_spill_call (cfg, bblock, call, method->signature, method->string_ctor, ip, FALSE);
1711 }
1712
1713 inline static int
1714 mono_emit_native_call (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoMethodSignature *sig,
1715                        MonoInst **args, const guint8 *ip, gboolean to_end)
1716 {
1717         MonoCallInst *call;
1718
1719         g_assert (sig);
1720
1721         call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, FALSE, ip, to_end);
1722         call->fptr = func;
1723         return mono_spill_call (cfg, bblock, call, sig, func == mono_array_new_va, ip, to_end);
1724 }
1725
1726 inline static int
1727 mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip)
1728 {
1729         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
1730         
1731         if (!info) {
1732                 g_warning ("unregistered JIT ICall");
1733                 g_assert_not_reached ();
1734         }
1735
1736         return mono_emit_native_call (cfg, bblock, info->wrapper, info->sig, args, ip, FALSE);
1737 }
1738
1739 static void
1740 mono_emulate_opcode (MonoCompile *cfg, MonoInst *tree, MonoInst **iargs, MonoJitICallInfo *info)
1741 {
1742         MonoInst *ins, *temp = NULL, *store, *load;
1743         int i, nargs;
1744         MonoCallInst *call;
1745
1746         /*g_print ("emulating: ");
1747         mono_print_tree (tree);
1748         g_print ("\n");*/
1749         MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (info->sig->ret, FALSE, FALSE));
1750         ins = (MonoInst*)call;
1751         
1752         call->inst.cil_code = tree->cil_code;
1753         call->args = iargs;
1754         call->signature = info->sig;
1755
1756         call = mono_arch_call_opcode (cfg, cfg->cbb, call, FALSE);
1757
1758         if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
1759                 temp = mono_compile_create_var (cfg, info->sig->ret, OP_LOCAL);
1760                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
1761                 store->cil_code = tree->cil_code;
1762         } else {
1763                 store = ins;
1764         }
1765
1766         nargs = info->sig->param_count + info->sig->hasthis;
1767
1768         for (i = 1; i < nargs; i++) {
1769                 call->args [i - 1]->next = call->args [i];
1770         }
1771
1772         if (nargs)
1773                 call->args [nargs - 1]->next = store;
1774
1775         if (cfg->prev_ins) {
1776                 store->next = cfg->prev_ins->next;
1777                 if (nargs)
1778                         cfg->prev_ins->next =  call->args [0];
1779                 else
1780                         cfg->prev_ins->next = store;
1781         } else {
1782                 store->next = cfg->cbb->code;
1783                 if (nargs)              
1784                         cfg->cbb->code = call->args [0];
1785                 else
1786                         cfg->cbb->code = store;
1787         }
1788
1789         
1790         call->fptr = info->wrapper;
1791
1792         if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
1793                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
1794                 *tree = *load;
1795         }
1796 }
1797
1798 static MonoMethodSignature *
1799 mono_get_element_address_signature (int arity)
1800 {
1801         static GHashTable *sighash = NULL;
1802         MonoMethodSignature *res;
1803         int i;
1804
1805         if (!sighash)
1806                 sighash = g_hash_table_new (NULL, NULL);
1807
1808
1809         if ((res = g_hash_table_lookup (sighash, (gpointer)arity)))
1810                 return res;
1811
1812         res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
1813
1814         res->params [0] = &mono_defaults.array_class->byval_arg; 
1815         
1816         for (i = 1; i <= arity; i++)
1817                 res->params [i] = &mono_defaults.int_class->byval_arg;
1818
1819         res->ret = &mono_defaults.int_class->byval_arg;
1820
1821         g_hash_table_insert (sighash, (gpointer)arity, res);
1822
1823         return res;
1824 }
1825
1826 static void
1827 handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native) {
1828         MonoInst *iargs [3];
1829         int n;
1830
1831         g_assert (klass);
1832         /*
1833          * This check breaks with spilled vars... need to handle it during verification anyway.
1834          * g_assert (klass && klass == src->klass && klass == dest->klass);
1835          */
1836
1837         if (native)
1838                 n = mono_class_native_size (klass, NULL);
1839         else
1840                 n = mono_class_value_size (klass, NULL);
1841
1842         iargs [0] = dest;
1843         iargs [1] = src;
1844         NEW_ICONST (cfg, iargs [2], n);
1845
1846         mono_emit_native_call (cfg, bblock, helper_memcpy, helper_sig_memcpy, iargs, ip, to_end);
1847 }
1848
1849 static void
1850 handle_initobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, const guchar *ip, MonoClass *klass, MonoInst **stack_start, MonoInst **sp)
1851 {
1852         MonoInst *iargs [2];
1853         MonoInst *ins, *zero_int32;
1854         int n;
1855
1856         NEW_ICONST (cfg, zero_int32, 0);
1857
1858         mono_class_init (klass);
1859         n = mono_class_value_size (klass, NULL);
1860         MONO_INST_NEW (cfg, ins, 0);
1861         ins->cil_code = ip;
1862         ins->inst_left = dest;
1863         ins->inst_right = zero_int32;
1864         switch (n) {
1865         case 1:
1866                 ins->opcode = CEE_STIND_I1;
1867                 MONO_ADD_INS (bblock, ins);
1868                 break;
1869         case 2:
1870                 ins->opcode = CEE_STIND_I2;
1871                 MONO_ADD_INS (bblock, ins);
1872                 break;
1873         case 4:
1874                 ins->opcode = CEE_STIND_I4;
1875                 MONO_ADD_INS (bblock, ins);
1876                 break;
1877         default:
1878                 handle_loaded_temps (cfg, bblock, stack_start, sp);
1879                 NEW_ICONST (cfg, ins, n);
1880                 iargs [0] = dest;
1881                 iargs [1] = ins;
1882                 mono_emit_jit_icall (cfg, bblock, helper_initobj, iargs, ip);
1883                 break;
1884         }
1885 }
1886
1887 #define CODE_IS_STLOC(ip) (((ip) [0] >= CEE_STLOC_0 && (ip) [0] <= CEE_STLOC_3) || ((ip) [0] == CEE_STLOC_S))
1888
1889 static gboolean
1890 mono_method_check_inlining (MonoMethod *method)
1891 {
1892         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
1893         MonoMethodSignature *signature = method->signature;
1894         int i;
1895
1896         /* fixme: we should inline wrappers */
1897         if (method->wrapper_type != MONO_WRAPPER_NONE)
1898                 return FALSE;
1899
1900         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1901             (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1902             (method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
1903             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
1904             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1905             (method->klass->marshalbyref) ||
1906             !header || header->num_clauses ||
1907             /* fixme: why cant we inline valuetype returns? */
1908             MONO_TYPE_ISSTRUCT (signature->ret))
1909                 return FALSE;
1910
1911         /* its not worth to inline methods with valuetype arguments?? */
1912         for (i = 0; i < signature->param_count; i++) {
1913                 if (MONO_TYPE_ISSTRUCT (signature->params [i])) {
1914                         return FALSE;
1915                 }
1916         }
1917
1918         //if (!MONO_TYPE_IS_VOID (signature->ret)) return FALSE;
1919
1920         /* also consider num_locals? */
1921         if (header->code_size < 20)
1922                 return TRUE;
1923
1924         return FALSE;
1925 }
1926
1927 static MonoInst*
1928 mini_get_opcode_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
1929 {
1930         int pc, op;
1931         MonoInst *ins;
1932
1933         if (cmethod->klass == mono_defaults.string_class) {
1934                 if (cmethod->name [0] != 'g' || strcmp (cmethod->name, "get_Chars"))
1935                         return NULL;
1936                 op = OP_GETCHR;
1937         } else if (cmethod->klass == mono_defaults.math_class) {
1938                 if (strcmp (cmethod->name, "Sin") == 0)
1939                         op = OP_SIN;
1940                 else if (strcmp (cmethod->name, "Cos") == 0)
1941                         op = OP_COS;
1942                 else if (strcmp (cmethod->name, "Tan") == 0)
1943                         op = OP_TAN;
1944                 else if (strcmp (cmethod->name, "Atan") == 0)
1945                         op = OP_ATAN;
1946                 else if (strcmp (cmethod->name, "Sqrt") == 0)
1947                         op = OP_SQRT;
1948                 else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8)
1949                         op = OP_ABS;
1950                 else
1951                         return NULL;
1952         } else {
1953                 return NULL;
1954         }
1955         pc = fsig->param_count + fsig->hasthis;
1956         MONO_INST_NEW (cfg, ins, op);
1957
1958         if (pc > 0) {
1959                 ins->inst_i0 = args [0];
1960                 if (pc > 1)
1961                         ins->inst_i1 = args [1];
1962         }
1963
1964         return ins;
1965 }
1966
1967 static void
1968 mono_save_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, MonoInst **sp, MonoInst **args)
1969 {
1970         MonoInst *store, *temp;
1971         int i;
1972
1973         g_assert (!MONO_TYPE_ISSTRUCT (sig->ret));
1974
1975         if (!sig->hasthis && sig->param_count == 0) 
1976                 return;
1977
1978         if (sig->hasthis) {
1979                 if (sp [0]->opcode == OP_ICONST) {
1980                         *args++ = sp [0];
1981                 } else {
1982                         temp = mono_compile_create_var (cfg, type_from_stack_type (*sp), OP_LOCAL);
1983                         *args++ = temp;
1984                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
1985                         store->cil_code = sp [0]->cil_code;
1986                         MONO_ADD_INS (bblock, store);
1987                 }
1988                 sp++;
1989         }
1990
1991         for (i = 0; i < sig->param_count; ++i) {
1992                 if (sp [0]->opcode == OP_ICONST) {
1993                         *args++ = sp [0];
1994                 } else {
1995                         temp = mono_compile_create_var (cfg, sig->params [i], OP_LOCAL);
1996                         *args++ = temp;
1997                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
1998                         store->cil_code = sp [0]->cil_code;
1999                         if (store->opcode == CEE_STOBJ) {
2000                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2001                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, temp->klass, FALSE, FALSE);
2002                         } else {
2003                                 MONO_ADD_INS (bblock, store);
2004                         } 
2005                 }
2006                 sp++;
2007         }
2008 }
2009
2010 static int
2011 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoBasicBlock *bblock, MonoInst **sp,
2012                 guchar *ip, guint real_offset, GList *dont_inline, MonoBasicBlock **last_b)
2013 {
2014         MonoInst *ins, *rvar = NULL;
2015         MonoMethodHeader *cheader;
2016         MonoBasicBlock *ebblock, *sbblock;
2017         int i, costs, new_locals_offset;
2018                                 
2019         if (cfg->verbose_level > 2)
2020                 g_print ("INLINE START %p %s\n", cmethod,  mono_method_full_name (cmethod, TRUE));
2021
2022         cheader = ((MonoMethodNormal *)cmethod)->header;
2023
2024         if (!cmethod->inline_info) {
2025                 mono_jit_stats.inlineable_methods++;
2026                 cmethod->inline_info = 1;
2027         }
2028         /* allocate space to store the return value */
2029         if (!MONO_TYPE_IS_VOID (fsig->ret)) 
2030                 rvar =  mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
2031
2032         /* allocate local variables */
2033         new_locals_offset = cfg->num_varinfo;
2034         for (i = 0; i < cheader->num_locals; ++i)
2035                 mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
2036         
2037         /* allocate starte and end blocks */
2038         sbblock = NEW_BBLOCK (cfg);
2039         sbblock->block_num = cfg->num_bblocks++;
2040         sbblock->real_offset = real_offset;
2041
2042         ebblock = NEW_BBLOCK (cfg);
2043         ebblock->block_num = cfg->num_bblocks++;
2044         ebblock->real_offset = real_offset;
2045         
2046         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, new_locals_offset, rvar, dont_inline, sp, real_offset, *ip == CEE_CALLVIRT);
2047         
2048         if (costs >= 0 && costs < 60) {
2049                 if (cfg->verbose_level > 2)
2050                         g_print ("INLINE END %s\n", mono_method_full_name (cmethod, TRUE));
2051                 
2052                 mono_jit_stats.inlined_methods++;
2053
2054                 /* always add some code to avoid block split failures */
2055                 MONO_INST_NEW (cfg, ins, CEE_NOP);
2056                 MONO_ADD_INS (bblock, ins);
2057                 ins->cil_code = ip;
2058
2059                 bblock->next_bb = sbblock;
2060                 link_bblock (cfg, bblock, sbblock);
2061
2062                 if (rvar) {
2063                         NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
2064                         *sp++ = ins;
2065                 }
2066                 *last_b = ebblock;
2067                 return costs + 1;
2068         } else {
2069                 if (cfg->verbose_level > 2)
2070                         g_print ("INLINE ABORTED %s\n", mono_method_full_name (cmethod, TRUE));
2071         }
2072         return 0;
2073 }
2074
2075 /*
2076  * Some of these comments may well be out-of-date.
2077  * Design decisions: we do a single pass over the IL code (and we do bblock 
2078  * splitting/merging in the few cases when it's required: a back jump to an IL
2079  * address that was not already seen as bblock starting point).
2080  * Code is validated as we go (full verification is still better left to metadata/verify.c).
2081  * Complex operations are decomposed in simpler ones right away. We need to let the 
2082  * arch-specific code peek and poke inside this process somehow (except when the 
2083  * optimizations can take advantage of the full semantic info of coarse opcodes).
2084  * All the opcodes of the form opcode.s are 'normalized' to opcode.
2085  * MonoInst->opcode initially is the IL opcode or some simplification of that 
2086  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
2087  * opcode with value bigger than OP_LAST.
2088  * At this point the IR can be handed over to an interpreter, a dumb code generator
2089  * or to the optimizing code generator that will translate it to SSA form.
2090  *
2091  * Profiling directed optimizations.
2092  * We may compile by default with few or no optimizations and instrument the code
2093  * or the user may indicate what methods to optimize the most either in a config file
2094  * or through repeated runs where the compiler applies offline the optimizations to 
2095  * each method and then decides if it was worth it.
2096  *
2097  * TODO:
2098  * * consider using an array instead of an hash table (bb_hash)
2099  */
2100
2101 #define CHECK_TYPE(ins) if (!(ins)->type) goto unverified
2102 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) goto unverified
2103 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) goto unverified
2104
2105 /* offset from br.s -> br like opcodes */
2106 #define BIG_BRANCH_OFFSET 13
2107
2108 /*
2109  * mono_method_to_ir: translates IL into basic blocks containing trees
2110  */
2111 static int
2112 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
2113                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
2114                    guint inline_offset, gboolean is_virtual_call)
2115 {
2116         MonoInst *zero_int32, *zero_int64, *zero_ptr, *zero_obj, *zero_r8;
2117         MonoInst *ins, **sp, **stack_start;
2118         MonoBasicBlock *bblock, *tblock = NULL, *init_localsbb = NULL;
2119         GHashTable *bbhash;
2120         MonoMethod *cmethod;
2121         MonoInst **arg_array;
2122         MonoMethodHeader *header;
2123         MonoImage *image;
2124         guint32 token, ins_flag;
2125         MonoClass *klass;
2126         unsigned char *ip, *end, *target;
2127         static double r8_0 = 0.0;
2128         MonoMethodSignature *sig;
2129         MonoType **param_types;
2130         GList *bb_recheck = NULL, *tmp;
2131         int i, n, start_new_bblock, align;
2132         int num_calls = 0, inline_costs = 0;
2133         int *filter_lengths = NULL;
2134         int breakpoint_id = 0;
2135         guint real_offset;
2136
2137         image = method->klass->image;
2138         header = ((MonoMethodNormal *)method)->header;
2139         sig = method->signature;
2140         ip = (unsigned char*)header->code;
2141         end = ip + header->code_size;
2142         mono_jit_stats.cil_code_size += header->code_size;
2143
2144         if (cfg->method == method) {
2145                 real_offset = 0;
2146                 bbhash = cfg->bb_hash;
2147         } else {
2148                 real_offset = inline_offset;
2149                 bbhash = g_hash_table_new (g_direct_hash, NULL);
2150         }
2151
2152         dont_inline = g_list_prepend (dont_inline, method);
2153         if (cfg->method == method) {
2154
2155                 /* ENTRY BLOCK */
2156                 cfg->bb_entry = start_bblock = NEW_BBLOCK (cfg);
2157                 start_bblock->cil_code = NULL;
2158                 start_bblock->cil_length = 0;
2159                 start_bblock->block_num = cfg->num_bblocks++;
2160
2161                 /* EXIT BLOCK */
2162                 cfg->bb_exit = end_bblock = NEW_BBLOCK (cfg);
2163                 end_bblock->cil_code = NULL;
2164                 end_bblock->cil_length = 0;
2165                 end_bblock->block_num = cfg->num_bblocks++;
2166                 g_assert (cfg->num_bblocks == 2);
2167
2168                 arg_array = alloca (sizeof (MonoInst *) * (sig->hasthis + sig->param_count));
2169                 for (i = sig->hasthis + sig->param_count - 1; i >= 0; i--)
2170                         arg_array [i] = cfg->varinfo [i];
2171
2172                 if (mono_compile_aot) 
2173                         cfg->opt |= MONO_OPT_SAHRED;
2174
2175                 if (header->num_clauses) {
2176                         int size = sizeof (int) * header->num_clauses;
2177                         filter_lengths = alloca (size);
2178                         memset (filter_lengths, 0, size);
2179                 }
2180                 /* handle exception clauses */
2181                 for (i = 0; i < header->num_clauses; ++i) {
2182                         //unsigned char *p = ip;
2183                         MonoExceptionClause *clause = &header->clauses [i];
2184                         GET_BBLOCK (cfg, bbhash, tblock, ip + clause->try_offset);
2185                         tblock->real_offset = clause->try_offset;
2186                         GET_BBLOCK (cfg, bbhash, tblock, ip + clause->handler_offset);
2187                         tblock->real_offset = clause->handler_offset;
2188                         /*g_print ("clause try IL_%04x to IL_%04x handler %d at IL_%04x to IL_%04x\n", clause->try_offset, clause->try_offset + clause->try_len, clause->flags, clause->handler_offset, clause->handler_offset + clause->handler_len);
2189                           while (p < end) {
2190                           g_print ("%s", mono_disasm_code_one (NULL, method, p, &p));
2191                           }*/
2192                         /* catch and filter blocks get the exception object on the stack */
2193                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
2194                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2195                                 /* mostly like handle_stack_args (), but just sets the input args */
2196                                 /* g_print ("handling clause at IL_%04x\n", clause->handler_offset); */
2197                                 if (!cfg->exvar) {
2198                                         cfg->exvar = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
2199                                         /* prevent it from being register allocated */
2200                                         cfg->exvar->flags |= MONO_INST_INDIRECT;
2201                                 }
2202                                 tblock->in_scount = 1;
2203                                 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
2204                                 tblock->in_stack [0] = cfg->exvar;
2205                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2206                                         GET_BBLOCK (cfg, bbhash, tblock, ip + clause->token_or_filter);
2207                                         tblock->real_offset = clause->token_or_filter;
2208                                         tblock->in_scount = 1;
2209                                         tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
2210                                         tblock->in_stack [0] = cfg->exvar;
2211                                 }
2212                         }
2213                 }
2214
2215         } else {
2216                 arg_array = alloca (sizeof (MonoInst *) * (sig->hasthis + sig->param_count));
2217                 mono_save_args (cfg, start_bblock, sig, inline_args, arg_array);
2218         }
2219
2220         /* FIRST CODE BLOCK */
2221         bblock = NEW_BBLOCK (cfg);
2222         bblock->cil_code = ip;
2223
2224         ADD_BBLOCK (cfg, bbhash, bblock);
2225
2226         if (cfg->method == method) {
2227                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
2228                 if (breakpoint_id && (mono_debug_format != MONO_DEBUG_FORMAT_DEBUGGER)) {
2229                         MONO_INST_NEW (cfg, ins, CEE_BREAK);
2230                         MONO_ADD_INS (bblock, ins);
2231                 }
2232         }
2233         
2234         if ((header->init_locals || (cfg->method == method && (cfg->opt & MONO_OPT_SAHRED)))) {
2235                 /* we use a separate basic block for the initialization code */
2236                 cfg->bb_init = init_localsbb = NEW_BBLOCK (cfg);
2237                 init_localsbb->real_offset = real_offset;
2238                 start_bblock->next_bb = init_localsbb;
2239                 init_localsbb->next_bb = bblock;
2240                 link_bblock (cfg, start_bblock, init_localsbb);
2241                 link_bblock (cfg, init_localsbb, bblock);
2242                 init_localsbb->block_num = cfg->num_bblocks++;
2243         } else {
2244                 start_bblock->next_bb = bblock;
2245                 link_bblock (cfg, start_bblock, bblock);
2246         }
2247
2248         mono_debug_init_method (cfg, bblock, breakpoint_id);
2249
2250         param_types = mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * (sig->hasthis + sig->param_count));
2251         if (sig->hasthis)
2252                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
2253         for (n = 0; n < sig->param_count; ++n)
2254                 param_types [n + sig->hasthis] = sig->params [n];
2255
2256         /* do this somewhere outside - not here */
2257         NEW_ICONST (cfg, zero_int32, 0);
2258         NEW_ICONST (cfg, zero_int64, 0);
2259         zero_int64->type = STACK_I8;
2260         NEW_PCONST (cfg, zero_ptr, 0);
2261         NEW_PCONST (cfg, zero_obj, 0);
2262         zero_obj->type = STACK_OBJ;
2263
2264         MONO_INST_NEW (cfg, zero_r8, OP_R8CONST);
2265         zero_r8->type = STACK_R8;
2266         zero_r8->inst_p0 = &r8_0;
2267
2268         /* add a check for this != NULL to inlined methods */
2269         if (is_virtual_call) {
2270                 MONO_INST_NEW (cfg, ins, OP_CHECK_THIS);
2271                 NEW_ARGLOAD (cfg, ins->inst_left, 0);
2272                 ins->cil_code = ip;
2273                 MONO_ADD_INS (bblock, ins);
2274         }
2275
2276         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
2277         stack_start = sp = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
2278
2279         ins_flag = 0;
2280         start_new_bblock = 0;
2281         while (ip < end) {
2282
2283                 if (cfg->method == method)
2284                         real_offset = ip - header->code;
2285                 else
2286                         real_offset = inline_offset;
2287
2288                 if (start_new_bblock) {
2289                         bblock->cil_length = ip - bblock->cil_code;
2290                         if (start_new_bblock == 2) {
2291                                 g_assert (ip == tblock->cil_code);
2292                         } else {
2293                                 GET_BBLOCK (cfg, bbhash, tblock, ip);
2294                         }
2295                         bblock->next_bb = tblock;
2296                         bblock = tblock;
2297                         start_new_bblock = 0;
2298                         for (i = 0; i < bblock->in_scount; ++i) {
2299                                 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
2300                                 *sp++ = ins;
2301                         }
2302                 } else {
2303                         if ((tblock = g_hash_table_lookup (bbhash, ip)) && (tblock != bblock)) {
2304                                 link_bblock (cfg, bblock, tblock);
2305                                 if (sp != stack_start) {
2306                                         handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2307                                         sp = stack_start;
2308                                 }
2309                                 bblock->next_bb = tblock;
2310                                 bblock = tblock;
2311                                 for (i = 0; i < bblock->in_scount; ++i) {
2312                                         NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
2313                                         *sp++ = ins;
2314                                 }
2315                         }
2316                 }
2317
2318                 if (cfg->verbose_level > 3)
2319                         g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, sp-stack_start, mono_disasm_code_one (NULL, method, ip, NULL));
2320
2321                 switch (*ip) {
2322                 case CEE_NOP:
2323                         ++ip;
2324                         break;
2325                 case CEE_BREAK:
2326                         MONO_INST_NEW (cfg, ins, CEE_BREAK);
2327                         ins->cil_code = ip++;
2328                         MONO_ADD_INS (bblock, ins);
2329                         break;
2330                 case CEE_LDARG_0:
2331                 case CEE_LDARG_1:
2332                 case CEE_LDARG_2:
2333                 case CEE_LDARG_3:
2334                         CHECK_STACK_OVF (1);
2335                         n = (*ip)-CEE_LDARG_0;
2336                         NEW_ARGLOAD (cfg, ins, n);
2337                         ins->cil_code = ip++;
2338                         *sp++ = ins;
2339                         break;
2340                 case CEE_LDLOC_0:
2341                 case CEE_LDLOC_1:
2342                 case CEE_LDLOC_2:
2343                 case CEE_LDLOC_3:
2344                         CHECK_STACK_OVF (1);
2345                         n = (*ip)-CEE_LDLOC_0;
2346                         NEW_LOCLOAD (cfg, ins, n);
2347                         ins->cil_code = ip++;
2348                         *sp++ = ins;
2349                         break;
2350                 case CEE_STLOC_0:
2351                 case CEE_STLOC_1:
2352                 case CEE_STLOC_2:
2353                 case CEE_STLOC_3:
2354                         CHECK_STACK (1);
2355                         n = (*ip)-CEE_STLOC_0;
2356                         --sp;
2357                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2358                         NEW_LOCSTORE (cfg, ins, n, *sp);
2359                         ins->cil_code = ip;
2360                         if (ins->opcode == CEE_STOBJ) {
2361                                 NEW_LOCLOADA (cfg, ins, n);
2362                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
2363                         } else
2364                                 MONO_ADD_INS (bblock, ins);
2365                         ++ip;
2366                         inline_costs += 1;
2367                         break;
2368                 case CEE_LDARG_S:
2369                         CHECK_STACK_OVF (1);
2370                         NEW_ARGLOAD (cfg, ins, ip [1]);
2371                         ins->cil_code = ip;
2372                         *sp++ = ins;
2373                         ip += 2;
2374                         break;
2375                 case CEE_LDARGA_S:
2376                         CHECK_STACK_OVF (1);
2377                         NEW_ARGLOADA (cfg, ins, ip [1]);
2378                         ins->cil_code = ip;
2379                         *sp++ = ins;
2380                         ip += 2;
2381                         break;
2382                 case CEE_STARG_S:
2383                         CHECK_STACK (1);
2384                         --sp;
2385                         NEW_ARGSTORE (cfg, ins, ip [1], *sp);
2386                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2387                         ins->cil_code = ip;
2388                         if (ins->opcode == CEE_STOBJ) {
2389                                 NEW_ARGLOADA (cfg, ins, ip [1]);
2390                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
2391                         } else
2392                                 MONO_ADD_INS (bblock, ins);
2393                         ip += 2;
2394                         break;
2395                 case CEE_LDLOC_S:
2396                         CHECK_STACK_OVF (1);
2397                         NEW_LOCLOAD (cfg, ins, ip [1]);
2398                         ins->cil_code = ip;
2399                         *sp++ = ins;
2400                         ip += 2;
2401                         break;
2402                 case CEE_LDLOCA_S:
2403                         CHECK_STACK_OVF (1);
2404                         NEW_LOCLOADA (cfg, ins, ip [1]);
2405                         ins->cil_code = ip;
2406                         *sp++ = ins;
2407                         ip += 2;
2408                         break;
2409                 case CEE_STLOC_S:
2410                         CHECK_STACK (1);
2411                         --sp;
2412                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2413                         NEW_LOCSTORE (cfg, ins, ip [1], *sp);
2414                         ins->cil_code = ip;
2415                         if (ins->opcode == CEE_STOBJ) {
2416                                 NEW_LOCLOADA (cfg, ins, ip [1]);
2417                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
2418                         } else
2419                                 MONO_ADD_INS (bblock, ins);
2420                         ip += 2;
2421                         inline_costs += 1;
2422                         break;
2423                 case CEE_LDNULL:
2424                         CHECK_STACK_OVF (1);
2425                         NEW_PCONST (cfg, ins, NULL);
2426                         ins->cil_code = ip;
2427                         ins->type = STACK_OBJ;
2428                         ++ip;
2429                         *sp++ = ins;
2430                         break;
2431                 case CEE_LDC_I4_M1:
2432                         CHECK_STACK_OVF (1);
2433                         NEW_ICONST (cfg, ins, -1);
2434                         ins->cil_code = ip;
2435                         ++ip;
2436                         *sp++ = ins;
2437                         break;
2438                 case CEE_LDC_I4_0:
2439                 case CEE_LDC_I4_1:
2440                 case CEE_LDC_I4_2:
2441                 case CEE_LDC_I4_3:
2442                 case CEE_LDC_I4_4:
2443                 case CEE_LDC_I4_5:
2444                 case CEE_LDC_I4_6:
2445                 case CEE_LDC_I4_7:
2446                 case CEE_LDC_I4_8:
2447                         CHECK_STACK_OVF (1);
2448                         NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
2449                         ins->cil_code = ip;
2450                         ++ip;
2451                         *sp++ = ins;
2452                         break;
2453                 case CEE_LDC_I4_S:
2454                         CHECK_STACK_OVF (1);
2455                         ++ip;
2456                         NEW_ICONST (cfg, ins, *((signed char*)ip));
2457                         ins->cil_code = ip;
2458                         ++ip;
2459                         *sp++ = ins;
2460                         break;
2461                 case CEE_LDC_I4:
2462                         CHECK_STACK_OVF (1);
2463                         NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
2464                         ins->cil_code = ip;
2465                         ip += 5;
2466                         *sp++ = ins;
2467                         break;
2468                 case CEE_LDC_I8:
2469                         CHECK_STACK_OVF (1);
2470                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
2471                         ins->cil_code = ip;
2472                         ins->type = STACK_I8;
2473                         ++ip;
2474                         ins->inst_l = (gint64)read64 (ip);
2475                         ip += 8;
2476                         *sp++ = ins;
2477                         break;
2478                 case CEE_LDC_R4: {
2479                         float *f = g_malloc (sizeof (float));
2480                         CHECK_STACK_OVF (1);
2481                         MONO_INST_NEW (cfg, ins, OP_R4CONST);
2482                         ins->type = STACK_R8;
2483                         ++ip;
2484                         readr4 (ip, f);
2485                         ins->inst_p0 = f;
2486                         ip += 4;
2487                         *sp++ = ins;                    
2488                         break;
2489                 }
2490                 case CEE_LDC_R8: {
2491                         double *d = g_malloc (sizeof (double));
2492                         CHECK_STACK_OVF (1);
2493                         MONO_INST_NEW (cfg, ins, OP_R8CONST);
2494                         ins->type = STACK_R8;
2495                         ++ip;
2496                         readr8 (ip, d);
2497                         ins->inst_p0 = d;
2498                         ip += 8;
2499                         *sp++ = ins;                    
2500                         break;
2501                 }
2502                 case CEE_DUP: {
2503                         MonoInst *temp, *store;
2504                         CHECK_STACK (1);
2505                         CHECK_STACK_OVF (1);
2506                         sp--;
2507                         ins = *sp;
2508                 
2509                         /* 
2510                          * small optimization: if the loaded value was from a local already,
2511                          * just load it twice.
2512                          */
2513                         if (ins->ssa_op == MONO_SSA_LOAD && 
2514                             (ins->inst_i0->opcode == OP_LOCAL || ins->inst_i0->opcode == OP_ARG)) {
2515                                 sp++;
2516                                 MONO_INST_NEW (cfg, temp, 0);
2517                                 *temp = *ins;
2518                                 temp->cil_code = ip;
2519                                 *sp++ = temp;
2520                         } else {
2521                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
2522                                 temp->cil_code = ip;
2523                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2524                                 store->cil_code = ip;
2525                                 MONO_ADD_INS (bblock, store);
2526                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
2527                                 *sp++ = ins;
2528                                 ins->cil_code = ip;
2529                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
2530                                 *sp++ = ins;
2531                                 ins->cil_code = ip;
2532                         }
2533                         ++ip;
2534                         inline_costs += 2;
2535                         break;
2536                 }
2537                 case CEE_POP:
2538                         CHECK_STACK (1);
2539                         MONO_INST_NEW (cfg, ins, CEE_POP);
2540                         MONO_ADD_INS (bblock, ins);
2541                         ins->cil_code = ip++;
2542                         --sp;
2543                         ins->inst_i0 = *sp;
2544                         break;
2545                 case CEE_JMP:
2546                         if (stack_start != sp)
2547                                 goto unverified;
2548                         MONO_INST_NEW (cfg, ins, CEE_JMP);
2549                         token = read32 (ip + 1);
2550                         /* FIXME: check the signature matches */
2551                         cmethod = mono_get_method (image, token, NULL);
2552                         /*
2553                          * The current magic trampoline can't handle this
2554                          * apparently, so we compile the method right away.
2555                          * Later, we may need to fix the trampoline or use a different one.
2556                          */
2557                         ins->inst_p0 = mono_compile_method (cmethod);
2558                         MONO_ADD_INS (bblock, ins);
2559                         ip += 5;
2560                         start_new_bblock = 1;
2561                         break;
2562                 case CEE_CALLI:
2563                 case CEE_CALL:
2564                 case CEE_CALLVIRT: {
2565                         MonoInst *addr = NULL;
2566                         MonoMethodSignature *fsig = NULL;
2567                         int temp, array_rank = 0;
2568                         int virtual = *ip == CEE_CALLVIRT;
2569
2570                         token = read32 (ip + 1);
2571
2572                         if (*ip == CEE_CALLI) {
2573                                 cmethod = NULL;
2574                                 CHECK_STACK (1);
2575                                 --sp;
2576                                 addr = *sp;
2577                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
2578                                         fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
2579                                 else
2580                                         fsig = mono_metadata_parse_signature (image, token);
2581
2582                                 n = fsig->param_count + fsig->hasthis;
2583
2584                         } else {
2585                                 cmethod = mono_get_method (image, token, NULL);
2586
2587                                 if (!cmethod->klass->inited)
2588                                         mono_class_init (cmethod->klass);
2589
2590                                 if (cmethod->signature->pinvoke) {
2591 #ifdef MONO_USE_EXC_TABLES
2592                                         if (mono_method_blittable (cmethod)) {
2593                                                 fsig = cmethod->signature;
2594                                         } else {
2595 #endif
2596                                                 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod);
2597                                                 fsig = wrapper->signature;
2598 #ifdef MONO_USE_EXC_TABLES
2599                                         }
2600 #endif
2601                                 } else {
2602                                         fsig = cmethod->signature;
2603                                 }
2604
2605                                 n = fsig->param_count + fsig->hasthis;
2606
2607                                 if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
2608                                     cmethod->klass->parent == mono_defaults.array_class) {
2609                                         array_rank = cmethod->klass->rank;
2610                                 }
2611
2612                                 if (cmethod->string_ctor)
2613                                         g_assert_not_reached ();
2614
2615                         }
2616
2617                         CHECK_STACK (n);
2618
2619                         //g_assert (!virtual || fsig->hasthis);
2620
2621                         sp -= n;
2622
2623                         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_get_opcode_for_method (cfg, cmethod, fsig, sp))) {
2624                                 ins->cil_code = ip;
2625
2626                                 if (MONO_TYPE_IS_VOID (fsig->ret)) {
2627                                         MONO_ADD_INS (bblock, ins);
2628                                 } else {
2629                                         type_to_eval_stack_type (fsig->ret, ins);
2630                                         *sp = ins;
2631                                         sp++;
2632                                 }
2633
2634                                 ip += 5;
2635                                 break;
2636                         }
2637
2638                         if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
2639                             (!virtual || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || (cmethod->flags & METHOD_ATTRIBUTE_FINAL)) && 
2640                             mono_method_check_inlining (cmethod) &&
2641                             !g_list_find (dont_inline, cmethod)) {
2642                                 int costs;
2643                                 MonoBasicBlock *ebblock;
2644                                 
2645                                 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock))) {
2646                                         ip += 5;
2647                                         real_offset += 5;
2648
2649                                         GET_BBLOCK (cfg, bbhash, bblock, ip);
2650                                         ebblock->next_bb = bblock;
2651                                         link_bblock (cfg, ebblock, bblock);
2652                                         if (!MONO_TYPE_IS_VOID (fsig->ret))
2653                                                 sp++;
2654
2655                                         if (sp != stack_start) {
2656                                                 handle_stack_args (cfg, ebblock, stack_start, sp - stack_start);
2657                                                 sp = stack_start;
2658                                         }
2659                                         start_new_bblock = 1;
2660
2661                                         inline_costs += costs;
2662                                         break;
2663                                 }
2664                         }
2665                         
2666                         inline_costs += 10 * num_calls++;
2667                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2668
2669                         /* tail recursion elimination */
2670                         if ((cfg->opt & MONO_OPT_TAILC) && *ip == CEE_CALL && cmethod == cfg->method && ip [5] == CEE_RET) {
2671                                 gboolean has_vtargs = FALSE;
2672                                 int i;
2673                                 
2674                                 /* keep it simple */
2675                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
2676                                         if (MONO_TYPE_ISSTRUCT (cmethod->signature->params [i])) 
2677                                                 has_vtargs = TRUE;
2678                                 }
2679
2680                                 if (!has_vtargs) {
2681                                         for (i = 0; i < n; ++i) {
2682                                                 NEW_ARGSTORE (cfg, ins, i, sp [i]);
2683                                                 ins->cil_code = ip;
2684                                                 MONO_ADD_INS (bblock, ins);
2685                                         }
2686                                         MONO_INST_NEW (cfg, ins, CEE_BR);
2687                                         ins->cil_code = ip;
2688                                         MONO_ADD_INS (bblock, ins);
2689                                         tblock = start_bblock->out_bb [0];
2690                                         link_bblock (cfg, bblock, tblock);
2691                                         ins->inst_target_bb = tblock;
2692                                         start_new_bblock = 1;
2693                                         ip += 5;
2694                                         
2695                                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
2696                                                 /* just create a dummy - the value is never used */
2697                                                 ins = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
2698                                                 NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
2699                                                 sp++;
2700                                         }
2701
2702                                         break;
2703                                 }
2704                         }
2705
2706                         if (*ip == CEE_CALLI) {
2707
2708                                 if ((temp = mono_emit_calli (cfg, bblock, fsig, sp, addr, ip)) != -1) {
2709                                         NEW_TEMPLOAD (cfg, *sp, temp);
2710                                         sp++;
2711                                 }
2712                                         
2713                         } else if (array_rank) {
2714                                 MonoMethodSignature *esig;
2715                                 MonoInst *addr;
2716
2717                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
2718                                         esig = mono_get_element_address_signature (fsig->param_count - 1);
2719                                         
2720                                         temp = mono_emit_native_call (cfg, bblock, ves_array_element_address, esig, sp, ip, FALSE);
2721                                         NEW_TEMPLOAD (cfg, addr, temp);
2722                                         NEW_INDSTORE (cfg, ins, addr, sp [fsig->param_count], fsig->params [fsig->param_count - 1]);
2723                                         ins->cil_code = ip;
2724                                         if (ins->opcode == CEE_STOBJ) {
2725                                                 handle_stobj (cfg, bblock, addr, sp [fsig->param_count], ip, mono_class_from_mono_type (fsig->params [fsig->param_count-1]), FALSE, FALSE);
2726                                         } else {
2727                                                 MONO_ADD_INS (bblock, ins);
2728                                         }
2729
2730                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
2731                                         esig = mono_get_element_address_signature (fsig->param_count);
2732
2733                                         temp = mono_emit_native_call (cfg, bblock, ves_array_element_address, esig, sp, ip, FALSE);
2734                                         NEW_TEMPLOAD (cfg, addr, temp);
2735                                         NEW_INDLOAD (cfg, ins, addr, fsig->ret);
2736                                         ins->cil_code = ip;
2737
2738                                         *sp++ = ins;
2739                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
2740                                         /* implement me */
2741                                         esig = mono_get_element_address_signature (fsig->param_count);
2742
2743                                         temp = mono_emit_native_call (cfg, bblock, ves_array_element_address, esig, sp, ip, FALSE);
2744                                         NEW_TEMPLOAD (cfg, *sp, temp);
2745                                         sp++;
2746                                 } else {
2747                                         g_assert_not_reached ();
2748                                 }
2749
2750                         } else {
2751                                 if (0 && CODE_IS_STLOC (ip + 5) && (!MONO_TYPE_ISSTRUCT (fsig->ret)) && (!MONO_TYPE_IS_VOID (fsig->ret) || cmethod->string_ctor)) {
2752                                         /* no need to spill */
2753                                         ins = (MonoInst*)mono_emit_method_call (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL);
2754                                         *sp++ = ins;
2755                                 } else {
2756                                         if ((temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, sp, ip, virtual ? sp [0] : NULL)) != -1) {
2757                                                 NEW_TEMPLOAD (cfg, *sp, temp);
2758                                                 sp++;
2759                                         }
2760                                 }
2761                         }
2762
2763                         ip += 5;
2764                         break;
2765                 }
2766                 case CEE_RET:
2767                         if (cfg->method != method) {
2768                                 /* return from inlined methode */
2769                                 if (return_var) {
2770                                         MonoInst *store;
2771                                         CHECK_STACK (1);
2772                                         --sp;
2773                                         //g_assert (returnvar != -1);
2774                                         NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
2775                                         store->cil_code = sp [0]->cil_code;
2776                                         if (store->opcode == CEE_STOBJ) {
2777                                                 g_assert_not_reached ();
2778                                                 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
2779                                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, return_var->klass, FALSE, FALSE);
2780                                         } else
2781                                                 MONO_ADD_INS (bblock, store);
2782                                 } 
2783                         } else {
2784                                 if (cfg->ret) {
2785                                         g_assert (!return_var);
2786                                         CHECK_STACK (1);
2787                                         --sp;
2788                                         MONO_INST_NEW (cfg, ins, CEE_NOP);
2789                                         ins->opcode = mono_type_to_stind (method->signature->ret);
2790                                         if (ins->opcode == CEE_STOBJ) {
2791                                                 NEW_RETLOADA (cfg, ins);
2792                                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
2793                                         } else {
2794                                                 ins->opcode = OP_SETRET;
2795                                                 ins->cil_code = ip;
2796                                                 ins->inst_i0 = *sp;;
2797                                                 ins->inst_i1 = NULL;
2798                                                 MONO_ADD_INS (bblock, ins);
2799                                         }
2800                                 }
2801                         }
2802                         if (sp != stack_start)
2803                                 goto unverified;
2804                         MONO_INST_NEW (cfg, ins, CEE_BR);
2805                         ins->cil_code = ip++;
2806                         ins->inst_target_bb = end_bblock;
2807                         MONO_ADD_INS (bblock, ins);
2808                         link_bblock (cfg, bblock, end_bblock);
2809                         start_new_bblock = 1;
2810                         break;
2811                 case CEE_BR_S:
2812                         MONO_INST_NEW (cfg, ins, CEE_BR);
2813                         ins->cil_code = ip++;
2814                         MONO_ADD_INS (bblock, ins);
2815                         target = ip + 1 + (signed char)(*ip);
2816                         ++ip;
2817                         GET_BBLOCK (cfg, bbhash, tblock, target);
2818                         link_bblock (cfg, bblock, tblock);
2819                         CHECK_BBLOCK (target, ip, tblock);
2820                         ins->inst_target_bb = tblock;
2821                         if (sp != stack_start) {
2822                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2823                                 sp = stack_start;
2824                         }
2825                         start_new_bblock = 1;
2826                         inline_costs += 10;
2827                         break;
2828                 case CEE_BRFALSE_S:
2829                 case CEE_BRTRUE_S:
2830                         CHECK_STACK (1);
2831                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
2832                         ins->cil_code = ip++;
2833                         target = ip + 1 + *(signed char*)ip;
2834                         ip++;
2835                         ADD_UNCOND (ins->opcode == CEE_BRTRUE);
2836                         if (sp != stack_start) {
2837                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2838                                 sp = stack_start;
2839                         }
2840                         inline_costs += 10;
2841                         break;
2842                 case CEE_BEQ_S:
2843                 case CEE_BGE_S:
2844                 case CEE_BGT_S:
2845                 case CEE_BLE_S:
2846                 case CEE_BLT_S:
2847                 case CEE_BNE_UN_S:
2848                 case CEE_BGE_UN_S:
2849                 case CEE_BGT_UN_S:
2850                 case CEE_BLE_UN_S:
2851                 case CEE_BLT_UN_S:
2852                         CHECK_STACK (2);
2853                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
2854                         ins->cil_code = ip++;
2855                         target = ip + 1 + *(signed char*)ip;
2856                         ip++;
2857                         ADD_BINCOND (NULL);
2858                         if (sp != stack_start) {
2859                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2860                                 sp = stack_start;
2861                         }
2862                         inline_costs += 10;
2863                         break;
2864                 case CEE_BR:
2865                         MONO_INST_NEW (cfg, ins, CEE_BR);
2866                         ins->cil_code = ip++;
2867                         MONO_ADD_INS (bblock, ins);
2868                         target = ip + 4 + (gint32)read32(ip);
2869                         ip += 4;
2870                         GET_BBLOCK (cfg, bbhash, tblock, target);
2871                         link_bblock (cfg, bblock, tblock);
2872                         CHECK_BBLOCK (target, ip, tblock);
2873                         ins->inst_target_bb = tblock;
2874                         if (sp != stack_start) {
2875                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2876                                 sp = stack_start;
2877                         }
2878                         start_new_bblock = 1;
2879                         inline_costs += 10;
2880                         break;
2881                 case CEE_BRFALSE:
2882                 case CEE_BRTRUE:
2883                         CHECK_STACK (1);
2884                         MONO_INST_NEW (cfg, ins, *ip);
2885                         ins->cil_code = ip++;
2886                         target = ip + 4 + (gint32)read32(ip);
2887                         ip += 4;
2888                         ADD_UNCOND(ins->opcode == CEE_BRTRUE);
2889                         if (sp != stack_start) {
2890                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2891                                 sp = stack_start;
2892                         }
2893                         inline_costs += 10;
2894                         break;
2895                 case CEE_BEQ:
2896                 case CEE_BGE:
2897                 case CEE_BGT:
2898                 case CEE_BLE:
2899                 case CEE_BLT:
2900                 case CEE_BNE_UN:
2901                 case CEE_BGE_UN:
2902                 case CEE_BGT_UN:
2903                 case CEE_BLE_UN:
2904                 case CEE_BLT_UN:
2905                         CHECK_STACK (2);
2906                         MONO_INST_NEW (cfg, ins, *ip);
2907                         ins->cil_code = ip++;
2908                         target = ip + 4 + (gint32)read32(ip);
2909                         ip += 4;
2910                         ADD_BINCOND(NULL);
2911                         if (sp != stack_start) {
2912                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2913                                 sp = stack_start;
2914                         }
2915                         inline_costs += 10;
2916                         break;
2917                 case CEE_SWITCH:
2918                         CHECK_STACK (1);
2919                         n = read32 (ip + 1);
2920                         MONO_INST_NEW (cfg, ins, *ip);
2921                         --sp;
2922                         ins->inst_left = *sp;
2923                         if (ins->inst_left->type != STACK_I4) goto unverified;
2924                         ins->cil_code = ip;
2925                         ip += 5;
2926                         target = ip + n * sizeof (guint32);
2927                         MONO_ADD_INS (bblock, ins);
2928                         GET_BBLOCK (cfg, bbhash, tblock, target);
2929                         link_bblock (cfg, bblock, tblock);
2930                         ins->klass = GUINT_TO_POINTER (n);
2931                         ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (n + 1));
2932                         ins->inst_many_bb [n] = tblock;
2933
2934                         for (i = 0; i < n; ++i) {
2935                                 GET_BBLOCK (cfg, bbhash, tblock, target + (gint32)read32(ip));
2936                                 link_bblock (cfg, bblock, tblock);
2937                                 ins->inst_many_bb [i] = tblock;
2938                                 ip += 4;
2939                         }
2940                         /* FIXME: handle stack args */
2941                         inline_costs += 20;
2942                         break;
2943                 case CEE_LDIND_I1:
2944                 case CEE_LDIND_U1:
2945                 case CEE_LDIND_I2:
2946                 case CEE_LDIND_U2:
2947                 case CEE_LDIND_I4:
2948                 case CEE_LDIND_U4:
2949                 case CEE_LDIND_I8:
2950                 case CEE_LDIND_I:
2951                 case CEE_LDIND_R4:
2952                 case CEE_LDIND_R8:
2953                 case CEE_LDIND_REF:
2954                         CHECK_STACK (1);
2955                         MONO_INST_NEW (cfg, ins, *ip);
2956                         ins->cil_code = ip;
2957                         --sp;
2958                         ins->inst_i0 = *sp;
2959                         *sp++ = ins;
2960                         ins->type = ldind_type [*ip - CEE_LDIND_I1];
2961                         ins->flags |= ins_flag;
2962                         ins_flag = 0;
2963                         ++ip;
2964                         break;
2965                 case CEE_STIND_REF:
2966                 case CEE_STIND_I1:
2967                 case CEE_STIND_I2:
2968                 case CEE_STIND_I4:
2969                 case CEE_STIND_I8:
2970                 case CEE_STIND_R4:
2971                 case CEE_STIND_R8:
2972                         CHECK_STACK (2);
2973                         MONO_INST_NEW (cfg, ins, *ip);
2974                         ins->cil_code = ip++;
2975                         sp -= 2;
2976                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2977                         MONO_ADD_INS (bblock, ins);
2978                         ins->inst_i0 = sp [0];
2979                         ins->inst_i1 = sp [1];
2980                         ins->flags |= ins_flag;
2981                         ins_flag = 0;
2982                         inline_costs += 1;
2983                         break;
2984                 case CEE_ADD:
2985                 case CEE_SUB:
2986                 case CEE_MUL:
2987                 case CEE_DIV:
2988                 case CEE_DIV_UN:
2989                 case CEE_REM:
2990                 case CEE_REM_UN:
2991                 case CEE_AND:
2992                 case CEE_OR:
2993                 case CEE_XOR:
2994                 case CEE_SHL:
2995                 case CEE_SHR:
2996                 case CEE_SHR_UN:
2997                         CHECK_STACK (2);
2998                         ADD_BINOP (*ip);
2999                         ip++;
3000                         break;
3001                 case CEE_NEG:
3002                 case CEE_NOT:
3003                 case CEE_CONV_I1:
3004                 case CEE_CONV_I2:
3005                 case CEE_CONV_I4:
3006                 case CEE_CONV_I8:
3007                 case CEE_CONV_R4:
3008                 case CEE_CONV_R8:
3009                 case CEE_CONV_U4:
3010                 case CEE_CONV_U8:
3011                 case CEE_CONV_OVF_I8:
3012                 case CEE_CONV_OVF_U8:
3013                 case CEE_CONV_R_UN:
3014                         CHECK_STACK (1);
3015                         ADD_UNOP (*ip);
3016                         ip++;
3017                         break;
3018                 case CEE_CONV_OVF_I4:
3019                 case CEE_CONV_OVF_I1:
3020                 case CEE_CONV_OVF_I2:
3021                 case CEE_CONV_OVF_I:
3022                 case CEE_CONV_OVF_U:
3023                         CHECK_STACK (1);
3024
3025                         if (sp [-1]->type == STACK_R8) {
3026                                 ADD_UNOP (CEE_CONV_OVF_I8);
3027                                 ADD_UNOP (*ip);
3028                         } else {
3029                                 ADD_UNOP (*ip);
3030                         }
3031
3032                         ip++;
3033                         break;
3034                 case CEE_CONV_OVF_U1:
3035                 case CEE_CONV_OVF_U2:
3036                 case CEE_CONV_OVF_U4:
3037                         CHECK_STACK (1);
3038
3039                         if (sp [-1]->type == STACK_R8) {
3040                                 ADD_UNOP (CEE_CONV_OVF_U8);
3041                                 ADD_UNOP (*ip);
3042                         } else {
3043                                 ADD_UNOP (*ip);
3044                         }
3045
3046                         ip++;
3047                         break;
3048                 case CEE_CONV_OVF_I1_UN:
3049                 case CEE_CONV_OVF_I2_UN:
3050                 case CEE_CONV_OVF_I4_UN:
3051                 case CEE_CONV_OVF_I8_UN:
3052                 case CEE_CONV_OVF_U1_UN:
3053                 case CEE_CONV_OVF_U2_UN:
3054                 case CEE_CONV_OVF_U4_UN:
3055                 case CEE_CONV_OVF_U8_UN:
3056                 case CEE_CONV_OVF_I_UN:
3057                 case CEE_CONV_OVF_U_UN:
3058                         CHECK_STACK (1);
3059                         ADD_UNOP (*ip);
3060                         ip++;
3061                         break;
3062                 case CEE_CPOBJ:
3063                         g_error ("opcode 0x%02x not handled", *ip);
3064                         break;
3065                 case CEE_LDOBJ: {
3066                         MonoInst *iargs [3];
3067                         CHECK_STACK (1);
3068                         --sp;
3069                         token = read32 (ip + 1);
3070                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3071                                 klass = mono_method_get_wrapper_data (method, token);
3072                         else
3073                                 klass = mono_class_get (image, token);
3074
3075                         mono_class_init (klass);
3076                         n = mono_class_value_size (klass, NULL);
3077                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
3078                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
3079                         iargs [1] = *sp;
3080                         NEW_ICONST (cfg, iargs [2], n);
3081                         iargs [2]->cil_code = ip;
3082
3083                         mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
3084                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
3085                         ++sp;
3086                         ip += 5;
3087                         inline_costs += 1;
3088                         break;
3089                 }
3090                 case CEE_LDSTR:
3091                         CHECK_STACK_OVF (1);
3092                         n = read32 (ip + 1);
3093
3094                         if (mono_compile_aot) {
3095                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, (gpointer)n);
3096                         }
3097
3098                         if ((cfg->opt & MONO_OPT_SAHRED) || mono_compile_aot) {
3099                                 int temp;
3100                                 MonoInst *iargs [3];
3101                                 NEW_TEMPLOAD (cfg, iargs [0], mono_get_domainvar (cfg)->inst_c0);
3102                                 NEW_IMAGECONST (cfg, iargs [1], image);
3103                                 NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
3104                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldstr, iargs, ip);
3105                                 NEW_TEMPLOAD (cfg, *sp, temp);
3106                                 mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
3107                         } else {
3108                                 NEW_PCONST (cfg, ins, NULL);
3109                                 ins->cil_code = ip;
3110                                 ins->type = STACK_OBJ;
3111                                 ins->inst_p0 = mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
3112                                 *sp = ins;
3113                         }
3114                         sp++;
3115                         ip += 5;
3116                         break;
3117                 case CEE_NEWOBJ: {
3118                         MonoInst *iargs [2];
3119                         int temp;
3120
3121                         token = read32 (ip + 1);
3122                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
3123                                 cmethod = mono_method_get_wrapper_data (method, token);
3124                         } else
3125                                 cmethod = mono_get_method (image, token, NULL);
3126
3127                         mono_class_init (cmethod->klass);
3128
3129                         n = cmethod->signature->param_count;
3130                         CHECK_STACK (n);
3131
3132                         /* move the args to allow room for 'this' in the first position */
3133                         while (n--) {
3134                                 --sp;
3135                                 sp [1] = sp [0];
3136                         }
3137
3138                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3139                         
3140
3141                         if (cmethod->klass->parent == mono_defaults.array_class) {
3142                                 NEW_METHODCONST (cfg, *sp, cmethod);
3143                                 temp = mono_emit_native_call (cfg, bblock, mono_array_new_va, cmethod->signature, sp, ip, FALSE);
3144
3145                         } else if (cmethod->string_ctor) {
3146                                 /* we simply pass a null pointer */
3147                                 NEW_PCONST (cfg, *sp, NULL); 
3148                                 /* now call the string ctor */
3149                                 temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, sp, ip, NULL);
3150                         } else {
3151                                 if (cmethod->klass->valuetype) {
3152                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
3153                                         temp = iargs [0]->inst_c0;
3154                                         NEW_TEMPLOADA (cfg, *sp, temp);
3155                                 } else {
3156                                         NEW_DOMAINCONST (cfg, iargs [0]);
3157                                         NEW_CLASSCONST (cfg, iargs [1], cmethod->klass);
3158
3159                                         temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
3160                                         NEW_TEMPLOAD (cfg, *sp, temp);
3161                                 }
3162
3163                                 if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
3164                                     mono_method_check_inlining (cmethod) &&
3165                                     !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE) &&
3166                                     !g_list_find (dont_inline, cmethod)) {
3167                                         int costs;
3168                                         MonoBasicBlock *ebblock;
3169                                         if ((costs = inline_method (cfg, cmethod, cmethod->signature, bblock, sp, ip, real_offset, dont_inline, &ebblock))) {
3170
3171                                                 GET_BBLOCK (cfg, bbhash, bblock, ip + 5);
3172                                                 ebblock->next_bb = bblock;
3173                                                 link_bblock (cfg, ebblock, bblock);
3174
3175                                                 /*if (sp != stack_start) {
3176                                                         handle_stack_args (cfg, ebblock, stack_start, sp - stack_start);
3177                                                         sp = stack_start;
3178                                                 }
3179                                                 start_new_bblock = 1;*/
3180
3181                                                 inline_costs += costs;
3182                                                 /*g_print ("inlined newobj for %s\n", cmethod->klass->name);*/
3183                                         }
3184                                 } else {
3185                                         /* now call the actual ctor */
3186                                         mono_emit_method_call_spilled (cfg, bblock, cmethod, sp, ip, NULL);
3187                                 }
3188                         }
3189
3190                         NEW_TEMPLOAD (cfg, *sp, temp);
3191                         sp++;
3192                         
3193                         ip += 5;
3194                         inline_costs += 5;
3195                         break;
3196                 }
3197                 case CEE_ISINST:
3198                         CHECK_STACK (1);
3199                         MONO_INST_NEW (cfg, ins, *ip);
3200                         --sp;
3201                         klass = mono_class_get (image, read32 (ip + 1));
3202                         mono_class_init (klass);
3203                         ins->type = STACK_OBJ;
3204                         ins->inst_left = *sp;
3205                         ins->inst_newa_class = klass;
3206                         ins->cil_code = ip;
3207                         ip += 5;
3208                         *sp++ = ins;
3209                         break;
3210                 case CEE_UNBOX: {
3211                         MonoInst *add, *vtoffset;
3212
3213                         CHECK_STACK (1);
3214                         --sp;
3215                         token = read32 (ip + 1);
3216                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3217                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
3218                         else 
3219                                 klass = mono_class_get (image, token);
3220                         mono_class_init (klass);
3221
3222
3223                         MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
3224                         ins->type = STACK_OBJ;
3225                         ins->inst_left = *sp;
3226                         ins->klass = klass;
3227                         ins->inst_newa_class = klass;
3228                         ins->cil_code = ip;
3229
3230                         MONO_INST_NEW (cfg, add, CEE_ADD);
3231                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
3232                         add->inst_left = ins;
3233                         add->inst_right = vtoffset;
3234                         add->type = STACK_MP;
3235                         *sp++ = add;
3236                         ip += 5;
3237                         inline_costs += 2;
3238                         break;
3239                 }
3240                 case CEE_CASTCLASS:
3241                         CHECK_STACK (1);
3242                         MONO_INST_NEW (cfg, ins, *ip);
3243                         --sp;
3244                         klass = mono_class_get (image, read32 (ip + 1));
3245                         mono_class_init (klass);
3246                         ins->type = STACK_OBJ;
3247                         ins->inst_left = *sp;
3248                         ins->klass = klass;
3249                         ins->inst_newa_class = klass;
3250                         ins->cil_code = ip;
3251                         ip += 5;
3252                         *sp++ = ins;
3253                         break;
3254                 case CEE_THROW:
3255                         CHECK_STACK (1);
3256                         MONO_INST_NEW (cfg, ins, *ip);
3257                         --sp;
3258                         ins->inst_left = *sp;
3259                         ins->cil_code = ip++;
3260                         MONO_ADD_INS (bblock, ins);
3261                         sp = stack_start;
3262                         start_new_bblock = 1;
3263                         break;
3264                 case CEE_LDFLD:
3265                 case CEE_LDFLDA:
3266                 case CEE_STFLD: {
3267                         MonoInst *offset_ins;
3268                         MonoClassField *field;
3269                         guint foffset;
3270
3271                         if (*ip == CEE_STFLD) {
3272                                 CHECK_STACK (2);
3273                                 sp -= 2;
3274                         } else {
3275                                 CHECK_STACK (1);
3276                                 --sp;
3277                         }
3278                         // FIXME: enable this test later.
3279                         //if (sp [0]->type != STACK_OBJ && sp [0]->type != STACK_MP)
3280                         //      goto unverified;
3281                         token = read32 (ip + 1);
3282                         field = mono_field_from_token (image, token, &klass);
3283                         mono_class_init (klass);
3284                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
3285                         /* FIXME: mark instructions for use in SSA */
3286                         if (*ip == CEE_STFLD) {
3287                                 if (klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) {
3288                                         /* fixme: we need to inline that call somehow */
3289                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
3290                                         MonoInst *iargs [5];
3291                                         iargs [0] = sp [0];
3292                                         NEW_CLASSCONST (cfg, iargs [1], klass);
3293                                         NEW_FIELDCONST (cfg, iargs [2], field);
3294                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
3295                                         iargs [4] = sp [1];
3296                                         mono_emit_method_call_spilled (cfg, bblock, stfld_wrapper, iargs, ip, NULL);
3297                                 } else {
3298                                         MonoInst *store;
3299                                         NEW_ICONST (cfg, offset_ins, foffset);
3300                                         MONO_INST_NEW (cfg, ins, CEE_ADD);
3301                                         ins->cil_code = ip;
3302                                         ins->inst_left = *sp;
3303                                         ins->inst_right = offset_ins;
3304                                         ins->type = STACK_MP;
3305
3306                                         MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
3307                                         store->cil_code = ip;
3308                                         store->inst_left = ins;
3309                                         store->inst_right = sp [1];
3310                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3311                                         store->flags |= ins_flag;
3312                                         ins_flag = 0;
3313                                         if (store->opcode == CEE_STOBJ) {
3314                                                 handle_stobj (cfg, bblock, ins, sp [1], ip, 
3315                                                               mono_class_from_mono_type (field->type), FALSE, FALSE);
3316                                         } else
3317                                                 MONO_ADD_INS (bblock, store);
3318                                 }
3319                         } else {
3320                                 if (klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) {
3321                                         /* fixme: we need to inline that call somehow */
3322                                         MonoMethod *ldfld_wrapper = mono_marshal_get_ldfld_wrapper (field->type); 
3323                                         MonoInst *iargs [4];
3324                                         int temp;
3325                                         iargs [0] = sp [0];
3326                                         NEW_CLASSCONST (cfg, iargs [1], klass);
3327                                         NEW_FIELDCONST (cfg, iargs [2], field);
3328                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
3329                                         temp = mono_emit_method_call_spilled (cfg, bblock, ldfld_wrapper, iargs, ip, NULL);
3330                                         if (*ip == CEE_LDFLDA) {
3331                                                 /* not sure howto handle this */
3332                                                 NEW_TEMPLOADA (cfg, *sp, temp);
3333                                         } else {
3334                                                 NEW_TEMPLOAD (cfg, *sp, temp);
3335                                         }
3336                                         sp++;
3337                                 } else {
3338                                         NEW_ICONST (cfg, offset_ins, foffset);
3339                                         MONO_INST_NEW (cfg, ins, CEE_ADD);
3340                                         ins->cil_code = ip;
3341                                         ins->inst_left = *sp;
3342                                         ins->inst_right = offset_ins;
3343                                         ins->type = STACK_MP;
3344
3345                                         if (*ip == CEE_LDFLDA) {
3346                                                 *sp++ = ins;
3347                                         } else {
3348                                                 MonoInst *load;
3349                                                 MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
3350                                                 type_to_eval_stack_type (field->type, load);
3351                                                 load->cil_code = ip;
3352                                                 load->inst_left = ins;
3353                                                 load->flags |= ins_flag;
3354                                                 ins_flag = 0;
3355                                                 *sp++ = load;
3356                                         }
3357                                 }
3358                         }
3359                         ip += 5;
3360                         break;
3361                 }
3362                 case CEE_LDSFLD:
3363                 case CEE_LDSFLDA:
3364                 case CEE_STSFLD: {
3365                         MonoClassField *field;
3366                         MonoVTable *vtable;
3367
3368                         token = read32 (ip + 1);
3369
3370                         field = mono_field_from_token (image, token, &klass);
3371                         mono_class_init (klass);
3372
3373                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3374                                 
3375                         if (((cfg->opt & MONO_OPT_SAHRED) || mono_compile_aot)) {
3376                                 int temp;
3377                                 MonoInst *iargs [2];
3378                                 g_assert (field->parent);
3379                                 NEW_TEMPLOAD (cfg, iargs [0], mono_get_domainvar (cfg)->inst_c0);
3380                                 NEW_FIELDCONST (cfg, iargs [1], field);
3381                                 temp = mono_emit_jit_icall (cfg, bblock, mono_class_static_field_address, iargs, ip);
3382                                 NEW_TEMPLOAD (cfg, ins, temp);
3383                         } else {
3384                                 vtable = mono_class_vtable (cfg->domain, klass);
3385                                 NEW_PCONST (cfg, ins, (char*)vtable->data + field->offset);
3386                                 ins->cil_code = ip;
3387                         }
3388
3389                         /* FIXME: mark instructions for use in SSA */
3390                         if (*ip == CEE_LDSFLDA) {
3391                                 *sp++ = ins;
3392                         } else if (*ip == CEE_STSFLD) {
3393                                 MonoInst *store;
3394                                 CHECK_STACK (1);
3395                                 sp--;
3396                                 MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
3397                                 store->cil_code = ip;
3398                                 store->inst_left = ins;
3399                                 store->inst_right = sp [0];
3400                                 store->flags |= ins_flag;
3401                                 ins_flag = 0;
3402
3403                                 if (store->opcode == CEE_STOBJ) {
3404                                         handle_stobj (cfg, bblock, ins, sp [0], ip, mono_class_from_mono_type (field->type), FALSE, FALSE);
3405                                 } else
3406                                         MONO_ADD_INS (bblock, store);
3407                         } else {
3408                                 MonoInst *load;
3409                                 CHECK_STACK_OVF (1);
3410                                 MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
3411                                 type_to_eval_stack_type (field->type, load);
3412                                 load->cil_code = ip;
3413                                 load->inst_left = ins;
3414                                 *sp++ = load;
3415                                 load->flags |= ins_flag;
3416                                 ins_flag = 0;
3417                         /* fixme: dont see the problem why this does not work */
3418                                 //cfg->disable_aot = TRUE;
3419                         }
3420                         ip += 5;
3421                         break;
3422                 }
3423                 case CEE_STOBJ:
3424                         CHECK_STACK (2);
3425                         sp -= 2;
3426                         token = read32 (ip + 1);
3427                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3428                                 klass = mono_method_get_wrapper_data (method, token);
3429                         else
3430                                 klass = mono_class_get (image, token);
3431                         mono_class_init (klass);
3432                         handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE);
3433                         ip += 5;
3434                         inline_costs += 1;
3435                         break;
3436                 case CEE_BOX: {
3437                         MonoInst *iargs [2];
3438                         MonoInst *load, *vtoffset, *add, *val, *vstore;
3439                         int temp;
3440                         CHECK_STACK (1);
3441                         --sp;
3442                         val = *sp;
3443                         token = read32 (ip + 1);
3444                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3445                                 klass = mono_method_get_wrapper_data (method, token);
3446                         else
3447                                 klass = mono_class_get (image, token);
3448                         mono_class_init (klass);
3449
3450                         /* much like NEWOBJ */
3451                         NEW_DOMAINCONST (cfg, iargs [0]);
3452                         NEW_CLASSCONST (cfg, iargs [1], klass);
3453                         
3454                         temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
3455                         NEW_TEMPLOAD (cfg, load, temp);
3456                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
3457                         MONO_INST_NEW (cfg, add, CEE_ADD);
3458                         add->inst_left = load;
3459                         add->inst_right = vtoffset;
3460                         add->cil_code = ip;
3461                         add->klass = klass;
3462                         MONO_INST_NEW (cfg, vstore, CEE_STIND_I);
3463                         vstore->opcode = mono_type_to_stind (&klass->byval_arg);
3464                         vstore->cil_code = ip;
3465                         vstore->inst_left = add;
3466                         vstore->inst_right = val;
3467
3468                         if (vstore->opcode == CEE_STOBJ) {
3469                                 handle_stobj (cfg, bblock, add, val, ip, klass, FALSE, FALSE);
3470                         } else
3471                                 MONO_ADD_INS (bblock, vstore);
3472
3473                         NEW_TEMPLOAD (cfg, load, temp);
3474                         *sp++ = load;
3475                         ip += 5;
3476                         inline_costs += 1;
3477                         break;
3478                 }
3479                 case CEE_NEWARR:
3480                         CHECK_STACK (1);
3481                         MONO_INST_NEW (cfg, ins, *ip);
3482                         ins->cil_code = ip;
3483                         --sp;
3484
3485                         token = read32 (ip + 1);
3486
3487                         /* allocate the domainvar - becaus this is used in decompose_foreach */
3488                         if ((cfg->opt & MONO_OPT_SAHRED) || mono_compile_aot)
3489                                 mono_get_domainvar (cfg);
3490                         
3491                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3492                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
3493                         else
3494                                 klass = mono_class_get (image, token);
3495
3496                         mono_class_init (klass);
3497                         ins->inst_newa_class = klass;
3498                         ins->inst_newa_len = *sp;
3499                         ins->type = STACK_OBJ;
3500                         ip += 5;
3501                         *sp++ = ins;
3502                         inline_costs += 1;
3503                         break;
3504                 case CEE_LDLEN:
3505                         CHECK_STACK (1);
3506                         MONO_INST_NEW (cfg, ins, *ip);
3507                         ins->cil_code = ip++;
3508                         --sp;
3509                         ins->inst_left = *sp;
3510                         ins->type = STACK_PTR;
3511                         *sp++ = ins;
3512                         break;
3513                 case CEE_LDELEMA:
3514                         CHECK_STACK (2);
3515                         sp -= 2;
3516                         klass = mono_class_get (image, read32 (ip + 1));
3517                         mono_class_init (klass);
3518                         NEW_LDELEMA (cfg, ins, sp, klass);
3519                         ins->cil_code = ip;
3520                         *sp++ = ins;
3521                         ip += 5;
3522                         break;
3523                 case CEE_LDELEM_I1:
3524                 case CEE_LDELEM_U1:
3525                 case CEE_LDELEM_I2:
3526                 case CEE_LDELEM_U2:
3527                 case CEE_LDELEM_I4:
3528                 case CEE_LDELEM_U4:
3529                 case CEE_LDELEM_I8:
3530                 case CEE_LDELEM_I:
3531                 case CEE_LDELEM_R4:
3532                 case CEE_LDELEM_R8:
3533                 case CEE_LDELEM_REF: {
3534                         MonoInst *load;
3535                         /*
3536                          * translate to:
3537                          * ldind.x (ldelema (array, index))
3538                          * ldelema does the bounds check
3539                          */
3540                         CHECK_STACK (2);
3541                         sp -= 2;
3542                         klass = array_access_to_klass (*ip);
3543                         NEW_LDELEMA (cfg, load, sp, klass);
3544                         load->cil_code = ip;
3545                         MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
3546                         ins->cil_code = ip;
3547                         ins->inst_left = load;
3548                         *sp++ = ins;
3549                         ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
3550                         ++ip;
3551                         break;
3552                 }
3553                 case CEE_STELEM_I:
3554                 case CEE_STELEM_I1:
3555                 case CEE_STELEM_I2:
3556                 case CEE_STELEM_I4:
3557                 case CEE_STELEM_I8:
3558                 case CEE_STELEM_R4:
3559                 case CEE_STELEM_R8: {
3560                         MonoInst *load;
3561                         /*
3562                          * translate to:
3563                          * stind.x (ldelema (array, index), val)
3564                          * ldelema does the bounds check
3565                          */
3566                         CHECK_STACK (3);
3567                         sp -= 3;
3568                         klass = array_access_to_klass (*ip);
3569                         NEW_LDELEMA (cfg, load, sp, klass);
3570                         load->cil_code = ip;
3571                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
3572                         ins->cil_code = ip;
3573                         ins->inst_left = load;
3574                         ins->inst_right = sp [2];
3575                         ++ip;
3576                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3577                         MONO_ADD_INS (bblock, ins);
3578                         /* FIXME: add the implicit STELEM_REF castclass */
3579                         inline_costs += 1;
3580                         cfg->disable_ssa = TRUE;
3581                         break;
3582                 }
3583                 case CEE_STELEM_REF: {
3584                         MonoInst *iargs [3];
3585
3586                         CHECK_STACK (3);
3587                         sp -= 3;
3588
3589                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3590
3591                         iargs [2] = sp [2];
3592                         iargs [1] = sp [1];
3593                         iargs [0] = sp [0];
3594                         
3595                         mono_emit_jit_icall (cfg, bblock, helper_stelem_ref, iargs, ip);
3596
3597                         /*
3598                         MonoInst *group;
3599                         NEW_GROUP (cfg, group, sp [0], sp [1]);
3600                         MONO_INST_NEW (cfg, ins, CEE_STELEM_REF);
3601                         ins->cil_code = ip;
3602                         ins->inst_left = group;
3603                         ins->inst_right = sp [2];
3604                         MONO_ADD_INS (bblock, ins);
3605                         */
3606
3607                         ++ip;
3608                         inline_costs += 1;
3609                         cfg->disable_ssa = TRUE;
3610                         break;
3611                 }
3612                 case CEE_CKFINITE: {
3613                         MonoInst *store, *temp;
3614                         CHECK_STACK (1);
3615
3616                         /* this instr. can throw exceptions as side effect,
3617                          * so we cant eliminate dead code which contains CKFINITE opdodes.
3618                          * Spilling to memory makes sure that we always perform
3619                          * this check */
3620
3621                         
3622                         MONO_INST_NEW (cfg, ins, CEE_CKFINITE);
3623                         ins->cil_code = ip;
3624                         ins->inst_left = sp [-1];
3625                         temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
3626
3627                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
3628                         store->cil_code = ip;
3629                         MONO_ADD_INS (bblock, store);
3630
3631                         NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
3632                        
3633                         ++ip;
3634                         break;
3635                 }
3636                 case CEE_REFANYVAL:
3637                 case CEE_MKREFANY:
3638                         g_error ("opcode 0x%02x not handled", *ip);
3639                         break;
3640                 case CEE_LDTOKEN: {
3641                         gpointer handle;
3642                         MonoClass *handle_class;
3643
3644                         CHECK_STACK_OVF (1);
3645
3646                         n = read32 (ip + 1);
3647
3648                         handle = mono_ldtoken (image, n, &handle_class);
3649                         mono_class_init (handle_class);
3650
3651                         if (((cfg->opt & MONO_OPT_SAHRED) || mono_compile_aot)) {
3652                                 int temp;
3653                                 MonoInst *res, *store, *addr, *vtvar, *iargs [2];
3654
3655                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
3656
3657                                 NEW_IMAGECONST (cfg, iargs [0], image);
3658                                 NEW_ICONST (cfg, iargs [1], n);
3659                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
3660                                 NEW_TEMPLOAD (cfg, res, temp);
3661                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
3662                                 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
3663                                 MONO_ADD_INS (bblock, store);
3664                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
3665                         } else {
3666                                 if ((ip [5] == CEE_CALL) && (cmethod = mono_get_method (image, read32 (ip + 6), NULL)) &&
3667                                                 (cmethod->klass == mono_defaults.monotype_class->parent) &&
3668                                                 (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
3669                                         MonoClass *tclass = mono_class_from_mono_type (handle);
3670                                         mono_class_init (tclass);
3671                                         NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
3672                                         ins->type = STACK_OBJ;
3673                                         ins->klass = cmethod->klass;
3674                                         ip += 5;
3675                                 } else {
3676                                         NEW_PCONST (cfg, ins, handle);
3677                                         ins->type = STACK_VTYPE;
3678                                         ins->klass = handle_class;
3679                                 }
3680                         }
3681
3682                         *sp++ = ins;
3683                         ip += 5;
3684                         break;
3685                 }
3686                 case CEE_CONV_U2:
3687                 case CEE_CONV_U1:
3688                 case CEE_CONV_I:
3689                         CHECK_STACK (1);
3690                         ADD_UNOP (*ip);
3691                         ip++;
3692                         break;
3693                 case CEE_ADD_OVF:
3694                 case CEE_ADD_OVF_UN:
3695                 case CEE_MUL_OVF:
3696                 case CEE_MUL_OVF_UN:
3697                 case CEE_SUB_OVF:
3698                 case CEE_SUB_OVF_UN:
3699                         CHECK_STACK (2);
3700                         ADD_BINOP (*ip);
3701                         ip++;
3702                         break;
3703                 case CEE_ENDFINALLY:
3704                         /* FIXME: check stack state */
3705                         MONO_INST_NEW (cfg, ins, *ip);
3706                         MONO_ADD_INS (bblock, ins);
3707                         ins->cil_code = ip++;
3708                         start_new_bblock = 1;
3709                         break;
3710                 case CEE_LEAVE:
3711                 case CEE_LEAVE_S: {
3712                         GList *handlers;
3713                         if (*ip == CEE_LEAVE) {
3714                                 target = ip + 5 + (gint32)read32(ip + 1);
3715                         } else {
3716                                 target = ip + 2 + (signed char)(ip [1]);
3717                         }
3718
3719                         /* empty the stack */
3720                         while (sp != stack_start) {
3721                                 MONO_INST_NEW (cfg, ins, CEE_POP);
3722                                 ins->cil_code = ip;
3723                                 sp--;
3724                                 ins->inst_i0 = *sp;
3725                                 MONO_ADD_INS (bblock, ins);
3726                         }
3727
3728                         /* fixme: call fault handler ? */
3729
3730                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
3731                                 GList *tmp;
3732                                 for (tmp = handlers; tmp; tmp = tmp->next) {
3733                                         tblock = tmp->data;
3734                                         link_bblock (cfg, bblock, tblock);
3735                                         MONO_INST_NEW (cfg, ins, OP_HANDLER);
3736                                         ins->cil_code = ip;
3737                                         ins->inst_target_bb = tblock;
3738                                         MONO_ADD_INS (bblock, ins);
3739                                 }
3740                                 g_list_free (handlers);
3741                         } 
3742
3743                         MONO_INST_NEW (cfg, ins, CEE_BR);
3744                         ins->cil_code = ip;
3745                         MONO_ADD_INS (bblock, ins);
3746                         GET_BBLOCK (cfg, bbhash, tblock, target);
3747                         link_bblock (cfg, bblock, tblock);
3748                         CHECK_BBLOCK (target, ip, tblock);
3749                         ins->inst_target_bb = tblock;
3750                         start_new_bblock = 1;
3751
3752                         if (*ip == CEE_LEAVE)
3753                                 ip += 5;
3754                         else
3755                                 ip += 2;
3756
3757                         break;
3758                 }
3759                 case CEE_STIND_I:
3760                         CHECK_STACK (2);
3761                         MONO_INST_NEW (cfg, ins, *ip);
3762                         sp -= 2;
3763                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3764                         MONO_ADD_INS (bblock, ins);
3765                         ins->cil_code = ip++;
3766                         ins->inst_i0 = sp [0];
3767                         ins->inst_i1 = sp [1];
3768                         inline_costs += 1;
3769                         break;
3770                 case CEE_CONV_U:
3771                         CHECK_STACK (1);
3772                         ADD_UNOP (*ip);
3773                         ip++;
3774                         break;
3775                 /* trampoline mono specific opcodes */
3776                 case MONO_CUSTOM_PREFIX: {
3777
3778                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
3779
3780                         switch (ip [1]) {
3781
3782                         case CEE_MONO_FUNC1: {
3783                                 int temp;
3784                                 gpointer func = NULL;
3785                                 CHECK_STACK (1);
3786                                 sp--;
3787
3788                                 switch (ip [2]) {
3789                                 case MONO_MARSHAL_CONV_STR_LPWSTR:
3790                                         func = mono_string_to_utf16;
3791                                         break;
3792                                 case MONO_MARSHAL_CONV_LPWSTR_STR:
3793                                         func = mono_string_from_utf16;
3794                                         break;
3795                                 case MONO_MARSHAL_CONV_LPSTR_STR:
3796                                         func = mono_string_new_wrapper;
3797                                         break;
3798                                 case MONO_MARSHAL_CONV_STR_LPTSTR:
3799                                 case MONO_MARSHAL_CONV_STR_LPSTR:
3800                                         func = mono_string_to_utf8;
3801                                         break;
3802                                 case MONO_MARSHAL_CONV_STR_BSTR:
3803                                         func = mono_string_to_bstr;
3804                                         break;
3805                                 case MONO_MARSHAL_CONV_STR_TBSTR:
3806                                 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
3807                                         func = mono_string_to_ansibstr;
3808                                         break;
3809                                 case MONO_MARSHAL_CONV_SB_LPSTR:
3810                                         func = mono_string_builder_to_utf8;
3811                                         break;
3812                                 case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
3813                                         func = mono_array_to_savearray;
3814                                         break;
3815                                 case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
3816                                         func = mono_array_to_lparray;
3817                                         break;
3818                                 case MONO_MARSHAL_CONV_DEL_FTN:
3819                                         func = mono_delegate_to_ftnptr;
3820                                         break;
3821                                 case MONO_MARSHAL_CONV_STRARRAY_STRLPARRAY:
3822                                         func = mono_marshal_string_array;
3823                                         break;
3824                                 default:
3825                                         g_warning ("unknown conversion %d\n", ip [2]);
3826                                         g_assert_not_reached ();
3827                                 }
3828
3829                                 temp = mono_emit_jit_icall (cfg, bblock, func, sp, ip);
3830                                 NEW_TEMPLOAD (cfg, *sp, temp);
3831                                 sp++;
3832
3833                                 ip += 3;
3834                                 inline_costs += 10 * num_calls++;
3835                                 break;
3836                         }
3837                         case CEE_MONO_PROC2: {
3838                                 gpointer func = NULL;
3839                                 CHECK_STACK (2);
3840                                 sp -= 2;
3841
3842                                 switch (ip [2]) {
3843                                 case MONO_MARSHAL_CONV_LPSTR_SB:
3844                                         func = mono_string_utf8_to_builder;
3845                                         break;
3846                                 case MONO_MARSHAL_FREE_ARRAY:
3847                                         func = mono_marshal_free_array;
3848                                         break;
3849                                 default:
3850                                         g_assert_not_reached ();
3851                                 }
3852
3853                                 mono_emit_jit_icall (cfg, bblock, func, sp, ip);
3854                                 ip += 3;
3855                                 inline_costs += 10 * num_calls++;
3856                                 break;
3857                         }
3858                         case CEE_MONO_PROC3: {
3859                                 gpointer func = NULL;
3860                                 CHECK_STACK (3);
3861                                 sp -= 3;
3862
3863                                 switch (ip [2]) {
3864                                 case MONO_MARSHAL_CONV_STR_BYVALSTR:
3865                                         func = mono_string_to_byvalstr;
3866                                         break;
3867                                 case MONO_MARSHAL_CONV_STR_BYVALWSTR:
3868                                         func = mono_string_to_byvalwstr;
3869                                         break;
3870                                 default:
3871                                         g_assert_not_reached ();
3872                                 }
3873
3874                                 mono_emit_jit_icall (cfg, bblock, func, sp, ip);
3875                                 ip += 3;
3876                                 inline_costs += 10 * num_calls++;
3877                                 break;
3878                         }
3879                         case CEE_MONO_FREE:
3880                                 CHECK_STACK (1);
3881                                 sp -= 1;
3882                                 mono_emit_jit_icall (cfg, bblock, g_free, sp, ip);
3883                                 ip += 2;
3884                                 inline_costs += 10 * num_calls++;
3885                                 break;
3886                         case CEE_MONO_LDPTR:
3887                                 CHECK_STACK_OVF (1);
3888                                 token = read32 (ip + 2);
3889                                 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
3890                                 ins->cil_code = ip;
3891                                 *sp++ = ins;
3892                                 ip += 6;
3893                                 inline_costs += 10 * num_calls++;
3894                                 break;
3895                         case CEE_MONO_VTADDR:
3896                                 CHECK_STACK (1);
3897                                 --sp;
3898                                 MONO_INST_NEW (cfg, ins, OP_VTADDR);
3899                                 ins->cil_code = ip;
3900                                 ins->type = STACK_MP;
3901                                 ins->inst_left = *sp;
3902                                 *sp++ = ins;
3903                                 ip += 2;
3904                                 break;
3905                         case CEE_MONO_NEWOBJ: {
3906                                 MonoInst *iargs [2];
3907                                 int temp;
3908                                 CHECK_STACK_OVF (1);
3909                                 token = read32 (ip + 2);
3910                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
3911                                 mono_class_init (klass);
3912                                 NEW_DOMAINCONST (cfg, iargs [0]);
3913                                 NEW_CLASSCONST (cfg, iargs [1], klass);
3914                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
3915                                 NEW_TEMPLOAD (cfg, *sp, temp);
3916                                 sp++;
3917                                 ip += 6;
3918                                 inline_costs += 10 * num_calls++;
3919                                 break;
3920                         }
3921                         case CEE_MONO_OBJADDR:
3922                                 CHECK_STACK (1);
3923                                 --sp;
3924                                 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
3925                                 ins->cil_code = ip;
3926                                 ins->type = STACK_MP;
3927                                 ins->inst_left = *sp;
3928                                 *sp++ = ins;
3929                                 ip += 2;
3930                                 break;
3931                         case CEE_MONO_LDNATIVEOBJ:
3932                                 CHECK_STACK (1);
3933                                 token = read32 (ip + 2);
3934                                 klass = mono_method_get_wrapper_data (method, token);
3935                                 g_assert (klass->valuetype);
3936                                 mono_class_init (klass);
3937                                 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
3938                                 sp [-1] = ins;
3939                                 ip += 6;
3940                                 break;
3941                         case CEE_MONO_RETOBJ:
3942                                 g_assert (cfg->ret);
3943                                 g_assert (method->signature->pinvoke); 
3944                                 CHECK_STACK (1);
3945                                 --sp;
3946                                 
3947                                 token = read32 (ip + 2);    
3948                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
3949
3950                                 NEW_RETLOADA (cfg, ins);
3951                                 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE);
3952                                 
3953                                 if (sp != stack_start)
3954                                         goto unverified;
3955                                 
3956                                 MONO_INST_NEW (cfg, ins, CEE_BR);
3957                                 ins->cil_code = ip;
3958                                 ins->inst_target_bb = end_bblock;
3959                                 MONO_ADD_INS (bblock, ins);
3960                                 link_bblock (cfg, bblock, end_bblock);
3961                                 start_new_bblock = 1;
3962                                 ip += 6;
3963                                 break;
3964                         default:
3965                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
3966                                 break;
3967                         }
3968                         break;
3969                 }
3970                 case CEE_PREFIX1: {
3971                         switch (ip [1]) {
3972                         case CEE_ARGLIST:
3973                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
3974                                 break;
3975                         case CEE_CEQ:
3976                         case CEE_CGT:
3977                         case CEE_CGT_UN:
3978                         case CEE_CLT:
3979                         case CEE_CLT_UN: {
3980                                 MonoInst *cmp;
3981                                 CHECK_STACK (2);
3982                                 MONO_INST_NEW (cfg, cmp, 256 + ip [1]);
3983                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
3984                                 sp -= 2;
3985                                 cmp->inst_i0 = sp [0];
3986                                 cmp->inst_i1 = sp [1];
3987                                 cmp->cil_code = ip;
3988                                 type_from_op (cmp);
3989                                 CHECK_TYPE (cmp);
3990                                 cmp->opcode = OP_COMPARE;
3991                                 ins->cil_code = ip;
3992                                 ins->type = STACK_I4;
3993                                 ins->inst_i0 = cmp;
3994                                 *sp++ = ins;
3995                                 ip += 2;
3996                                 break;
3997                         }
3998                         case CEE_LDFTN: {
3999                                 MonoInst *argconst;
4000                                 int temp;
4001
4002                                 CHECK_STACK_OVF (1);
4003                                 n = read32 (ip + 2);
4004                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
4005                                         cmethod = mono_method_get_wrapper_data (method, n);
4006                                 else {
4007                                         cmethod = mono_get_method (image, n, NULL);
4008
4009                                         /*
4010                                          * We can't do this in mono_ldftn, since it is used in
4011                                          * the synchronized wrapper, leading to an infinite loop.
4012                                          */
4013                                         if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
4014                                                 cmethod = mono_marshal_get_synchronized_wrapper (cmethod);
4015                                 }
4016
4017                                 mono_class_init (cmethod->klass);
4018                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4019
4020                                 NEW_METHODCONST (cfg, argconst, cmethod);
4021                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
4022                                 NEW_TEMPLOAD (cfg, *sp, temp);
4023                                 sp ++;
4024                                 
4025                                 ip += 6;
4026                                 inline_costs += 10 * num_calls++;
4027                                 break;
4028                         }
4029                         case CEE_LDVIRTFTN: {
4030                                 MonoInst *args [2];
4031                                 int temp;
4032
4033                                 CHECK_STACK (1);
4034                                 n = read32 (ip + 2);
4035                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
4036                                         cmethod = mono_method_get_wrapper_data (method, n);
4037                                 else
4038                                         cmethod = mono_get_method (image, n, NULL);
4039
4040                                 mono_class_init (cmethod->klass);
4041                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4042
4043                                 --sp;
4044                                 args [0] = *sp;
4045                                 NEW_METHODCONST (cfg, args [1], cmethod);
4046                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
4047                                 NEW_TEMPLOAD (cfg, *sp, temp);
4048                                 sp ++;
4049
4050                                 ip += 6;
4051                                 inline_costs += 10 * num_calls++;
4052                                 break;
4053                         }
4054                         case CEE_LDARG:
4055                                 CHECK_STACK_OVF (1);
4056                                 NEW_ARGLOAD (cfg, ins, read16 (ip + 2));
4057                                 ins->cil_code = ip;
4058                                 *sp++ = ins;
4059                                 ip += 4;
4060                                 break;
4061                         case CEE_LDARGA:
4062                                 CHECK_STACK_OVF (1);
4063                                 NEW_ARGLOADA (cfg, ins, read16 (ip + 2));
4064                                 ins->cil_code = ip;
4065                                 *sp++ = ins;
4066                                 ip += 4;
4067                                 break;
4068                         case CEE_STARG:
4069                                 CHECK_STACK (1);
4070                                 --sp;
4071                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4072                                 n = read16 (ip + 2);
4073                                 NEW_ARGSTORE (cfg, ins, n, *sp);
4074                                 ins->cil_code = ip;
4075                                 if (ins->opcode == CEE_STOBJ) {
4076                                         NEW_ARGLOADA (cfg, ins, n);
4077                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
4078                                 } else
4079                                         MONO_ADD_INS (bblock, ins);
4080                                 ip += 4;
4081                                 break;
4082                         case CEE_LDLOC:
4083                                 CHECK_STACK_OVF (1);
4084                                 NEW_LOCLOAD (cfg, ins, read16 (ip + 2));
4085                                 ins->cil_code = ip;
4086                                 *sp++ = ins;
4087                                 ip += 4;
4088                                 break;
4089                         case CEE_LDLOCA:
4090                                 CHECK_STACK_OVF (1);
4091                                 NEW_LOCLOADA (cfg, ins, read16 (ip + 2));
4092                                 ins->cil_code = ip;
4093                                 *sp++ = ins;
4094                                 ip += 4;
4095                                 break;
4096                         case CEE_STLOC:
4097                                 CHECK_STACK (1);
4098                                 --sp;
4099                                 n = read16 (ip + 2);
4100                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4101                                 NEW_LOCSTORE (cfg, ins, n, *sp);
4102                                 ins->cil_code = ip;
4103                                 if (ins->opcode == CEE_STOBJ) {
4104                                         NEW_LOCLOADA (cfg, ins, n);
4105                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
4106                                 } else
4107                                         MONO_ADD_INS (bblock, ins);
4108                                 ip += 4;
4109                                 inline_costs += 1;
4110                                 break;
4111                         case CEE_LOCALLOC:
4112                                 CHECK_STACK (1);
4113                                 --sp;
4114                                 if (sp != stack_start) 
4115                                         goto unverified;
4116                                 MONO_INST_NEW (cfg, ins, 256 + ip [1]);
4117                                 ins->inst_left = *sp;
4118                                 ins->cil_code = ip;
4119
4120                                 if (header->init_locals)
4121                                         ins->flags |= MONO_INST_INIT;
4122
4123                                 *sp++ = ins;
4124                                 ip += 2;
4125                                 /* FIXME: set init flag if locals init is set in this method */
4126                                 break;
4127                         case CEE_ENDFILTER: {
4128                                 MonoExceptionClause *clause, *nearest;
4129                                 int cc, nearest_num;
4130
4131                                 CHECK_STACK (1);
4132                                 --sp;
4133                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
4134                                         goto unverified;
4135                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
4136                                 ins->inst_left = *sp;
4137                                 ins->cil_code = ip;
4138                                 MONO_ADD_INS (bblock, ins);
4139                                 start_new_bblock = 1;
4140                                 ip += 2;
4141
4142                                 nearest = NULL;
4143                                 for (cc = 0; cc < header->num_clauses; ++cc) {
4144                                         clause = &header->clauses [cc];
4145                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
4146                                             (!nearest || (clause->token_or_filter > nearest->token_or_filter))) {
4147                                                 nearest = clause;
4148                                                 nearest_num = cc;
4149                                         }
4150                                 }
4151                                 g_assert (nearest);
4152                                 filter_lengths [nearest_num] = (ip - header->code) -  nearest->token_or_filter;
4153
4154                                 break;
4155                         }
4156                         case CEE_UNALIGNED_:
4157                                 ins_flag |= MONO_INST_UNALIGNED;
4158                                 ip += 3;
4159                                 break;
4160                         case CEE_VOLATILE_:
4161                                 ins_flag |= MONO_INST_VOLATILE;
4162                                 ip += 2;
4163                                 break;
4164                         case CEE_TAIL_:
4165                                 ins_flag |= MONO_INST_TAILCALL;
4166                                 ip += 2;
4167                                 break;
4168                         case CEE_INITOBJ:
4169                                 CHECK_STACK (1);
4170                                 --sp;
4171                                 token = read32 (ip + 2);
4172                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
4173                                         klass = mono_method_get_wrapper_data (method, token);
4174                                 else
4175                                         klass = mono_class_get (image, token);
4176                                 handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
4177                                 ip += 6;
4178                                 inline_costs += 1;
4179                                 break;
4180                         case CEE_CPBLK:
4181                         case CEE_INITBLK: {
4182                                 MonoInst *iargs [3];
4183                                 CHECK_STACK (3);
4184                                 sp -= 3;
4185                                 iargs [0] = sp [0];
4186                                 iargs [1] = sp [1];
4187                                 iargs [2] = sp [2];
4188                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4189                                 if (ip [1] == CEE_CPBLK) {
4190                                         mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
4191                                 } else {
4192                                         mono_emit_jit_icall (cfg, bblock, helper_memset, iargs, ip);
4193                                 }
4194                                 ip += 2;
4195                                 inline_costs += 1;
4196                                 break;
4197                         }
4198                         case CEE_RETHROW: {
4199                                 MonoInst *load;
4200                                 /* FIXME: check we are in a catch handler */
4201                                 NEW_TEMPLOAD (cfg, load, cfg->exvar->inst_c0);
4202                                 load->cil_code = ip;
4203                                 MONO_INST_NEW (cfg, ins, CEE_THROW);
4204                                 ins->inst_left = load;
4205                                 ins->cil_code = ip;
4206                                 MONO_ADD_INS (bblock, ins);
4207                                 sp = stack_start;
4208                                 start_new_bblock = 1;
4209                                 ip += 2;
4210                                 break;
4211                         }
4212                         case CEE_SIZEOF:
4213                                 CHECK_STACK_OVF (1);
4214                                 token = read32 (ip + 2);
4215                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
4216                                         MonoType *type = mono_type_create_from_typespec (image, token);
4217                                         token = mono_type_size (type, &align);
4218                                         mono_metadata_free_type (type);
4219                                 } else {
4220                                         MonoClass *szclass = mono_class_get (image, token);
4221                                         mono_class_init (szclass);
4222                                         token = mono_class_value_size (szclass, &align);
4223                                 }
4224                                 NEW_ICONST (cfg, ins, token);
4225                                 ins->cil_code = ip;
4226                                 *sp++= ins;
4227                                 ip += 6;
4228                                 break;
4229                         case CEE_REFANYTYPE:
4230                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
4231                                 break;
4232                         default:
4233                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
4234                         }
4235                         break;
4236                 }
4237                 default:
4238                         g_error ("opcode 0x%02x not handled", *ip);
4239                 }
4240         }
4241         if (start_new_bblock != 1)
4242                 goto unverified;
4243
4244         bblock->cil_length = ip - bblock->cil_code;
4245         bblock->next_bb = end_bblock;
4246         link_bblock (cfg, bblock, end_bblock);
4247
4248         if (cfg->method == method && cfg->domainvar) {
4249                 MonoCallInst *call;
4250                 MonoInst *store;
4251
4252                 MONO_INST_NEW_CALL (cfg, call, CEE_CALL);
4253                 call->signature = helper_sig_domain_get;
4254                 call->inst.type = STACK_PTR;
4255                 call->fptr = mono_domain_get;
4256                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, (MonoInst*)call);
4257                 
4258                 MONO_ADD_INS (init_localsbb, store);
4259         }
4260
4261         if (header->init_locals) {
4262                 MonoInst *store;
4263                 for (i = 0; i < header->num_locals; ++i) {
4264                         int t = header->locals [i]->type;
4265                         if (t == MONO_TYPE_VALUETYPE && header->locals [i]->data.klass->enumtype)
4266                                 t = header->locals [i]->data.klass->enum_basetype->type;
4267                         /* FIXME: use initobj for valuetypes, handle pointers, long, float. */
4268                         if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
4269                                 NEW_ICONST (cfg, ins, 0);
4270                                 NEW_LOCSTORE (cfg, store, i, ins);
4271                                 MONO_ADD_INS (init_localsbb, store);
4272                         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
4273                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
4274                                 ins->type = STACK_I8;
4275                                 ins->inst_l = 0;
4276                                 NEW_LOCSTORE (cfg, store, i, ins);
4277                                 MONO_ADD_INS (init_localsbb, store);
4278                         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
4279                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
4280                                 ins->type = STACK_R8;
4281                                 ins->inst_p0 = (void*)&r8_0;
4282                                 NEW_LOCSTORE (cfg, store, i, ins);
4283                                 MONO_ADD_INS (init_localsbb, store);
4284                         } else if (t == MONO_TYPE_VALUETYPE) {
4285                                 NEW_LOCLOADA (cfg, ins, i);
4286                                 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (header->locals [i]), NULL, NULL);
4287                                 break;
4288                         } else {
4289                                 NEW_PCONST (cfg, ins, NULL);
4290                                 NEW_LOCSTORE (cfg, store, i, ins);
4291                                 MONO_ADD_INS (init_localsbb, store);
4292                         }
4293                 }
4294         }
4295
4296         
4297         /* resolve backward branches in the middle of an existing basic block */
4298         for (tmp = bb_recheck; tmp; tmp = tmp->next) {
4299                 bblock = tmp->data;
4300                 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
4301                 tblock = find_previous (bbhash, start_bblock, bblock->cil_code);
4302                 if (tblock != start_bblock) {
4303                         int l;
4304                         split_bblock (cfg, tblock, bblock);
4305                         l = bblock->cil_code - header->code;
4306                         bblock->cil_length = tblock->cil_length - l;
4307                         tblock->cil_length = l;
4308                 } else {
4309                         g_print ("recheck failed.\n");
4310                 }
4311         }
4312
4313         /* we compute regions here, because the length of filter clauses is not known in advance.
4314         * It is computed in the CEE_ENDFILTER case in the above switch statement*/
4315         if (cfg->method == method) {
4316                 MonoBasicBlock *bb;
4317                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4318                         bb->region = mono_find_block_region (cfg, bb->real_offset, filter_lengths);
4319                         if (cfg->verbose_level > 2)
4320                                 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
4321                 }
4322         } else {
4323                 g_hash_table_destroy (bbhash);
4324         }
4325
4326         dont_inline = g_list_remove (dont_inline, method);
4327         return inline_costs;
4328
4329  inline_failure:
4330         if (cfg->method != method) 
4331                 g_hash_table_destroy (bbhash);
4332         dont_inline = g_list_remove (dont_inline, method);
4333         return -1;
4334
4335  unverified:
4336         if (cfg->method != method) 
4337                 g_hash_table_destroy (bbhash);
4338         g_error ("Invalid IL code at IL%04x in %s: %s\n", ip - header->code, 
4339                  mono_method_full_name (method, TRUE), mono_disasm_code_one (NULL, method, ip, NULL));
4340         dont_inline = g_list_remove (dont_inline, method);
4341         return -1;
4342 }
4343
4344 void
4345 mono_print_tree (MonoInst *tree) {
4346         int arity;
4347
4348         if (!tree)
4349                 return;
4350
4351         arity = mono_burg_arity [tree->opcode];
4352
4353         printf (" %s%s", arity?"(":"",  mono_inst_name (tree->opcode));
4354
4355         switch (tree->opcode) {
4356         case OP_ICONST:
4357                 printf ("[%d]", tree->inst_c0);
4358                 break;
4359         case OP_I8CONST:
4360                 printf ("[%lld]", tree->inst_l);
4361                 break;
4362         case OP_R8CONST:
4363                 printf ("[%f]", *(double*)tree->inst_p0);
4364                 break;
4365         case OP_R4CONST:
4366                 printf ("[%f]", *(float*)tree->inst_p0);
4367                 break;
4368         case OP_ARG:
4369         case OP_LOCAL:
4370                 printf ("[%d]", tree->inst_c0);
4371                 break;
4372         case OP_REGOFFSET:
4373                 printf ("[0x%x(%s)]", tree->inst_offset, mono_arch_regname (tree->inst_basereg));
4374                 break;
4375         case OP_REGVAR:
4376                 printf ("[%s]", mono_arch_regname (tree->dreg));
4377                 break;
4378         case CEE_NEWARR:
4379                 printf ("[%s]",  tree->inst_newa_class->name);
4380                 mono_print_tree (tree->inst_newa_len);
4381                 break;
4382         case CEE_CALL:
4383         case CEE_CALLVIRT:
4384         case OP_FCALL:
4385         case OP_FCALLVIRT:
4386         case OP_LCALL:
4387         case OP_LCALLVIRT:
4388         case OP_VCALL:
4389         case OP_VCALLVIRT:
4390         case OP_VOIDCALL:
4391         case OP_VOIDCALLVIRT: {
4392                 MonoCallInst *call = (MonoCallInst*)tree;
4393                 if (call->method)
4394                         printf ("[%s]", call->method->name);
4395                 break;
4396         }
4397         case OP_PHI: {
4398                 int i;
4399                 printf ("[%d (", tree->inst_c0);
4400                 for (i = 0; i < tree->inst_phi_args [0]; i++) {
4401                         if (i)
4402                                 printf (", ");
4403                         printf ("%d", tree->inst_phi_args [i + 1]);
4404                 }
4405                 printf (")]");
4406                 break;
4407         }
4408         case OP_RENAME:
4409         case OP_RETARG:
4410         case CEE_NOP:
4411         case CEE_JMP:
4412         case CEE_BREAK:
4413                 break;
4414         case CEE_BR:
4415                 printf ("[B%d]", tree->inst_target_bb->block_num);
4416                 break;
4417         case CEE_SWITCH:
4418         case CEE_ISINST:
4419         case CEE_CASTCLASS:
4420         case OP_OUTARG:
4421         case OP_CALL_REG:
4422         case OP_FCALL_REG:
4423         case OP_LCALL_REG:
4424         case OP_VCALL_REG:
4425         case OP_VOIDCALL_REG:
4426                 mono_print_tree (tree->inst_left);
4427                 break;
4428         case CEE_BNE_UN:
4429         case CEE_BEQ:
4430         case CEE_BLT:
4431         case CEE_BLT_UN:
4432         case CEE_BGT:
4433         case CEE_BGT_UN:
4434         case CEE_BGE:
4435         case CEE_BGE_UN:
4436         case CEE_BLE:
4437         case CEE_BLE_UN:
4438                 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
4439                 mono_print_tree (tree->inst_left);
4440                 break;
4441         default:
4442                 if (arity) {
4443                         mono_print_tree (tree->inst_left);
4444                         if (arity > 1)
4445                                 mono_print_tree (tree->inst_right);
4446                 }
4447                 break;
4448         }
4449
4450         if (arity)
4451                 printf (")");
4452 }
4453
4454 static void
4455 create_helper_signature (void)
4456 {
4457         /* FIXME: set call conv */
4458         /* MonoArray * mono_array_new (MonoDomain *domain, MonoClass *klass, gint32 len) */
4459         helper_sig_newarr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4460         helper_sig_newarr->params [0] = helper_sig_newarr->params [1] = &mono_defaults.int_class->byval_arg;
4461         helper_sig_newarr->ret = &mono_defaults.object_class->byval_arg;
4462         helper_sig_newarr->params [2] = &mono_defaults.int32_class->byval_arg;
4463         helper_sig_newarr->pinvoke = 1;
4464
4465         /* MonoObject * mono_object_new (MonoDomain *domain, MonoClass *klass) */
4466         helper_sig_object_new = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4467         helper_sig_object_new->params [0] = helper_sig_object_new->params [1] = &mono_defaults.int_class->byval_arg;
4468         helper_sig_object_new->ret = &mono_defaults.object_class->byval_arg;
4469         helper_sig_object_new->pinvoke = 1;
4470
4471         /* void* mono_method_compile (MonoMethod*) */
4472         helper_sig_compile = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4473         helper_sig_compile->params [0] = helper_sig_compile->ret = &mono_defaults.int_class->byval_arg;
4474         helper_sig_compile->pinvoke = 1;
4475
4476         /* void* mono_ldvirtfn (MonoObject *, MonoMethod*) */
4477         helper_sig_compile_virt = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4478         helper_sig_compile_virt->params [0] = &mono_defaults.object_class->byval_arg;
4479         helper_sig_compile_virt->params [1] = helper_sig_compile_virt->ret = &mono_defaults.int_class->byval_arg;
4480         helper_sig_compile_virt->pinvoke = 1;
4481
4482         /* MonoString* mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 str_index) */
4483         helper_sig_ldstr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4484         helper_sig_ldstr->params [0] = helper_sig_ldstr->params [1] = &mono_defaults.int_class->byval_arg;
4485         helper_sig_ldstr->params [2] = &mono_defaults.int32_class->byval_arg;
4486         helper_sig_ldstr->ret = &mono_defaults.object_class->byval_arg;
4487         helper_sig_ldstr->pinvoke = 1;
4488
4489         /* MonoDomain *mono_domain_get (void) */
4490         helper_sig_domain_get = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4491         helper_sig_domain_get->ret = &mono_defaults.int_class->byval_arg;
4492         helper_sig_domain_get->pinvoke = 1;
4493
4494         /* void* stelem_ref (MonoArray *, int index, MonoObject *) */
4495         helper_sig_stelem_ref = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4496         helper_sig_stelem_ref->params [0] = &mono_defaults.array_class->byval_arg;
4497         helper_sig_stelem_ref->params [1] = &mono_defaults.int32_class->byval_arg;
4498         helper_sig_stelem_ref->params [2] = &mono_defaults.object_class->byval_arg;
4499         helper_sig_stelem_ref->ret = &mono_defaults.void_class->byval_arg;
4500         helper_sig_stelem_ref->pinvoke = 1;
4501
4502         /* long amethod (long, long) */
4503         helper_sig_long_long_long = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4504         helper_sig_long_long_long->params [0] = helper_sig_long_long_long->params [1] = 
4505                 &mono_defaults.int64_class->byval_arg;
4506         helper_sig_long_long_long->ret = &mono_defaults.int64_class->byval_arg;
4507         helper_sig_long_long_long->pinvoke = 1;
4508
4509         /* object  amethod (intptr) */
4510         helper_sig_obj_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4511         helper_sig_obj_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4512         helper_sig_obj_ptr->ret = &mono_defaults.object_class->byval_arg;
4513         helper_sig_obj_ptr->pinvoke = 1;
4514
4515         /* void amethod (intptr) */
4516         helper_sig_void_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4517         helper_sig_void_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4518         helper_sig_void_ptr->ret = &mono_defaults.void_class->byval_arg;
4519         helper_sig_void_ptr->pinvoke = 1;
4520
4521         /* void amethod (MonoObject *obj) */
4522         helper_sig_void_obj = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4523         helper_sig_void_obj->params [0] = &mono_defaults.object_class->byval_arg;
4524         helper_sig_void_obj->ret = &mono_defaults.void_class->byval_arg;
4525         helper_sig_void_obj->pinvoke = 1;
4526
4527         /* intptr amethod (void) */
4528         helper_sig_ptr_void = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4529         helper_sig_ptr_void->ret = &mono_defaults.int_class->byval_arg;
4530         helper_sig_ptr_void->pinvoke = 1;
4531
4532         /* void  amethod (intptr, intptr) */
4533         helper_sig_void_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4534         helper_sig_void_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4535         helper_sig_void_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
4536         helper_sig_void_ptr_ptr->ret = &mono_defaults.void_class->byval_arg;
4537         helper_sig_void_ptr_ptr->pinvoke = 1;
4538
4539         /* void  amethod (intptr, intptr, intptr) */
4540         helper_sig_void_ptr_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4541         helper_sig_void_ptr_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4542         helper_sig_void_ptr_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
4543         helper_sig_void_ptr_ptr_ptr->params [2] = &mono_defaults.int_class->byval_arg;
4544         helper_sig_void_ptr_ptr_ptr->ret = &mono_defaults.void_class->byval_arg;
4545         helper_sig_void_ptr_ptr_ptr->pinvoke = 1;
4546
4547         /* intptr  amethod (intptr, intptr) */
4548         helper_sig_ptr_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4549         helper_sig_ptr_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4550         helper_sig_ptr_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
4551         helper_sig_ptr_ptr_ptr->ret = &mono_defaults.int_class->byval_arg;
4552         helper_sig_ptr_ptr_ptr->pinvoke = 1;
4553
4554         /* IntPtr  amethod (object) */
4555         helper_sig_ptr_obj = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4556         helper_sig_ptr_obj->params [0] = &mono_defaults.object_class->byval_arg;
4557         helper_sig_ptr_obj->ret = &mono_defaults.int_class->byval_arg;
4558         helper_sig_ptr_obj->pinvoke = 1;
4559
4560         /* long amethod (long, guint32) */
4561         helper_sig_long_long_int = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4562         helper_sig_long_long_int->params [0] = &mono_defaults.int64_class->byval_arg;
4563         helper_sig_long_long_int->params [1] = &mono_defaults.int32_class->byval_arg;
4564         helper_sig_long_long_int->ret = &mono_defaults.int64_class->byval_arg;
4565         helper_sig_long_long_int->pinvoke = 1;
4566
4567         /* ulong amethod (double) */
4568         helper_sig_ulong_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4569         helper_sig_ulong_double->params [0] = &mono_defaults.double_class->byval_arg;
4570         helper_sig_ulong_double->ret = &mono_defaults.uint64_class->byval_arg;
4571         helper_sig_ulong_double->pinvoke = 1;
4572
4573         /* long amethod (double) */
4574         helper_sig_long_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4575         helper_sig_long_double->params [0] = &mono_defaults.double_class->byval_arg;
4576         helper_sig_long_double->ret = &mono_defaults.int64_class->byval_arg;
4577         helper_sig_long_double->pinvoke = 1;
4578
4579         /* uint amethod (double) */
4580         helper_sig_uint_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4581         helper_sig_uint_double->params [0] = &mono_defaults.double_class->byval_arg;
4582         helper_sig_uint_double->ret = &mono_defaults.uint32_class->byval_arg;
4583         helper_sig_uint_double->pinvoke = 1;
4584
4585         /* int amethod (double) */
4586         helper_sig_int_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4587         helper_sig_int_double->params [0] = &mono_defaults.double_class->byval_arg;
4588         helper_sig_int_double->ret = &mono_defaults.int32_class->byval_arg;
4589         helper_sig_int_double->pinvoke = 1;
4590
4591         /* void  initobj (intptr, int size) */
4592         helper_sig_initobj = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4593         helper_sig_initobj->params [0] = &mono_defaults.int_class->byval_arg;
4594         helper_sig_initobj->params [1] = &mono_defaults.int32_class->byval_arg;
4595         helper_sig_initobj->ret = &mono_defaults.void_class->byval_arg;
4596         helper_sig_initobj->pinvoke = 1;
4597
4598         /* void  memcpy (intptr, intptr, int size) */
4599         helper_sig_memcpy = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4600         helper_sig_memcpy->params [0] = &mono_defaults.int_class->byval_arg;
4601         helper_sig_memcpy->params [1] = &mono_defaults.int_class->byval_arg;
4602         helper_sig_memcpy->params [2] = &mono_defaults.int32_class->byval_arg;
4603         helper_sig_memcpy->ret = &mono_defaults.void_class->byval_arg;
4604         helper_sig_memcpy->pinvoke = 1;
4605
4606         /* void  memset (intptr, int val, int size) */
4607         helper_sig_memset = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4608         helper_sig_memset->params [0] = &mono_defaults.int_class->byval_arg;
4609         helper_sig_memset->params [1] = &mono_defaults.int32_class->byval_arg;
4610         helper_sig_memset->params [2] = &mono_defaults.int32_class->byval_arg;
4611         helper_sig_memset->ret = &mono_defaults.void_class->byval_arg;
4612         helper_sig_memset->pinvoke = 1;
4613 }
4614
4615 static GHashTable *jit_icall_hash_name = NULL;
4616 static GHashTable *jit_icall_hash_addr = NULL;
4617
4618 MonoJitICallInfo *
4619 mono_find_jit_icall_by_name (const char *name)
4620 {
4621         g_assert (jit_icall_hash_name);
4622
4623         //printf ("lookup addr %s %p\n", name, g_hash_table_lookup (jit_icall_hash_name, name));
4624         return g_hash_table_lookup (jit_icall_hash_name, name);
4625 }
4626
4627 MonoJitICallInfo *
4628 mono_find_jit_icall_by_addr (gconstpointer addr)
4629 {
4630         g_assert (jit_icall_hash_addr);
4631
4632         return g_hash_table_lookup (jit_icall_hash_addr, (gpointer)addr);
4633 }
4634
4635 MonoJitICallInfo *
4636 mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save)
4637 {
4638         MonoJitICallInfo *info;
4639         MonoMethod *wrapper;
4640         char *n;
4641         
4642         g_assert (func);
4643         g_assert (name);
4644
4645         if (!jit_icall_hash_name) {
4646                 jit_icall_hash_name = g_hash_table_new (g_str_hash, g_str_equal);
4647                 jit_icall_hash_addr = g_hash_table_new (NULL, NULL);
4648         }
4649
4650         if (g_hash_table_lookup (jit_icall_hash_name, name)) {
4651                 g_warning ("jit icall already defined \"%s\"\n", name);
4652                 g_assert_not_reached ();
4653         }
4654
4655         info = g_new (MonoJitICallInfo, 1);
4656         
4657         info->name = g_strdup (name);
4658         info->func = func;
4659         info->sig = sig;
4660                 
4661         if (is_save
4662 #ifdef MONO_USE_EXC_TABLES
4663             || mono_arch_has_unwind_info (func)
4664 #endif
4665             ) {
4666                 info->wrapper = func;
4667         } else {
4668                 g_assert (sig);
4669                 n = g_strdup_printf ("__icall_wrapper_%s", name);       
4670                 wrapper = mono_marshal_get_icall_wrapper (sig, n, func);
4671                 info->wrapper = mono_jit_compile_method (wrapper);
4672                 g_free (n);
4673         }
4674
4675         g_hash_table_insert (jit_icall_hash_name, info->name, info);
4676         g_hash_table_insert (jit_icall_hash_addr, (gpointer)func, info);
4677         if (func != info->wrapper)
4678                 g_hash_table_insert (jit_icall_hash_addr, (gpointer)info->wrapper, info);
4679
4680         return info;
4681 }
4682
4683 static GHashTable *emul_opcode_hash = NULL;
4684
4685 static MonoJitICallInfo *
4686 mono_find_jit_opcode_emulation (int opcode)
4687 {
4688         if  (emul_opcode_hash)
4689                 return g_hash_table_lookup (emul_opcode_hash, (gpointer)opcode);
4690         else
4691                 return NULL;
4692 }
4693
4694 void
4695 mono_register_opcode_emulation (int opcode, MonoMethodSignature *sig, gpointer func)
4696 {
4697         MonoJitICallInfo *info;
4698         char *name;
4699
4700         if (!emul_opcode_hash)
4701                 emul_opcode_hash = g_hash_table_new (NULL, NULL);
4702
4703         g_assert (!sig->hasthis);
4704         g_assert (sig->param_count < 3);
4705
4706         name = g_strdup_printf ("__emulate_%s",  mono_inst_name (opcode));
4707
4708         info = mono_register_jit_icall (func, name, sig, FALSE);
4709
4710         g_free (name);
4711
4712         g_hash_table_insert (emul_opcode_hash, (gpointer)opcode, info);
4713 }
4714
4715 static void
4716 decompose_foreach (MonoInst *tree, gpointer data) 
4717 {
4718         static MonoJitICallInfo *newarr_info = NULL;
4719
4720         switch (tree->opcode) {
4721         case CEE_NEWARR: {
4722                 MonoCompile *cfg = data;
4723                 MonoInst *iargs [3];
4724
4725                 NEW_DOMAINCONST (cfg, iargs [0]);
4726                 NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
4727                 iargs [2] = tree->inst_newa_len;
4728
4729                 if (!newarr_info) {
4730                         newarr_info =  mono_find_jit_icall_by_addr (mono_array_new);
4731                         g_assert (newarr_info);
4732                 }
4733
4734                 mono_emulate_opcode (cfg, tree, iargs, newarr_info);
4735                 break;
4736         }
4737
4738         default:
4739                 break;
4740         }
4741 }
4742
4743 void
4744 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
4745
4746         switch (mono_burg_arity [tree->opcode]) {
4747         case 0: break;
4748         case 1: 
4749                 mono_inst_foreach (tree->inst_left, func, data);
4750                 break;
4751         case 2: 
4752                 mono_inst_foreach (tree->inst_left, func, data);
4753                 mono_inst_foreach (tree->inst_right, func, data);
4754                 break;
4755         default:
4756                 g_assert_not_reached ();
4757         }
4758         func (tree, data);
4759 }
4760
4761 #if 0
4762 static void
4763 mono_print_bb_code (MonoBasicBlock *bb) {
4764         if (bb->code) {
4765                 MonoInst *c = bb->code;
4766                 while (c) {
4767                         mono_print_tree (c);
4768                         g_print ("\n");
4769                         c = c->next;
4770                 }
4771         }
4772 }
4773 #endif
4774
4775 static void
4776 print_dfn (MonoCompile *cfg) {
4777         int i, j;
4778         char *code;
4779         MonoBasicBlock *bb;
4780
4781         g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
4782
4783         for (i = 0; i < cfg->num_bblocks; ++i) {
4784                 bb = cfg->bblocks [i];
4785                 if (bb->cil_code) {
4786                         char* code1, *code2;
4787                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
4788                         if (bb->last_ins->cil_code)
4789                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
4790                         else
4791                                 code2 = g_strdup ("");
4792
4793                         code1 [strlen (code1) - 1] = 0;
4794                         code = g_strdup_printf ("%s -> %s", code1, code2);
4795                         g_free (code1);
4796                         g_free (code2);
4797                 } else
4798                         code = g_strdup ("\n");
4799                 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
4800                 if (bb->code) {
4801                         MonoInst *c = bb->code;
4802                         while (c) {
4803                                 mono_print_tree (c);
4804                                 g_print ("\n");
4805                                 c = c->next;
4806                         }
4807                 } else {
4808
4809                 }
4810
4811                 g_print ("\tprev:");
4812                 for (j = 0; j < bb->in_count; ++j) {
4813                         g_print (" BB%d", bb->in_bb [j]->block_num);
4814                 }
4815                 g_print ("\t\tsucc:");
4816                 for (j = 0; j < bb->out_count; ++j) {
4817                         g_print (" BB%d", bb->out_bb [j]->block_num);
4818                 }
4819                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
4820
4821                 if (bb->idom)
4822                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
4823
4824                 if (bb->dominators)
4825                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
4826                 if (bb->dfrontier)
4827                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
4828                 g_free (code);
4829         }
4830
4831         g_print ("\n");
4832 }
4833
4834 /*
4835  * returns the offset used by spillvar. It allocates a new
4836  * spill variable if necessary. 
4837  */
4838 int
4839 mono_spillvar_offset (MonoCompile *cfg, int spillvar)
4840 {
4841         MonoSpillInfo **si, *info;
4842         int i = 0;
4843
4844         si = &cfg->spill_info; 
4845         
4846         while (i <= spillvar) {
4847
4848                 if (!*si) {
4849                         *si = info = mono_mempool_alloc (cfg->mempool, sizeof (MonoSpillInfo));
4850                         info->next = NULL;
4851                         cfg->stack_offset -= sizeof (gpointer);
4852                         info->offset = cfg->stack_offset;
4853                 }
4854
4855                 if (i == spillvar)
4856                         return (*si)->offset;
4857
4858                 i++;
4859                 si = &(*si)->next;
4860         }
4861
4862         g_assert_not_reached ();
4863         return 0;
4864 }
4865
4866 void
4867 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
4868 {
4869         inst->next = NULL;
4870         if (bb->last_ins) {
4871                 g_assert (bb->code);
4872                 bb->last_ins->next = inst;
4873                 bb->last_ins = inst;
4874         } else {
4875                 bb->last_ins = bb->code = inst;
4876         }
4877 }
4878
4879 void
4880 mono_destroy_compile (MonoCompile *cfg)
4881 {
4882         //mono_mempool_stats (cfg->mempool);
4883         g_hash_table_destroy (cfg->bb_hash);
4884         if (cfg->rs)
4885                 mono_regstate_free (cfg->rs);
4886         mono_mempool_destroy (cfg->mempool);
4887         g_list_free (cfg->ldstr_list);
4888
4889         g_free (cfg->varinfo);
4890         g_free (cfg->vars);
4891         g_free (cfg);
4892 }
4893
4894 gpointer 
4895 mono_get_lmf_addr (void)
4896 {
4897         MonoJitTlsData *jit_tls;        
4898
4899         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
4900                 return &jit_tls->lmf;
4901
4902         g_assert_not_reached ();
4903         return NULL;
4904 }
4905
4906 /**
4907  * mono_thread_abort:
4908  * @obj: exception object
4909  *
4910  * abort the thread, print exception information and stack trace
4911  */
4912 static void
4913 mono_thread_abort (MonoObject *obj)
4914 {
4915         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
4916         
4917         g_free (jit_tls);
4918
4919         ExitThread (-1);
4920 }
4921
4922 static void
4923 mono_thread_start_cb (guint32 tid, gpointer stack_start, gpointer func)
4924 {
4925         MonoJitTlsData *jit_tls;
4926         MonoLMF *lmf;
4927
4928         jit_tls = g_new0 (MonoJitTlsData, 1);
4929
4930         TlsSetValue (mono_jit_tls_id, jit_tls);
4931
4932         jit_tls->abort_func = mono_thread_abort;
4933         jit_tls->end_of_stack = stack_start;
4934
4935         lmf = g_new0 (MonoLMF, 1);
4936         lmf->ebp = -1;
4937
4938         jit_tls->lmf = lmf;
4939 }
4940
4941 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
4942
4943 static void
4944 mono_thread_abort_dummy (MonoObject *obj)
4945 {
4946   if (mono_thread_attach_aborted_cb)
4947     mono_thread_attach_aborted_cb (obj);
4948   else
4949     mono_thread_abort (obj);
4950 }
4951
4952 static void
4953 mono_thread_attach_cb (guint32 tid, gpointer stack_start)
4954 {
4955         MonoJitTlsData *jit_tls;
4956         MonoLMF *lmf;
4957
4958         jit_tls = g_new0 (MonoJitTlsData, 1);
4959
4960         TlsSetValue (mono_jit_tls_id, jit_tls);
4961
4962         jit_tls->abort_func = mono_thread_abort_dummy;
4963         jit_tls->end_of_stack = stack_start;
4964
4965         lmf = g_new0 (MonoLMF, 1);
4966         lmf->ebp = -1;
4967
4968         jit_tls->lmf = lmf;
4969 }
4970
4971 void
4972 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
4973 {
4974         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
4975
4976         ji->ip.i = ip;
4977         ji->type = type;
4978         ji->data.target = target;
4979         ji->next = cfg->patch_info;
4980
4981         cfg->patch_info = ji;
4982 }
4983
4984 void
4985 mono_remove_patch_info (MonoCompile *cfg, int ip)
4986 {
4987         MonoJumpInfo **ji = &cfg->patch_info;
4988
4989         while (*ji) {
4990                 if ((*ji)->ip.i == ip)
4991                         *ji = (*ji)->next;
4992                 else
4993                         ji = &((*ji)->next);
4994         }
4995 }
4996
4997 static void
4998 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
4999         MonoJitICallInfo *info;
5000
5001         switch (mono_burg_arity [tree->opcode]) {
5002         case 0: break;
5003         case 1: 
5004                 dec_foreach (tree->inst_left, cfg);
5005
5006                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
5007                         MonoInst *iargs [2];
5008                 
5009                         iargs [0] = tree->inst_left;
5010
5011                         mono_emulate_opcode (cfg, tree, iargs, info);
5012                         return;
5013                 }
5014
5015                 break;
5016         case 2: 
5017                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
5018                         MonoInst *iargs [2];
5019                 
5020                         iargs [0] = tree->inst_i0;
5021                         iargs [1] = tree->inst_i1;
5022                 
5023                         mono_emulate_opcode (cfg, tree, iargs, info);
5024
5025                         dec_foreach (iargs [0], cfg);
5026                         dec_foreach (iargs [1], cfg);
5027                         return;
5028                 } else {
5029                         dec_foreach (tree->inst_left, cfg);
5030                         dec_foreach (tree->inst_right, cfg);
5031                 }
5032                 break;
5033         default:
5034                 g_assert_not_reached ();
5035         }
5036         decompose_foreach (tree, cfg);
5037 }
5038
5039 static void
5040 decompose_pass (MonoCompile *cfg) {
5041         MonoBasicBlock *bb;
5042
5043         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5044                 MonoInst *tree;
5045                 cfg->cbb = bb;
5046                 cfg->prev_ins = NULL;
5047                 for (tree = cfg->cbb->code; tree; tree = tree->next) {
5048                         dec_foreach (tree, cfg);
5049                         cfg->prev_ins = tree;
5050                 }
5051         }
5052 }
5053
5054 static void
5055 nullify_basic_block (MonoBasicBlock *bb) 
5056 {
5057         bb->in_count = 0;
5058         bb->out_count = 0;
5059         bb->in_bb = NULL;
5060         bb->out_bb = NULL;
5061         bb->next_bb = NULL;
5062         bb->code = bb->last_ins = NULL;
5063 }
5064
5065 static void 
5066 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
5067 {
5068         int i, j;
5069
5070         for (i = 0; i < bb->out_count; i++) {
5071                 MonoBasicBlock *ob = bb->out_bb [i];
5072                 for (j = 0; j < ob->in_count; j++) {
5073                         if (ob->in_bb [j] == orig)
5074                                 ob->in_bb [j] = repl;
5075                 }
5076         }
5077
5078 }
5079
5080 static void
5081 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn) 
5082 {
5083         bb->out_count = bbn->out_count;
5084         bb->out_bb = bbn->out_bb;
5085
5086         replace_basic_block (bb, bbn, bb);
5087
5088         if (bb->last_ins) {
5089                 if (bbn->code) {
5090                         bb->last_ins->next = bbn->code;
5091                         bb->last_ins = bbn->last_ins;
5092                 }
5093         } else {
5094                 bb->code = bbn->code;
5095                 bb->last_ins = bbn->last_ins;
5096         }
5097         bb->next_bb = bbn->next_bb;
5098         nullify_basic_block (bbn);
5099 }
5100
5101 static void
5102 optimize_branches (MonoCompile *cfg) {
5103         int changed = FALSE;
5104         MonoBasicBlock *bb, *bbn;
5105
5106         do {
5107                 changed = FALSE;
5108
5109                 /* we skip the entry block (exit is handled specially instead ) */
5110                 for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
5111
5112                         if (bb->out_count == 1) {
5113                                 bbn = bb->out_bb [0];
5114
5115                                 if (bb->region == bbn->region && bb->next_bb == bbn) {
5116                                 /* the block are in sequence anyway ... */
5117
5118                                         /* 
5119                                          * miguel: I do not understand what the test below does, could we
5120                                          * use a macro, or a comment here?  opcode > CEE_BEQ && <= BLT_UN
5121                                          *
5122                                          * It could also test for bb->last_in only once, and the value
5123                                          * could be cached (last_ins->opcode)
5124                                          */
5125                                         if (bb->last_ins && (bb->last_ins->opcode == CEE_BR || (
5126                                                 (bb->last_ins && bb->last_ins->opcode >= CEE_BEQ && bb->last_ins->opcode <= CEE_BLT_UN)))) {
5127                                                 bb->last_ins->opcode = CEE_NOP;
5128                                                 changed = TRUE;
5129                                                 if (cfg->verbose_level > 2)
5130                                                         g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
5131                                         }
5132                                         /* fixme: this causes problems with inlining */
5133                                         if (bbn->in_count == 1) {
5134
5135                                                 if (bbn != cfg->bb_exit) {
5136                                                         if (cfg->verbose_level > 2)
5137                                                                 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
5138                                                         merge_basic_blocks (bb, bbn);
5139                                                         changed = TRUE;
5140                                                 }
5141
5142                                                 //mono_print_bb_code (bb);
5143                                         }
5144                                 } else {
5145                                         if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
5146                                                 bbn = bb->last_ins->inst_target_bb;
5147                                                 if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR) {
5148                                                         /*
5149                                                         if (cfg->verbose_level > 2)
5150                                                                 g_print ("in %s branch to branch triggered %d -> %d\n", cfg->method->name, bb->block_num, bbn->block_num);
5151                                                         bb->out_bb [0] = bb->last_ins->inst_target_bb = bbn->code->inst_target_bb;
5152                                                         changed = TRUE;*/
5153                                                 }
5154                                         }
5155                                 }
5156                         } else if (bb->out_count == 2) {
5157                                 /* fixme: this does not correctly unlink the blocks, so we get serious problems in idom code */
5158                                 if (0 && bb->last_ins && bb->last_ins->opcode >= CEE_BEQ && bb->last_ins->opcode <= CEE_BLT_UN) {
5159                                         bbn = bb->last_ins->inst_true_bb;
5160                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR) {
5161                                                 if (cfg->verbose_level > 2)
5162                                                         g_print ("cbranch to branch triggered %d -> %d (0x%02x)\n", bb->block_num, 
5163                                                                  bbn->block_num, bbn->code->opcode);
5164                                                  
5165                                                 if (bb->out_bb [0] == bbn) {
5166                                                         bb->out_bb [0] = bbn->code->inst_target_bb;
5167                                                 } else if (bb->out_bb [1] == bbn) {
5168                                                         bb->out_bb [1] = bbn->code->inst_target_bb;
5169                                                 }
5170                                                 bb->last_ins->inst_true_bb = bbn->code->inst_target_bb;
5171                                                 changed = TRUE;
5172                                         }
5173                                 }
5174                         }
5175                 }
5176         } while (changed);
5177 }
5178
5179 static void
5180 mono_compile_create_vars (MonoCompile *cfg)
5181 {
5182         MonoMethodSignature *sig;
5183         MonoMethodHeader *header;
5184         int i;
5185
5186         header = ((MonoMethodNormal *)cfg->method)->header;
5187
5188         sig = cfg->method->signature;
5189         
5190         if (!MONO_TYPE_IS_VOID (sig->ret)) {
5191                 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
5192                 cfg->ret->opcode = OP_RETARG;
5193                 cfg->ret->inst_vtype = sig->ret;
5194                 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
5195         }
5196
5197         if (sig->hasthis)
5198                 mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
5199
5200         for (i = 0; i < sig->param_count; ++i)
5201                 mono_compile_create_var (cfg, sig->params [i], OP_ARG);
5202
5203         cfg->locals_start = cfg->num_varinfo;
5204
5205         for (i = 0; i < header->num_locals; ++i)
5206                 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
5207 }
5208
5209 #if 0
5210 static void
5211 mono_print_code (MonoCompile *cfg)
5212 {
5213         MonoBasicBlock *bb;
5214         
5215         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5216                 MonoInst *tree = bb->code;      
5217
5218                 if (!tree)
5219                         continue;
5220                 
5221                 g_print ("CODE BLOCK %d (nesting %d):\n", bb->block_num, bb->nesting);
5222
5223                 for (; tree; tree = tree->next) {
5224                         mono_print_tree (tree);
5225                         g_print ("\n");
5226                 }
5227
5228                 if (bb->last_ins)
5229                         bb->last_ins->next = NULL;
5230         }
5231 }
5232 #endif
5233
5234 extern const char * const mono_burg_rule_string [];
5235
5236 static void
5237 emit_state (MonoCompile *cfg, MBState *state, int goal)
5238 {
5239         MBState *kids [10];
5240         int ern = mono_burg_rule (state, goal);
5241         const guint16 *nts = mono_burg_nts [ern];
5242         MBEmitFunc emit;
5243
5244         //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
5245         switch (goal) {
5246         case MB_NTERM_reg:
5247                 //if (state->reg2)
5248                 //      state->reg1 = state->reg2; /* chain rule */
5249                 //else
5250                 state->reg1 = mono_regstate_next_int (cfg->rs);
5251                 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
5252                 break;
5253         case MB_NTERM_lreg:
5254                 state->reg1 = mono_regstate_next_int (cfg->rs);
5255                 state->reg2 = mono_regstate_next_int (cfg->rs);
5256                 break;
5257         case MB_NTERM_freg:
5258                 state->reg1 = mono_regstate_next_float (cfg->rs);
5259                 break;
5260         default:
5261                 /* do nothing */
5262                 break;
5263         }
5264         if (nts [0]) {
5265                 mono_burg_kids (state, ern, kids);
5266
5267                 emit_state (cfg, kids [0], nts [0]);
5268                 if (nts [1]) {
5269                         emit_state (cfg, kids [1], nts [1]);
5270                         if (nts [2]) {
5271                                 g_assert (!nts [3]);
5272                                 emit_state (cfg, kids [2], nts [2]);
5273                         }
5274                 }
5275         }
5276
5277 //      g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
5278         if ((emit = mono_burg_func [ern]))
5279                 emit (state, state->tree, cfg); 
5280 }
5281
5282 #define DEBUG_SELECTION
5283
5284 static void 
5285 mini_select_instructions (MonoCompile *cfg)
5286 {
5287         MonoBasicBlock *bb;
5288         
5289         cfg->state_pool = mono_mempool_new ();
5290         cfg->rs = mono_regstate_new ();
5291
5292 #ifdef DEBUG_SELECTION
5293         if (cfg->verbose_level >= 4) {
5294         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5295                 MonoInst *tree = bb->code;      
5296                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
5297                 if (!tree)
5298                         continue;
5299                 for (; tree; tree = tree->next) {
5300                         mono_print_tree (tree);
5301                         g_print ("\n");
5302                 }
5303         }
5304         }
5305 #endif
5306
5307         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5308                 MonoInst *tree = bb->code, *next;       
5309                 MBState *mbstate;
5310
5311                 if (!tree)
5312                         continue;
5313                 bb->code = NULL;
5314                 bb->last_ins = NULL;
5315                 
5316                 cfg->cbb = bb;
5317                 mono_regstate_reset (cfg->rs);
5318
5319 #ifdef DEBUG_SELECTION
5320                 if (cfg->verbose_level >= 3)
5321                         g_print ("LABEL BLOCK %d:\n", bb->block_num);
5322 #endif
5323                 for (; tree; tree = next) {
5324                         next = tree->next;
5325 #ifdef DEBUG_SELECTION
5326                         if (cfg->verbose_level >= 3) {
5327                                 mono_print_tree (tree);
5328                                 g_print ("\n");
5329                         }
5330 #endif
5331
5332                         if (!(mbstate = mono_burg_label (tree, cfg))) {
5333                                 g_warning ("unabled to label tree %p", tree);
5334                                 mono_print_tree (tree);
5335                                 g_print ("\n");                         
5336                                 g_assert_not_reached ();
5337                         }
5338                         emit_state (cfg, mbstate, MB_NTERM_stmt);
5339                 }
5340                 bb->max_ireg = cfg->rs->next_vireg;
5341                 bb->max_freg = cfg->rs->next_vfreg;
5342
5343                 if (bb->last_ins)
5344                         bb->last_ins->next = NULL;
5345
5346                 mono_mempool_empty (cfg->state_pool); 
5347         }
5348         mono_mempool_destroy (cfg->state_pool); 
5349 }
5350
5351 void
5352 mono_codegen (MonoCompile *cfg)
5353 {
5354         MonoJumpInfo *patch_info;
5355         MonoBasicBlock *bb;
5356         int i, max_epilog_size;
5357         guint8 *code;
5358
5359         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5360                 cfg->spill_count = 0;
5361                 /* we reuse dfn here */
5362                 /* bb->dfn = bb_count++; */
5363                 mono_arch_local_regalloc (cfg, bb);
5364         }
5365
5366         if (mono_trace_coverage)
5367                 mono_allocate_coverage_info (cfg->method, cfg->num_bblocks);
5368
5369         code = mono_arch_emit_prolog (cfg);
5370
5371         if (mono_jit_profile)
5372                 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
5373
5374         cfg->code_len = code - cfg->native_code;
5375         cfg->prolog_end = cfg->code_len;
5376
5377         mono_debug_open_method (cfg);
5378              
5379         /* emit code all basic blocks */
5380         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5381                 bb->native_offset = cfg->code_len;
5382                 mono_arch_output_basic_block (cfg, bb);
5383         }
5384         cfg->bb_exit->native_offset = cfg->code_len;
5385
5386         code = cfg->native_code + cfg->code_len;
5387
5388         max_epilog_size = mono_arch_max_epilog_size (cfg);
5389
5390         /* we always allocate code in cfg->domain->code_mp to increase locality */
5391         cfg->code_size = cfg->code_len + max_epilog_size;
5392         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
5393         code = mono_mempool_alloc (cfg->domain->code_mp, cfg->code_size);
5394         memcpy (code, cfg->native_code, cfg->code_len);
5395         g_free (cfg->native_code);
5396         cfg->native_code = code;
5397         code = cfg->native_code + cfg->code_len;
5398   
5399         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
5400
5401         cfg->epilog_begin = cfg->code_len;
5402
5403         if (mono_jit_profile)
5404                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
5405
5406         cfg->code_len = code - cfg->native_code;
5407
5408         mono_arch_emit_epilog (cfg);
5409
5410         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5411                 switch (patch_info->type) {
5412                 case MONO_PATCH_INFO_ABS: {
5413                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
5414                         if (info) {
5415                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
5416                                 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
5417                                 patch_info->data.name = info->name;
5418                         }
5419                         break;
5420                 }
5421                 case MONO_PATCH_INFO_SWITCH: {
5422                         gpointer *table = g_new (gpointer, patch_info->table_size);
5423                         patch_info->ip.i = patch_info->ip.label->inst_c0;
5424                         for (i = 0; i < patch_info->table_size; i++) {
5425                                 table [i] = (gpointer)patch_info->data.table [i]->native_offset;
5426                         }
5427                         patch_info->data.target = table;
5428                         break;
5429                 }
5430                 default:
5431                         /* do nothing */
5432                         break;
5433                 }
5434         }
5435        
5436         if (cfg->verbose_level > 1)
5437                 g_print ("Method %s::%s emmitted at %p to %p\n", cfg->method->klass->name, 
5438                          cfg->method->name, cfg->native_code, cfg->native_code + cfg->code_len);
5439
5440         mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info);
5441
5442         mono_debug_close_method (cfg);
5443 }
5444
5445 static void
5446 mono_cprop_copy_values (MonoCompile *cfg, MonoInst *tree, MonoInst **acp)
5447 {
5448         MonoInst *cp;
5449         int arity;
5450
5451         if (tree->ssa_op == MONO_SSA_LOAD && (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG) && 
5452             (cp = acp [tree->inst_i0->inst_c0]) && !tree->inst_i0->flags) {
5453
5454                 if (cp->opcode == OP_ICONST) {
5455                         if (cfg->opt & MONO_OPT_CONSPROP) {
5456                                 //{ static int c = 0; printf ("CCOPY %d %d %s\n", c++, cp->inst_c0, mono_method_full_name (cfg->method, TRUE)); }
5457                                 *tree = *cp;
5458                         }
5459                 } else {
5460                         if (tree->inst_i0->inst_vtype->type == cp->inst_vtype->type) {
5461                                 if (cfg->opt & MONO_OPT_COPYPROP) {
5462                                         //{ static int c = 0; printf ("VCOPY %d\n", ++c); }
5463                                         tree->inst_i0 = cp;
5464                                 } 
5465                         }
5466                 } 
5467         } else {
5468                 arity = mono_burg_arity [tree->opcode];
5469
5470                 if (arity) {
5471                         mono_cprop_copy_values (cfg, tree->inst_i0, acp);
5472                         if (cfg->opt & MONO_OPT_CFOLD)
5473                                 mono_constant_fold_inst (tree, NULL); 
5474                         if (arity > 1) {
5475                                 mono_cprop_copy_values (cfg, tree->inst_i1, acp);
5476                                 if (cfg->opt & MONO_OPT_CFOLD)
5477                                         mono_constant_fold_inst (tree, NULL); 
5478                         }
5479                         mono_constant_fold_inst (tree, NULL); 
5480                 }
5481         }
5482 }
5483
5484 static void
5485 mono_cprop_invalidate_values (MonoInst *tree, MonoInst **acp, int acp_size)
5486 {
5487         int arity;
5488
5489         switch (tree->opcode) {
5490         case CEE_STIND_I:
5491         case CEE_STIND_I1:
5492         case CEE_STIND_I2:
5493         case CEE_STIND_I4:
5494         case CEE_STIND_REF:
5495         case CEE_STIND_I8:
5496         case CEE_STIND_R4:
5497         case CEE_STIND_R8:
5498         case CEE_STOBJ:
5499                 if (tree->ssa_op == MONO_SSA_NOP) {
5500                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
5501                         return;
5502                 }
5503
5504                 break;
5505         case CEE_CALL:
5506         case OP_CALL_REG:
5507         case CEE_CALLVIRT:
5508         case OP_LCALL_REG:
5509         case OP_LCALLVIRT:
5510         case OP_LCALL:
5511         case OP_FCALL_REG:
5512         case OP_FCALLVIRT:
5513         case OP_FCALL:
5514         case OP_VCALL_REG:
5515         case OP_VCALLVIRT:
5516         case OP_VCALL:
5517         case OP_VOIDCALL_REG:
5518         case OP_VOIDCALLVIRT:
5519         case OP_VOIDCALL: {
5520                 MonoCallInst *call = (MonoCallInst *)tree;
5521                 MonoMethodSignature *sig = call->signature;
5522                 int i, byref = FALSE;
5523
5524                 for (i = 0; i < sig->param_count; i++) {
5525                         if (sig->params [i]->byref) {
5526                                 byref = TRUE;
5527                                 break;
5528                         }
5529                 }
5530
5531                 if (byref)
5532                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
5533
5534                 return;
5535         }
5536         default:
5537                 break;
5538         }
5539
5540         arity = mono_burg_arity [tree->opcode];
5541
5542         switch (arity) {
5543         case 0:
5544                 break;
5545         case 1:
5546                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
5547                 break;
5548         case 2:
5549                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
5550                 mono_cprop_invalidate_values (tree->inst_i1, acp, acp_size);
5551                 break;
5552         default:
5553                 g_assert_not_reached ();
5554         }
5555 }
5556
5557 static void
5558 mono_local_cprop_bb (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **acp, int acp_size)
5559 {
5560         MonoInst *tree = bb->code;      
5561         int i;
5562
5563         if (!tree)
5564                 return;
5565
5566         for (; tree; tree = tree->next) {
5567
5568                 mono_cprop_copy_values (cfg, tree, acp);
5569
5570                 mono_cprop_invalidate_values (tree, acp, acp_size);
5571
5572                 if (tree->ssa_op == MONO_SSA_STORE  && 
5573                     (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG)) {
5574                         MonoInst *i1 = tree->inst_i1;
5575
5576                         acp [tree->inst_i0->inst_c0] = NULL;
5577
5578                         for (i = 0; i < acp_size; i++) {
5579                                 if (acp [i] && acp [i]->opcode != OP_ICONST && 
5580                                     acp [i]->inst_c0 == tree->inst_i0->inst_c0) {
5581                                         acp [i] = NULL;
5582                                 }
5583                         }
5584
5585                         if (i1->opcode == OP_ICONST) {
5586                                 acp [tree->inst_i0->inst_c0] = i1;
5587                                 //printf ("DEF1 BB%d %d\n", bb->block_num,tree->inst_i0->inst_c0);
5588                         }
5589                         if (i1->ssa_op == MONO_SSA_LOAD && 
5590                             (i1->inst_i0->opcode == OP_LOCAL || i1->inst_i0->opcode == OP_ARG) &&
5591                             (i1->inst_i0->inst_c0 != tree->inst_i0->inst_c0)) {
5592                                 acp [tree->inst_i0->inst_c0] = i1->inst_i0;
5593                                 //printf ("DEF2 BB%d %d %d\n", bb->block_num,tree->inst_i0->inst_c0,i1->inst_i0->inst_c0);
5594                         }
5595                 }
5596
5597                 /*
5598                   if (tree->opcode == CEE_BEQ) {
5599                   g_assert (tree->inst_i0->opcode == OP_COMPARE);
5600                   if (tree->inst_i0->inst_i0->opcode == OP_ICONST &&
5601                   tree->inst_i0->inst_i1->opcode == OP_ICONST) {
5602                   
5603                   tree->opcode = CEE_BR;
5604                   if (tree->inst_i0->inst_i0->opcode == tree->inst_i0->inst_i1->opcode) {
5605                   tree->inst_target_bb = tree->inst_true_bb;
5606                   } else {
5607                   tree->inst_target_bb = tree->inst_false_bb;
5608                   }
5609                   }
5610                   }
5611                 */
5612         }
5613 }
5614
5615 static void
5616 mono_local_cprop (MonoCompile *cfg)
5617 {
5618         MonoBasicBlock *bb;
5619         MonoInst **acp;
5620
5621         acp = alloca (sizeof (MonoInst *) * cfg->num_varinfo);
5622
5623         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5624                 memset (acp, 0, sizeof (MonoInst *) * cfg->num_varinfo);
5625                 mono_local_cprop_bb (cfg, bb, acp, cfg->num_varinfo);
5626         }
5627 }
5628
5629 MonoCompile*
5630 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, int parts)
5631 {
5632         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
5633         guint8 *ip = (guint8 *)header->code;
5634         MonoCompile *cfg;
5635         MonoJitInfo *jinfo;
5636         int dfn = 0, i, code_size_ratio;
5637
5638         mono_jit_stats.methods_compiled++;
5639         if (mono_jit_profile)
5640                 mono_profiler_method_jit (method);
5641
5642         cfg = g_new0 (MonoCompile, 1);
5643         cfg->method = method;
5644         cfg->mempool = mono_mempool_new ();
5645         cfg->opt = opts;
5646         cfg->bb_hash = g_hash_table_new (g_direct_hash, NULL);
5647         cfg->domain = domain;
5648         cfg->verbose_level = mini_verbose;
5649
5650         /*
5651          * create MonoInst* which represents arguments and local variables
5652          */
5653         mono_compile_create_vars (cfg);
5654
5655         if (cfg->verbose_level > 2)
5656                 g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
5657
5658         if ((i = mono_method_to_ir (cfg, method, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
5659                 mono_destroy_compile (cfg);
5660                 if (mono_jit_profile)
5661                         mono_profiler_method_end_jit (method, MONO_PROFILE_FAILED);
5662                 return NULL;
5663         }
5664
5665         mono_jit_stats.basic_blocks += cfg->num_bblocks;
5666         mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
5667
5668         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
5669
5670         /* Depth-first ordering on basic blocks */
5671         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
5672
5673         if (cfg->opt & MONO_OPT_BRANCH)
5674                 optimize_branches (cfg);
5675
5676         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
5677         if (cfg->num_bblocks != dfn + 1) {
5678                 if (cfg->verbose_level > 1)
5679                         g_print ("unreachable code?\n");
5680                 cfg->num_bblocks = dfn + 1;
5681         }
5682
5683         if (cfg->opt & MONO_OPT_LOOP) {
5684                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
5685                 mono_compute_natural_loops (cfg);
5686         }
5687
5688
5689         /* after method_to_ir */
5690         if (parts == 1)
5691                 return cfg;
5692
5693 //#define DEBUGSSA "logic_run"
5694 #define DEBUGSSA_CLASS "Tests"
5695 #ifdef DEBUGSSA
5696
5697
5698         if (!header->num_clauses && !cfg->disable_ssa) {
5699                 mono_local_cprop (cfg);
5700                 mono_ssa_compute (cfg);
5701         }
5702 #else 
5703
5704         /* fixme: add all optimizations which requires SSA */
5705         if (cfg->opt & (MONO_OPT_DEADCE)) {
5706                 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
5707                         mono_local_cprop (cfg);
5708                         mono_ssa_compute (cfg);
5709
5710                         if (cfg->verbose_level >= 2) {
5711                                 print_dfn (cfg);
5712                         }
5713                 }
5714         }
5715 #endif
5716
5717         /* after SSA translation */
5718         if (parts == 2)
5719                 return cfg;
5720
5721         if ((cfg->opt & MONO_OPT_CONSPROP) ||  (cfg->opt & MONO_OPT_COPYPROP)) {
5722                 if (cfg->comp_done & MONO_COMP_SSA) {
5723                         mono_ssa_cprop (cfg);
5724                 } else {
5725                         mono_local_cprop (cfg);
5726                 }
5727         }
5728
5729         if (cfg->comp_done & MONO_COMP_SSA) {                   
5730                 mono_ssa_deadce (cfg);
5731
5732                 //mono_ssa_strength_reduction (cfg);
5733
5734                 mono_ssa_remove (cfg);
5735
5736                 if (cfg->opt & MONO_OPT_BRANCH)
5737                         optimize_branches (cfg);
5738         }
5739
5740         /* after SSA removal */
5741         if (parts == 3)
5742                 return cfg;
5743         
5744         decompose_pass (cfg);
5745
5746         if (cfg->opt & MONO_OPT_LINEARS) {
5747                 GList *vars, *regs;
5748
5749                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
5750                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
5751                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
5752                         mono_analyze_liveness (cfg);
5753                 
5754                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
5755                         regs = mono_arch_get_global_int_regs (cfg);
5756                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
5757                 }
5758         }
5759
5760         //mono_print_code (cfg);
5761         
5762         //print_dfn (cfg);
5763
5764         /* variables are allocated after decompose, since decompose could create temps */
5765         mono_arch_allocate_vars (cfg);
5766
5767         if (cfg->opt & MONO_OPT_CFOLD)
5768                 mono_constant_fold (cfg);
5769
5770         mini_select_instructions (cfg);
5771
5772         mono_codegen (cfg);
5773         if (cfg->verbose_level >= 2) {
5774                 char *id =  mono_method_full_name (cfg->method, FALSE);
5775                 mono_disassemble_code (cfg->native_code, cfg->code_len, id + 3);
5776                 g_free (id);
5777         }
5778         
5779         jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo));
5780
5781         jinfo = g_new0 (MonoJitInfo, 1);
5782         jinfo->method = method;
5783         jinfo->code_start = cfg->native_code;
5784         jinfo->code_size = cfg->code_len;
5785         jinfo->used_regs = cfg->used_int_regs;
5786
5787         if (header->num_clauses) {
5788                 int i;
5789
5790                 jinfo->exvar_offset = cfg->exvar? cfg->exvar->inst_offset: 0;
5791                 jinfo->num_clauses = header->num_clauses;
5792                 jinfo->clauses = mono_mempool_alloc0 (cfg->domain->mp, 
5793                         sizeof (MonoJitExceptionInfo) * header->num_clauses);
5794
5795                 for (i = 0; i < header->num_clauses; i++) {
5796                         MonoExceptionClause *ec = &header->clauses [i];
5797                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
5798                         MonoBasicBlock *tblock;
5799
5800                         ei->flags = ec->flags;
5801
5802                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
5803                                 tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->token_or_filter);
5804                                 g_assert (tblock);
5805                                 ei->data.filter = cfg->native_code + tblock->native_offset;
5806                         } else {
5807                                 ei->data.token = ec->token_or_filter;
5808                         }
5809
5810                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset);
5811                         g_assert (tblock);
5812                         ei->try_start = cfg->native_code + tblock->native_offset;
5813                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset + ec->try_len);
5814                         g_assert (tblock);
5815                         ei->try_end = cfg->native_code + tblock->native_offset;
5816                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->handler_offset);
5817                         g_assert (tblock);
5818                         ei->handler_start = cfg->native_code + tblock->native_offset;
5819
5820                 }
5821         }
5822
5823         mono_jit_info_table_add (cfg->domain, jinfo);
5824
5825         /* collect statistics */
5826         mono_jit_stats.allocated_code_size += cfg->code_len;
5827         code_size_ratio = cfg->code_len;
5828         if (code_size_ratio > mono_jit_stats.biggest_method_size) {
5829                         mono_jit_stats.biggest_method_size = code_size_ratio;
5830                         mono_jit_stats.biggest_method = method;
5831         }
5832         code_size_ratio = (code_size_ratio * 100) / ((MonoMethodNormal *)method)->header->code_size;
5833         if (code_size_ratio > mono_jit_stats.max_code_size_ratio) {
5834                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
5835                 mono_jit_stats.max_ratio_method = method;
5836         }
5837         mono_jit_stats.native_code_size += cfg->code_len;
5838
5839         if (mono_jit_profile)
5840                 mono_profiler_method_end_jit (method, MONO_PROFILE_OK);
5841
5842         return cfg;
5843 }
5844
5845 static gpointer
5846 mono_jit_compile_method (MonoMethod *method)
5847 {
5848         /* FIXME: later copy the code from mono */
5849         MonoDomain *target_domain, *domain = mono_domain_get ();
5850         MonoCompile *cfg;
5851         GHashTable *jit_code_hash;
5852         gpointer code;
5853
5854         if (default_opt & MONO_OPT_SAHRED)
5855                 target_domain = mono_root_domain;
5856         else 
5857                 target_domain = domain;
5858
5859         jit_code_hash = target_domain->jit_code_hash;
5860
5861         if ((code = g_hash_table_lookup (jit_code_hash, method))) {
5862                 mono_jit_stats.methods_lookups++;
5863                 return code;
5864         }
5865
5866 #ifdef MONO_USE_AOT_COMPILER
5867         if (!mono_compile_aot) {
5868                 mono_class_init (method->klass);
5869                 if ((code = mono_aot_get_method (method))) {
5870                         g_hash_table_insert (jit_code_hash, method, code);
5871                         return code;
5872                 }
5873         }
5874 #endif
5875
5876         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
5877             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5878                 if (!method->info) {
5879                         MonoMethod *nm;
5880
5881                         if (!method->addr && (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
5882                                 mono_lookup_pinvoke_call (method);
5883 #ifdef MONO_USE_EXC_TABLES
5884                         if (mono_method_blittable (method)) {
5885                                 method->info = method->addr;
5886                         } else {
5887 #endif
5888                                 nm = mono_marshal_get_native_wrapper (method);
5889                                 method->info = mono_compile_method (nm);
5890
5891                                 //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE) 
5892                                 //mono_debug_add_wrapper (method, nm);
5893 #ifdef MONO_USE_EXC_TABLES
5894                         }
5895 #endif
5896                 }
5897                 return method->info;
5898         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
5899                 const char *name = method->name;
5900                 MonoMethod *nm;
5901
5902                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
5903                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
5904                                 /* FIXME: uhm, we need a wrapper to handle exceptions? */
5905                                 return (gpointer)mono_delegate_ctor;
5906                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
5907                                 nm = mono_marshal_get_delegate_invoke (method);
5908                                 return mono_jit_compile_method (nm);
5909                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
5910                                 nm = mono_marshal_get_delegate_begin_invoke (method);
5911                                 return mono_jit_compile_method (nm);
5912                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
5913                                 nm = mono_marshal_get_delegate_end_invoke (method);
5914                                 return mono_jit_compile_method (nm);
5915                         }
5916                 }
5917                 return NULL;
5918         }
5919
5920         cfg = mini_method_compile (method, default_opt, target_domain, 0);
5921         code = cfg->native_code;
5922         mono_destroy_compile (cfg);
5923
5924         g_hash_table_insert (jit_code_hash, method, code);
5925
5926         /* make sure runtime_init is called */
5927         mono_class_vtable (target_domain, method->klass);
5928
5929         return code;
5930 }
5931
5932 /**
5933  * mono_jit_runtime_invoke:
5934  * @method: the method to invoke
5935  * @obj: this pointer
5936  * @params: array of parameter values.
5937  * @exc: used to catch exceptions objects
5938  */
5939 static MonoObject*
5940 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
5941 {
5942         MonoMethod *invoke;
5943         MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc);
5944         invoke = mono_marshal_get_runtime_invoke (method);
5945         runtime_invoke = mono_jit_compile_method (invoke);      
5946         return runtime_invoke (obj, params, exc);
5947 }
5948
5949 #ifdef PLATFORM_WIN32
5950 #define GET_CONTEXT \
5951         struct sigcontext *ctx = (struct sigcontext*)_dummy;
5952 #else
5953 #define GET_CONTEXT \
5954         void **_p = (void **)&_dummy; \
5955         struct sigcontext *ctx = (struct sigcontext *)++_p;
5956 #endif
5957
5958 static void
5959 sigfpe_signal_handler (int _dummy)
5960 {
5961         MonoException *exc;
5962         GET_CONTEXT
5963
5964         exc = mono_get_exception_divide_by_zero ();
5965         
5966         mono_arch_handle_exception (ctx, exc, FALSE);
5967 }
5968
5969 static void
5970 sigill_signal_handler (int _dummy)
5971 {
5972         MonoException *exc;
5973         GET_CONTEXT
5974         exc = mono_get_exception_execution_engine ("SIGILL");
5975         
5976         mono_arch_handle_exception (ctx, exc, FALSE);
5977 }
5978
5979 static void
5980 sigsegv_signal_handler (int _dummy)
5981 {
5982         MonoException *exc;
5983         GET_CONTEXT
5984
5985         exc = mono_get_exception_null_reference ();
5986         
5987         mono_arch_handle_exception (ctx, exc, FALSE);
5988 }
5989
5990 static void
5991 sigusr1_signal_handler (int _dummy)
5992 {
5993         MonoThread *thread;
5994         GET_CONTEXT
5995         
5996         thread = mono_thread_current ();
5997         
5998         g_assert (thread->abort_exc);
5999
6000         mono_arch_handle_exception (ctx, thread->abort_exc, FALSE);
6001 }
6002
6003 static void
6004 mono_runtime_install_handlers (void)
6005 {
6006 #ifndef PLATFORM_WIN32
6007         struct sigaction sa;
6008 #endif
6009
6010 #ifdef PLATFORM_WIN32
6011         win32_seh_init();
6012         win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
6013         win32_seh_set_handler(SIGILL, sigill_signal_handler);
6014         win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
6015 #else /* !PLATFORM_WIN32 */
6016
6017         /* libpthreads has its own implementation of sigaction(),
6018          * but it seems to work well with our current exception
6019          * handlers. If not we must call syscall directly instead 
6020          * of sigaction */
6021         
6022         /* catch SIGFPE */
6023         sa.sa_handler = sigfpe_signal_handler;
6024         sigemptyset (&sa.sa_mask);
6025         sa.sa_flags = 0;
6026         //g_assert (syscall (SYS_sigaction, SIGFPE, &sa, NULL) != -1);
6027         g_assert (sigaction (SIGFPE, &sa, NULL) != -1);
6028
6029         /* catch SIGILL */
6030         sa.sa_handler = sigill_signal_handler;
6031         sigemptyset (&sa.sa_mask);
6032         sa.sa_flags = 0;
6033         //g_assert (syscall (SYS_sigaction, SIGILL, &sa, NULL) != -1);
6034         g_assert (sigaction (SIGILL, &sa, NULL) != -1);
6035
6036         /* catch thread abort signal */
6037         sa.sa_handler = sigusr1_signal_handler;
6038         sigemptyset (&sa.sa_mask);
6039         sa.sa_flags = 0;
6040         //g_assert (syscall (SYS_sigaction, SIGILL, &sa, NULL) != -1);
6041         g_assert (sigaction (mono_thread_get_abort_signal (), &sa, NULL) != -1);
6042
6043 #if 1
6044         /* catch SIGSEGV */
6045         sa.sa_handler = sigsegv_signal_handler;
6046         sigemptyset (&sa.sa_mask);
6047         sa.sa_flags = 0;
6048         //g_assert (syscall (SYS_sigaction, SIGSEGV, &sa, NULL) != -1);
6049         g_assert (sigaction (SIGSEGV, &sa, NULL) != -1);
6050 #endif
6051 #endif /* PLATFORM_WIN32 */
6052 }
6053
6054 /* mono_jit_create_remoting_trampoline:
6055  * @method: pointer to the method info
6056  *
6057  * Creates a trampoline which calls the remoting functions. This
6058  * is used in the vtable of transparent proxies.
6059  * 
6060  * Returns: a pointer to the newly created code 
6061  */
6062 static gpointer
6063 mono_jit_create_remoting_trampoline (MonoMethod *method)
6064 {
6065         MonoMethod *nm;
6066         guint8 *addr = NULL;
6067
6068         if (method->signature->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
6069                 nm = mono_marshal_get_remoting_invoke (method);
6070                 addr = mono_compile_method (nm);
6071         } else {
6072                 addr = mono_compile_method (method);
6073         }
6074         return addr;
6075 }
6076
6077 static CRITICAL_SECTION ms;
6078
6079 MonoDomain *
6080 mini_init (const char *filename)
6081 {
6082         MonoDomain *domain;
6083         
6084         metadata_section = &ms;
6085         InitializeCriticalSection (metadata_section);
6086
6087         mono_jit_tls_id = TlsAlloc ();
6088         mono_thread_start_cb (GetCurrentThreadId (), (gpointer)-1, NULL);
6089
6090         mono_burg_init ();
6091
6092         mono_runtime_install_handlers ();
6093
6094         mono_install_compile_method (mono_jit_compile_method);
6095         mono_install_trampoline (mono_arch_create_jit_trampoline);
6096         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
6097         mono_install_runtime_invoke (mono_jit_runtime_invoke);
6098         mono_install_handler (mono_arch_get_throw_exception ());
6099         mono_install_stack_walk (mono_jit_walk_stack);
6100         mono_install_get_config_dir ();
6101
6102         domain = mono_init (filename);
6103         mono_init_icall ();
6104
6105         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info", 
6106                                 ves_icall_get_frame_info);
6107         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace", 
6108                                 ves_icall_get_trace);
6109         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers", 
6110                                 mono_runtime_install_handlers);
6111
6112
6113         create_helper_signature ();
6114
6115         mono_arch_register_lowlevel_calls ();
6116         mono_register_jit_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
6117         mono_register_jit_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
6118
6119         mono_register_jit_icall (mono_get_lmf_addr, "mono_get_lmf_addr", helper_sig_ptr_void, TRUE);
6120         mono_register_jit_icall (mono_domain_get, "mono_domain_get", helper_sig_domain_get, TRUE);
6121
6122         /* fixme: we cant hanlde vararg methods this way, because the signature is not constant */
6123         //mono_register_jit_icall (ves_array_element_address, "ves_array_element_address", NULL);
6124         //mono_register_jit_icall (mono_array_new_va, "mono_array_new_va", NULL);
6125
6126         mono_register_jit_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", helper_sig_void_obj, TRUE);
6127         mono_register_jit_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", 
6128                                  helper_sig_void_ptr, TRUE);
6129
6130         /* 
6131          * NOTE, NOTE, NOTE, NOTE:
6132          * when adding emulation for some opcodes, remember to also add a dummy
6133          * rule to the burg files, because we need the arity information to be correct.
6134          */
6135         mono_register_opcode_emulation (OP_LMUL, helper_sig_long_long_long, mono_llmult);
6136         mono_register_opcode_emulation (OP_LMUL_OVF_UN, helper_sig_long_long_long, mono_llmult_ovf_un);
6137         mono_register_opcode_emulation (OP_LMUL_OVF, helper_sig_long_long_long, mono_llmult_ovf);
6138         mono_register_opcode_emulation (OP_LDIV, helper_sig_long_long_long, mono_lldiv);
6139         mono_register_opcode_emulation (OP_LDIV_UN, helper_sig_long_long_long, mono_lldiv_un);
6140         mono_register_opcode_emulation (OP_LREM, helper_sig_long_long_long, mono_llrem);
6141         mono_register_opcode_emulation (OP_LREM_UN, helper_sig_long_long_long, mono_llrem_un);
6142
6143         mono_register_opcode_emulation (OP_LSHL, helper_sig_long_long_int, mono_lshl);
6144         mono_register_opcode_emulation (OP_LSHR, helper_sig_long_long_int, mono_lshr);
6145         mono_register_opcode_emulation (OP_LSHR_UN, helper_sig_long_long_int, mono_lshr_un);
6146
6147         mono_register_opcode_emulation (OP_FCONV_TO_U8, helper_sig_ulong_double, mono_fconv_u8);
6148         mono_register_opcode_emulation (OP_FCONV_TO_U4, helper_sig_uint_double, mono_fconv_u4);
6149         mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, helper_sig_long_double, mono_fconv_ovf_i8);
6150         mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, helper_sig_ulong_double, mono_fconv_ovf_u8);
6151
6152 #if SIZEOF_VOID_P == 4
6153         mono_register_opcode_emulation (OP_FCONV_TO_U, helper_sig_uint_double, mono_fconv_u4);
6154 #else
6155 #warning "fixme: add opcode emulation"
6156 #endif
6157
6158         /* other jit icalls */
6159         mono_register_jit_icall (mono_class_static_field_address , "mono_class_static_field_address", 
6160                                  helper_sig_ptr_ptr_ptr, FALSE);
6161         mono_register_jit_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", helper_sig_ptr_ptr_ptr, FALSE);
6162         mono_register_jit_icall (mono_ldstr, "mono_ldstr", helper_sig_ldstr, FALSE);
6163         mono_register_jit_icall (helper_memcpy, "helper_memcpy", helper_sig_memcpy, FALSE);
6164         mono_register_jit_icall (helper_memset, "helper_memset", helper_sig_memset, FALSE);
6165         mono_register_jit_icall (helper_initobj, "helper_initobj", helper_sig_initobj, FALSE);
6166         mono_register_jit_icall (helper_stelem_ref, "helper_stelem_ref", helper_sig_stelem_ref, FALSE);
6167         mono_register_jit_icall (mono_object_new, "mono_object_new", helper_sig_object_new, FALSE);
6168         mono_register_jit_icall (mono_array_new, "mono_array_new", helper_sig_newarr, FALSE);
6169         mono_register_jit_icall (mono_string_to_utf16, "mono_string_to_utf16", helper_sig_ptr_obj, FALSE);
6170         mono_register_jit_icall (mono_string_from_utf16, "mono_string_from_utf16", helper_sig_obj_ptr, FALSE);
6171         mono_register_jit_icall (mono_string_new_wrapper, "mono_string_new_wrapper", helper_sig_obj_ptr, FALSE);
6172         mono_register_jit_icall (mono_string_to_utf8, "mono_string_to_utf8", helper_sig_ptr_obj, FALSE);
6173         mono_register_jit_icall (mono_string_to_bstr, "mono_string_to_bstr", helper_sig_ptr_obj, FALSE);
6174         mono_register_jit_icall (mono_string_to_ansibstr, "mono_string_to_ansibstr", helper_sig_ptr_obj, FALSE);
6175         mono_register_jit_icall (mono_string_builder_to_utf8, "mono_string_builder_to_utf8", helper_sig_ptr_obj, FALSE);
6176         mono_register_jit_icall (mono_array_to_savearray, "mono_array_to_savearray", helper_sig_ptr_obj, FALSE);
6177         mono_register_jit_icall (mono_array_to_lparray, "mono_array_to_lparray", helper_sig_ptr_obj, FALSE);
6178         mono_register_jit_icall (mono_delegate_to_ftnptr, "mono_delegate_to_ftnptr", helper_sig_ptr_obj, FALSE);
6179         mono_register_jit_icall (mono_marshal_string_array, "mono_marshal_string_array", helper_sig_ptr_obj, FALSE);
6180         mono_register_jit_icall (mono_string_utf8_to_builder, "mono_string_utf8_to_builder", helper_sig_void_ptr_ptr, FALSE);
6181         mono_register_jit_icall (mono_marshal_free_array, "mono_marshal_free_array", helper_sig_void_ptr_ptr, FALSE);
6182         mono_register_jit_icall (mono_string_to_byvalstr, "mono_string_to_byvalstr", helper_sig_void_ptr_ptr_ptr, FALSE);
6183         mono_register_jit_icall (mono_string_to_byvalwstr, "mono_string_to_byvalwstr", helper_sig_void_ptr_ptr_ptr, FALSE);
6184         mono_register_jit_icall (g_free, "g_free", helper_sig_void_ptr, FALSE);
6185         mono_register_jit_icall (mono_ldftn, "mono_ldftn", helper_sig_compile, FALSE);
6186         mono_register_jit_icall (mono_ldvirtfn, "mono_ldvirtfn", helper_sig_compile_virt, FALSE);
6187
6188         mono_runtime_init (domain, mono_thread_start_cb,
6189                            mono_thread_attach_cb);
6190
6191         //mono_thread_attach (domain);
6192         return domain;
6193 }
6194
6195 MonoJitStats mono_jit_stats = {0};
6196
6197 static void 
6198 print_jit_stats (void)
6199 {
6200         if (mono_jit_stats.enabled) {
6201                 g_print ("Mono Jit statistics\n");
6202                 g_print ("Compiled methods:       %ld\n", mono_jit_stats.methods_compiled);
6203                 g_print ("Methods from AOT:       %ld\n", mono_jit_stats.methods_aot);
6204                 g_print ("Methods cache lookup:   %ld\n", mono_jit_stats.methods_lookups);
6205                 g_print ("Method trampolines:     %ld\n", mono_jit_stats.method_trampolines);
6206                 g_print ("Basic blocks:           %ld\n", mono_jit_stats.basic_blocks);
6207                 g_print ("Max basic blocks:       %ld\n", mono_jit_stats.max_basic_blocks);
6208                 g_print ("Allocated vars:         %ld\n", mono_jit_stats.allocate_var);
6209                 g_print ("Analyze stack repeat:   %ld\n", mono_jit_stats.analyze_stack_repeat);
6210                 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
6211                 g_print ("Native code size:       %ld\n", mono_jit_stats.native_code_size);
6212                 g_print ("Max code size ratio:    %.2f (%s::%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
6213                                 mono_jit_stats.max_ratio_method->klass->name, mono_jit_stats.max_ratio_method->name);
6214                 g_print ("Biggest method:         %ld (%s::%s)\n", mono_jit_stats.biggest_method_size,
6215                                 mono_jit_stats.biggest_method->klass->name, mono_jit_stats.biggest_method->name);
6216                 g_print ("Code reallocs:          %ld\n", mono_jit_stats.code_reallocs);
6217                 g_print ("Allocated code size:    %ld\n", mono_jit_stats.allocated_code_size);
6218                 g_print ("Inlineable methods:     %ld\n", mono_jit_stats.inlineable_methods);
6219                 g_print ("Inlined methods:        %ld\n", mono_jit_stats.inlined_methods);
6220                 
6221                 g_print ("\nCreated object count:   %ld\n", mono_stats.new_object_count);
6222                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
6223                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
6224                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
6225                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
6226         }
6227 }
6228
6229 void
6230 mini_cleanup (MonoDomain *domain)
6231 {
6232         /* 
6233          * mono_runtime_cleanup() and mono_domain_finalize () need to
6234          * be called early since they need the execution engine still
6235          * fully working (mono_domain_finalize may invoke managed finalizers
6236          * and mono_runtime_cleanup will wait for other threads to finish).
6237          */
6238         mono_domain_finalize (domain);
6239
6240         mono_runtime_cleanup (domain);
6241
6242         mono_profiler_shutdown ();
6243
6244         mono_debug_cleanup ();
6245 #ifdef PLATFORM_WIN32
6246         win32_seh_cleanup();
6247 #endif
6248
6249         mono_domain_unload (domain, TRUE);
6250
6251         print_jit_stats ();
6252         DeleteCriticalSection (metadata_section);
6253 }
6254
6255 void
6256 mini_set_defaults (int verbose_level, guint32 opts)
6257 {
6258         mini_verbose = verbose_level;
6259         default_opt = opts;
6260 }
6261