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