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