2003-05-30 Dietmar Maurer <dietmar@ximian.com>
[mono.git] / mono / mini / mini.c
1 /*
2  * mini.c: The new Mono code generator.
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * (C) 2002 Ximian, Inc.
9  */
10
11 #include <config.h>
12 #include <signal.h>
13 #include <unistd.h>
14
15 #include <mono/metadata/assembly.h>
16 #include <mono/metadata/loader.h>
17 #include <mono/metadata/cil-coff.h>
18 #include <mono/metadata/tabledefs.h>
19 #include <mono/metadata/class.h>
20 #include <mono/metadata/object.h>
21 #include <mono/metadata/exception.h>
22 #include <mono/metadata/opcodes.h>
23 #include <mono/metadata/mono-endian.h>
24 #include <mono/metadata/tokentype.h>
25 #include <mono/metadata/tabledefs.h>
26 #include <mono/metadata/threads.h>
27 #include <mono/metadata/marshal.h>
28 #include <mono/metadata/socket-io.h>
29 #include <mono/metadata/appdomain.h>
30 #include <mono/metadata/debug-helpers.h>
31 #include <mono/io-layer/io-layer.h>
32 #include "mono/metadata/profiler.h"
33 #include <mono/metadata/profiler-private.h>
34 #include <mono/metadata/mono-config.h>
35 #include <mono/metadata/environment.h>
36 #include <mono/metadata/mono-debug.h>
37 #include <mono/metadata/mono-debug-debugger.h>
38
39 #include "mini.h"
40 #include <string.h>
41 #include <ctype.h>
42 #include "inssel.h"
43
44 #include "jit-icalls.c"
45
46 #define MONO_CHECK_THIS(ins) (cfg->method->signature->hasthis && (ins)->ssa_op == MONO_SSA_LOAD && (ins)->inst_left->inst_c0 == 0)
47
48 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 && args [i]->type != STACK_OBJ)
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                                 MonoVTable *vtable;
3776                                 vtable = mono_class_vtable (cfg->domain, klass);
3777                                 if (!cfg->domain->thread_static_fields || !(addr = g_hash_table_lookup (cfg->domain->thread_static_fields, field))) {
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                         n = mono_type_to_stind (&klass->byval_arg);
3848                         if (n == CEE_STOBJ) {
3849                                 handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE);
3850                         } else {
3851                                 /* FIXME: should check item at sp [1] is compatible with the type of the store. */
3852                                 MonoInst *store;
3853                                 MONO_INST_NEW (cfg, store, n);
3854                                 store->cil_code = ip;
3855                                 store->inst_left = sp [0];
3856                                 store->inst_right = sp [1];
3857                                 store->flags |= ins_flag;
3858                                 MONO_ADD_INS (bblock, store);
3859                         }
3860                         ins_flag = 0;
3861                         ip += 5;
3862                         inline_costs += 1;
3863                         break;
3864                 case CEE_BOX: {
3865                         MonoInst *iargs [2];
3866                         MonoInst *load, *vtoffset, *add, *val, *vstore;
3867                         int temp;
3868                         CHECK_STACK (1);
3869                         --sp;
3870                         val = *sp;
3871                         token = read32 (ip + 1);
3872                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3873                                 klass = mono_method_get_wrapper_data (method, token);
3874                         else
3875                                 klass = mono_class_get (image, token);
3876                         mono_class_init (klass);
3877
3878                         /* much like NEWOBJ */
3879                         NEW_DOMAINCONST (cfg, iargs [0]);
3880                         NEW_CLASSCONST (cfg, iargs [1], klass);
3881                         
3882                         temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
3883                         NEW_TEMPLOAD (cfg, load, temp);
3884                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
3885                         MONO_INST_NEW (cfg, add, CEE_ADD);
3886                         add->inst_left = load;
3887                         add->inst_right = vtoffset;
3888                         add->cil_code = ip;
3889                         add->klass = klass;
3890                         MONO_INST_NEW (cfg, vstore, CEE_STIND_I);
3891                         vstore->opcode = mono_type_to_stind (&klass->byval_arg);
3892                         vstore->cil_code = ip;
3893                         vstore->inst_left = add;
3894                         vstore->inst_right = val;
3895
3896                         if (vstore->opcode == CEE_STOBJ) {
3897                                 handle_stobj (cfg, bblock, add, val, ip, klass, FALSE, FALSE);
3898                         } else
3899                                 MONO_ADD_INS (bblock, vstore);
3900
3901                         NEW_TEMPLOAD (cfg, load, temp);
3902                         *sp++ = load;
3903                         ip += 5;
3904                         inline_costs += 1;
3905                         break;
3906                 }
3907                 case CEE_NEWARR:
3908                         CHECK_STACK (1);
3909                         MONO_INST_NEW (cfg, ins, *ip);
3910                         ins->cil_code = ip;
3911                         --sp;
3912
3913                         token = read32 (ip + 1);
3914
3915                         /* allocate the domainvar - becaus this is used in decompose_foreach */
3916                         if ((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot)
3917                                 mono_get_domainvar (cfg);
3918                         
3919                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3920                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
3921                         else
3922                                 klass = mono_class_get (image, token);
3923
3924                         mono_class_init (klass);
3925                         ins->inst_newa_class = klass;
3926                         ins->inst_newa_len = *sp;
3927                         ins->type = STACK_OBJ;
3928                         ip += 5;
3929                         *sp++ = ins;
3930                         inline_costs += 1;
3931                         break;
3932                 case CEE_LDLEN:
3933                         CHECK_STACK (1);
3934                         MONO_INST_NEW (cfg, ins, *ip);
3935                         ins->cil_code = ip++;
3936                         --sp;
3937                         ins->inst_left = *sp;
3938                         ins->type = STACK_PTR;
3939                         *sp++ = ins;
3940                         break;
3941                 case CEE_LDELEMA:
3942                         CHECK_STACK (2);
3943                         sp -= 2;
3944                         klass = mono_class_get (image, read32 (ip + 1));
3945                         mono_class_init (klass);
3946                         NEW_LDELEMA (cfg, ins, sp, klass);
3947                         ins->cil_code = ip;
3948                         *sp++ = ins;
3949                         ip += 5;
3950                         break;
3951                 case CEE_LDELEM_I1:
3952                 case CEE_LDELEM_U1:
3953                 case CEE_LDELEM_I2:
3954                 case CEE_LDELEM_U2:
3955                 case CEE_LDELEM_I4:
3956                 case CEE_LDELEM_U4:
3957                 case CEE_LDELEM_I8:
3958                 case CEE_LDELEM_I:
3959                 case CEE_LDELEM_R4:
3960                 case CEE_LDELEM_R8:
3961                 case CEE_LDELEM_REF: {
3962                         MonoInst *load;
3963                         /*
3964                          * translate to:
3965                          * ldind.x (ldelema (array, index))
3966                          * ldelema does the bounds check
3967                          */
3968                         CHECK_STACK (2);
3969                         sp -= 2;
3970                         klass = array_access_to_klass (*ip);
3971                         NEW_LDELEMA (cfg, load, sp, klass);
3972                         load->cil_code = ip;
3973                         MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
3974                         ins->cil_code = ip;
3975                         ins->inst_left = load;
3976                         *sp++ = ins;
3977                         ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
3978                         ++ip;
3979                         break;
3980                 }
3981                 case CEE_STELEM_I:
3982                 case CEE_STELEM_I1:
3983                 case CEE_STELEM_I2:
3984                 case CEE_STELEM_I4:
3985                 case CEE_STELEM_I8:
3986                 case CEE_STELEM_R4:
3987                 case CEE_STELEM_R8: {
3988                         MonoInst *load;
3989                         /*
3990                          * translate to:
3991                          * stind.x (ldelema (array, index), val)
3992                          * ldelema does the bounds check
3993                          */
3994                         CHECK_STACK (3);
3995                         sp -= 3;
3996                         klass = array_access_to_klass (*ip);
3997                         NEW_LDELEMA (cfg, load, sp, klass);
3998                         load->cil_code = ip;
3999                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
4000                         ins->cil_code = ip;
4001                         ins->inst_left = load;
4002                         ins->inst_right = sp [2];
4003                         ++ip;
4004                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4005                         MONO_ADD_INS (bblock, ins);
4006                         /* FIXME: add the implicit STELEM_REF castclass */
4007                         inline_costs += 1;
4008                         cfg->disable_ssa = TRUE;
4009                         break;
4010                 }
4011                 case CEE_STELEM_REF: {
4012                         MonoInst *iargs [3];
4013
4014                         CHECK_STACK (3);
4015                         sp -= 3;
4016
4017                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4018
4019                         iargs [2] = sp [2];
4020                         iargs [1] = sp [1];
4021                         iargs [0] = sp [0];
4022                         
4023                         mono_emit_jit_icall (cfg, bblock, helper_stelem_ref, iargs, ip);
4024
4025                         /*
4026                         MonoInst *group;
4027                         NEW_GROUP (cfg, group, sp [0], sp [1]);
4028                         MONO_INST_NEW (cfg, ins, CEE_STELEM_REF);
4029                         ins->cil_code = ip;
4030                         ins->inst_left = group;
4031                         ins->inst_right = sp [2];
4032                         MONO_ADD_INS (bblock, ins);
4033                         */
4034
4035                         ++ip;
4036                         inline_costs += 1;
4037                         cfg->disable_ssa = TRUE;
4038                         break;
4039                 }
4040                 case CEE_CKFINITE: {
4041                         MonoInst *store, *temp;
4042                         CHECK_STACK (1);
4043
4044                         /* this instr. can throw exceptions as side effect,
4045                          * so we cant eliminate dead code which contains CKFINITE opdodes.
4046                          * Spilling to memory makes sure that we always perform
4047                          * this check */
4048
4049                         
4050                         MONO_INST_NEW (cfg, ins, CEE_CKFINITE);
4051                         ins->cil_code = ip;
4052                         ins->inst_left = sp [-1];
4053                         temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
4054
4055                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
4056                         store->cil_code = ip;
4057                         MONO_ADD_INS (bblock, store);
4058
4059                         NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
4060                        
4061                         ++ip;
4062                         break;
4063                 }
4064                 case CEE_REFANYVAL:
4065                 case CEE_MKREFANY:
4066                         g_error ("opcode 0x%02x not handled", *ip);
4067                         break;
4068                 case CEE_LDTOKEN: {
4069                         gpointer handle;
4070                         MonoClass *handle_class;
4071
4072                         CHECK_STACK_OVF (1);
4073
4074                         n = read32 (ip + 1);
4075
4076                         handle = mono_ldtoken (image, n, &handle_class);
4077                         mono_class_init (handle_class);
4078
4079                         if (((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot)) {
4080                                 int temp;
4081                                 MonoInst *res, *store, *addr, *vtvar, *iargs [2];
4082
4083                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
4084
4085                                 NEW_IMAGECONST (cfg, iargs [0], image);
4086                                 NEW_ICONST (cfg, iargs [1], n);
4087                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
4088                                 NEW_TEMPLOAD (cfg, res, temp);
4089                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
4090                                 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
4091                                 MONO_ADD_INS (bblock, store);
4092                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
4093                         } else {
4094                                 if ((ip [5] == CEE_CALL) && (cmethod = mono_get_method (image, read32 (ip + 6), NULL)) &&
4095                                                 (cmethod->klass == mono_defaults.monotype_class->parent) &&
4096                                                 (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
4097                                         MonoClass *tclass = mono_class_from_mono_type (handle);
4098                                         mono_class_init (tclass);
4099                                         NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
4100                                         ins->type = STACK_OBJ;
4101                                         ins->klass = cmethod->klass;
4102                                         ip += 5;
4103                                 } else {
4104                                         NEW_PCONST (cfg, ins, handle);
4105                                         ins->type = STACK_VTYPE;
4106                                         ins->klass = handle_class;
4107                                 }
4108                         }
4109
4110                         *sp++ = ins;
4111                         ip += 5;
4112                         break;
4113                 }
4114                 case CEE_CONV_U2:
4115                 case CEE_CONV_U1:
4116                 case CEE_CONV_I:
4117                         CHECK_STACK (1);
4118                         ADD_UNOP (*ip);
4119                         ip++;
4120                         break;
4121                 case CEE_ADD_OVF:
4122                 case CEE_ADD_OVF_UN:
4123                 case CEE_MUL_OVF:
4124                 case CEE_MUL_OVF_UN:
4125                 case CEE_SUB_OVF:
4126                 case CEE_SUB_OVF_UN:
4127                         CHECK_STACK (2);
4128                         ADD_BINOP (*ip);
4129                         ip++;
4130                         break;
4131                 case CEE_ENDFINALLY:
4132                         /* FIXME: check stack state */
4133                         MONO_INST_NEW (cfg, ins, *ip);
4134                         MONO_ADD_INS (bblock, ins);
4135                         ins->cil_code = ip++;
4136                         start_new_bblock = 1;
4137                         break;
4138                 case CEE_LEAVE:
4139                 case CEE_LEAVE_S: {
4140                         GList *handlers;
4141                         if (*ip == CEE_LEAVE) {
4142                                 target = ip + 5 + (gint32)read32(ip + 1);
4143                         } else {
4144                                 target = ip + 2 + (signed char)(ip [1]);
4145                         }
4146
4147                         /* empty the stack */
4148                         while (sp != stack_start) {
4149                                 MONO_INST_NEW (cfg, ins, CEE_POP);
4150                                 ins->cil_code = ip;
4151                                 sp--;
4152                                 ins->inst_i0 = *sp;
4153                                 MONO_ADD_INS (bblock, ins);
4154                         }
4155
4156                         /* fixme: call fault handler ? */
4157
4158                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
4159                                 GList *tmp;
4160                                 for (tmp = handlers; tmp; tmp = tmp->next) {
4161                                         tblock = tmp->data;
4162                                         link_bblock (cfg, bblock, tblock);
4163                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
4164                                         ins->cil_code = ip;
4165                                         ins->inst_target_bb = tblock;
4166                                         MONO_ADD_INS (bblock, ins);
4167                                 }
4168                                 g_list_free (handlers);
4169                         } 
4170
4171                         MONO_INST_NEW (cfg, ins, CEE_BR);
4172                         ins->cil_code = ip;
4173                         MONO_ADD_INS (bblock, ins);
4174                         GET_BBLOCK (cfg, bbhash, tblock, target);
4175                         link_bblock (cfg, bblock, tblock);
4176                         CHECK_BBLOCK (target, ip, tblock);
4177                         ins->inst_target_bb = tblock;
4178                         start_new_bblock = 1;
4179
4180                         if (*ip == CEE_LEAVE)
4181                                 ip += 5;
4182                         else
4183                                 ip += 2;
4184
4185                         break;
4186                 }
4187                 case CEE_STIND_I:
4188                         CHECK_STACK (2);
4189                         MONO_INST_NEW (cfg, ins, *ip);
4190                         sp -= 2;
4191                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4192                         MONO_ADD_INS (bblock, ins);
4193                         ins->cil_code = ip++;
4194                         ins->inst_i0 = sp [0];
4195                         ins->inst_i1 = sp [1];
4196                         inline_costs += 1;
4197                         break;
4198                 case CEE_CONV_U:
4199                         CHECK_STACK (1);
4200                         ADD_UNOP (*ip);
4201                         ip++;
4202                         break;
4203                 /* trampoline mono specific opcodes */
4204                 case MONO_CUSTOM_PREFIX: {
4205
4206                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
4207
4208                         switch (ip [1]) {
4209
4210                         case CEE_MONO_FUNC1: {
4211                                 int temp;
4212                                 gpointer func = NULL;
4213                                 CHECK_STACK (1);
4214                                 sp--;
4215
4216                                 switch (ip [2]) {
4217                                 case MONO_MARSHAL_CONV_STR_LPWSTR:
4218                                         func = mono_string_to_utf16;
4219                                         break;
4220                                 case MONO_MARSHAL_CONV_LPWSTR_STR:
4221                                         func = mono_string_from_utf16;
4222                                         break;
4223                                 case MONO_MARSHAL_CONV_LPSTR_STR:
4224                                         func = mono_string_new_wrapper;
4225                                         break;
4226                                 case MONO_MARSHAL_CONV_STR_LPTSTR:
4227                                 case MONO_MARSHAL_CONV_STR_LPSTR:
4228                                         func = mono_string_to_utf8;
4229                                         break;
4230                                 case MONO_MARSHAL_CONV_STR_BSTR:
4231                                         func = mono_string_to_bstr;
4232                                         break;
4233                                 case MONO_MARSHAL_CONV_STR_TBSTR:
4234                                 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
4235                                         func = mono_string_to_ansibstr;
4236                                         break;
4237                                 case MONO_MARSHAL_CONV_SB_LPSTR:
4238                                         func = mono_string_builder_to_utf8;
4239                                         break;
4240                                 case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
4241                                         func = mono_array_to_savearray;
4242                                         break;
4243                                 case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
4244                                         func = mono_array_to_lparray;
4245                                         break;
4246                                 case MONO_MARSHAL_CONV_DEL_FTN:
4247                                         func = mono_delegate_to_ftnptr;
4248                                         break;
4249                                 case MONO_MARSHAL_CONV_STRARRAY_STRLPARRAY:
4250                                         func = mono_marshal_string_array;
4251                                         break;
4252                                 default:
4253                                         g_warning ("unknown conversion %d\n", ip [2]);
4254                                         g_assert_not_reached ();
4255                                 }
4256
4257                                 temp = mono_emit_jit_icall (cfg, bblock, func, sp, ip);
4258                                 NEW_TEMPLOAD (cfg, *sp, temp);
4259                                 sp++;
4260
4261                                 ip += 3;
4262                                 inline_costs += 10 * num_calls++;
4263                                 break;
4264                         }
4265                         case CEE_MONO_PROC2: {
4266                                 gpointer func = NULL;
4267                                 CHECK_STACK (2);
4268                                 sp -= 2;
4269
4270                                 switch (ip [2]) {
4271                                 case MONO_MARSHAL_CONV_LPSTR_SB:
4272                                         func = mono_string_utf8_to_builder;
4273                                         break;
4274                                 case MONO_MARSHAL_FREE_ARRAY:
4275                                         func = mono_marshal_free_array;
4276                                         break;
4277                                 default:
4278                                         g_assert_not_reached ();
4279                                 }
4280
4281                                 mono_emit_jit_icall (cfg, bblock, func, sp, ip);
4282                                 ip += 3;
4283                                 inline_costs += 10 * num_calls++;
4284                                 break;
4285                         }
4286                         case CEE_MONO_PROC3: {
4287                                 gpointer func = NULL;
4288                                 CHECK_STACK (3);
4289                                 sp -= 3;
4290
4291                                 switch (ip [2]) {
4292                                 case MONO_MARSHAL_CONV_STR_BYVALSTR:
4293                                         func = mono_string_to_byvalstr;
4294                                         break;
4295                                 case MONO_MARSHAL_CONV_STR_BYVALWSTR:
4296                                         func = mono_string_to_byvalwstr;
4297                                         break;
4298                                 default:
4299                                         g_assert_not_reached ();
4300                                 }
4301
4302                                 mono_emit_jit_icall (cfg, bblock, func, sp, ip);
4303                                 ip += 3;
4304                                 inline_costs += 10 * num_calls++;
4305                                 break;
4306                         }
4307                         case CEE_MONO_FREE:
4308                                 CHECK_STACK (1);
4309                                 sp -= 1;
4310                                 mono_emit_jit_icall (cfg, bblock, g_free, sp, ip);
4311                                 ip += 2;
4312                                 inline_costs += 10 * num_calls++;
4313                                 break;
4314                         case CEE_MONO_LDPTR:
4315                                 CHECK_STACK_OVF (1);
4316                                 token = read32 (ip + 2);
4317                                 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
4318                                 ins->cil_code = ip;
4319                                 *sp++ = ins;
4320                                 ip += 6;
4321                                 inline_costs += 10 * num_calls++;
4322                                 break;
4323                         case CEE_MONO_VTADDR:
4324                                 CHECK_STACK (1);
4325                                 --sp;
4326                                 MONO_INST_NEW (cfg, ins, OP_VTADDR);
4327                                 ins->cil_code = ip;
4328                                 ins->type = STACK_MP;
4329                                 ins->inst_left = *sp;
4330                                 *sp++ = ins;
4331                                 ip += 2;
4332                                 break;
4333                         case CEE_MONO_NEWOBJ: {
4334                                 MonoInst *iargs [2];
4335                                 int temp;
4336                                 CHECK_STACK_OVF (1);
4337                                 token = read32 (ip + 2);
4338                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
4339                                 mono_class_init (klass);
4340                                 NEW_DOMAINCONST (cfg, iargs [0]);
4341                                 NEW_CLASSCONST (cfg, iargs [1], klass);
4342                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
4343                                 NEW_TEMPLOAD (cfg, *sp, temp);
4344                                 sp++;
4345                                 ip += 6;
4346                                 inline_costs += 10 * num_calls++;
4347                                 break;
4348                         }
4349                         case CEE_MONO_OBJADDR:
4350                                 CHECK_STACK (1);
4351                                 --sp;
4352                                 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
4353                                 ins->cil_code = ip;
4354                                 ins->type = STACK_MP;
4355                                 ins->inst_left = *sp;
4356                                 *sp++ = ins;
4357                                 ip += 2;
4358                                 break;
4359                         case CEE_MONO_LDNATIVEOBJ:
4360                                 CHECK_STACK (1);
4361                                 token = read32 (ip + 2);
4362                                 klass = mono_method_get_wrapper_data (method, token);
4363                                 g_assert (klass->valuetype);
4364                                 mono_class_init (klass);
4365                                 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
4366                                 sp [-1] = ins;
4367                                 ip += 6;
4368                                 break;
4369                         case CEE_MONO_RETOBJ:
4370                                 g_assert (cfg->ret);
4371                                 g_assert (method->signature->pinvoke); 
4372                                 CHECK_STACK (1);
4373                                 --sp;
4374                                 
4375                                 token = read32 (ip + 2);    
4376                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
4377
4378                                 NEW_RETLOADA (cfg, ins);
4379                                 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE);
4380                                 
4381                                 if (sp != stack_start)
4382                                         goto unverified;
4383                                 
4384                                 MONO_INST_NEW (cfg, ins, CEE_BR);
4385                                 ins->cil_code = ip;
4386                                 ins->inst_target_bb = end_bblock;
4387                                 MONO_ADD_INS (bblock, ins);
4388                                 link_bblock (cfg, bblock, end_bblock);
4389                                 start_new_bblock = 1;
4390                                 ip += 6;
4391                                 break;
4392                         default:
4393                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
4394                                 break;
4395                         }
4396                         break;
4397                 }
4398                 case CEE_PREFIX1: {
4399                         switch (ip [1]) {
4400                         case CEE_ARGLIST:
4401                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
4402                                 break;
4403                         case CEE_CEQ:
4404                         case CEE_CGT:
4405                         case CEE_CGT_UN:
4406                         case CEE_CLT:
4407                         case CEE_CLT_UN: {
4408                                 MonoInst *cmp;
4409                                 CHECK_STACK (2);
4410                                 MONO_INST_NEW (cfg, cmp, 256 + ip [1]);
4411                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
4412                                 sp -= 2;
4413                                 cmp->inst_i0 = sp [0];
4414                                 cmp->inst_i1 = sp [1];
4415                                 cmp->cil_code = ip;
4416                                 type_from_op (cmp);
4417                                 CHECK_TYPE (cmp);
4418                                 cmp->opcode = OP_COMPARE;
4419                                 ins->cil_code = ip;
4420                                 ins->type = STACK_I4;
4421                                 ins->inst_i0 = cmp;
4422                                 *sp++ = ins;
4423                                 ip += 2;
4424                                 break;
4425                         }
4426                         case CEE_LDFTN: {
4427                                 MonoInst *argconst;
4428                                 int temp;
4429
4430                                 CHECK_STACK_OVF (1);
4431                                 n = read32 (ip + 2);
4432                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
4433                                         cmethod = mono_method_get_wrapper_data (method, n);
4434                                 else {
4435                                         cmethod = mono_get_method (image, n, NULL);
4436
4437                                         /*
4438                                          * We can't do this in mono_ldftn, since it is used in
4439                                          * the synchronized wrapper, leading to an infinite loop.
4440                                          */
4441                                         if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
4442                                                 cmethod = mono_marshal_get_synchronized_wrapper (cmethod);
4443                                 }
4444
4445                                 mono_class_init (cmethod->klass);
4446                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4447
4448                                 NEW_METHODCONST (cfg, argconst, cmethod);
4449                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
4450                                 NEW_TEMPLOAD (cfg, *sp, temp);
4451                                 sp ++;
4452                                 
4453                                 ip += 6;
4454                                 inline_costs += 10 * num_calls++;
4455                                 break;
4456                         }
4457                         case CEE_LDVIRTFTN: {
4458                                 MonoInst *args [2];
4459                                 int temp;
4460
4461                                 CHECK_STACK (1);
4462                                 n = read32 (ip + 2);
4463                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
4464                                         cmethod = mono_method_get_wrapper_data (method, n);
4465                                 else
4466                                         cmethod = mono_get_method (image, n, NULL);
4467
4468                                 mono_class_init (cmethod->klass);
4469                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4470
4471                                 --sp;
4472                                 args [0] = *sp;
4473                                 NEW_METHODCONST (cfg, args [1], cmethod);
4474                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
4475                                 NEW_TEMPLOAD (cfg, *sp, temp);
4476                                 sp ++;
4477
4478                                 ip += 6;
4479                                 inline_costs += 10 * num_calls++;
4480                                 break;
4481                         }
4482                         case CEE_LDARG:
4483                                 CHECK_STACK_OVF (1);
4484                                 NEW_ARGLOAD (cfg, ins, read16 (ip + 2));
4485                                 ins->cil_code = ip;
4486                                 *sp++ = ins;
4487                                 ip += 4;
4488                                 break;
4489                         case CEE_LDARGA:
4490                                 CHECK_STACK_OVF (1);
4491                                 NEW_ARGLOADA (cfg, ins, read16 (ip + 2));
4492                                 ins->cil_code = ip;
4493                                 *sp++ = ins;
4494                                 ip += 4;
4495                                 break;
4496                         case CEE_STARG:
4497                                 CHECK_STACK (1);
4498                                 --sp;
4499                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4500                                 n = read16 (ip + 2);
4501                                 NEW_ARGSTORE (cfg, ins, n, *sp);
4502                                 ins->cil_code = ip;
4503                                 if (ins->opcode == CEE_STOBJ) {
4504                                         NEW_ARGLOADA (cfg, ins, n);
4505                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
4506                                 } else
4507                                         MONO_ADD_INS (bblock, ins);
4508                                 ip += 4;
4509                                 break;
4510                         case CEE_LDLOC:
4511                                 CHECK_STACK_OVF (1);
4512                                 NEW_LOCLOAD (cfg, ins, read16 (ip + 2));
4513                                 ins->cil_code = ip;
4514                                 *sp++ = ins;
4515                                 ip += 4;
4516                                 break;
4517                         case CEE_LDLOCA:
4518                                 CHECK_STACK_OVF (1);
4519                                 NEW_LOCLOADA (cfg, ins, read16 (ip + 2));
4520                                 ins->cil_code = ip;
4521                                 *sp++ = ins;
4522                                 ip += 4;
4523                                 break;
4524                         case CEE_STLOC:
4525                                 CHECK_STACK (1);
4526                                 --sp;
4527                                 n = read16 (ip + 2);
4528                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4529                                 NEW_LOCSTORE (cfg, ins, n, *sp);
4530                                 ins->cil_code = ip;
4531                                 if (ins->opcode == CEE_STOBJ) {
4532                                         NEW_LOCLOADA (cfg, ins, n);
4533                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
4534                                 } else
4535                                         MONO_ADD_INS (bblock, ins);
4536                                 ip += 4;
4537                                 inline_costs += 1;
4538                                 break;
4539                         case CEE_LOCALLOC:
4540                                 CHECK_STACK (1);
4541                                 --sp;
4542                                 if (sp != stack_start) 
4543                                         goto unverified;
4544                                 MONO_INST_NEW (cfg, ins, 256 + ip [1]);
4545                                 ins->inst_left = *sp;
4546                                 ins->cil_code = ip;
4547
4548                                 if (header->init_locals)
4549                                         ins->flags |= MONO_INST_INIT;
4550
4551                                 *sp++ = ins;
4552                                 ip += 2;
4553                                 /* FIXME: set init flag if locals init is set in this method */
4554                                 break;
4555                         case CEE_ENDFILTER: {
4556                                 MonoExceptionClause *clause, *nearest;
4557                                 int cc, nearest_num;
4558
4559                                 CHECK_STACK (1);
4560                                 --sp;
4561                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
4562                                         goto unverified;
4563                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
4564                                 ins->inst_left = *sp;
4565                                 ins->cil_code = ip;
4566                                 MONO_ADD_INS (bblock, ins);
4567                                 start_new_bblock = 1;
4568                                 ip += 2;
4569
4570                                 nearest = NULL;
4571                                 for (cc = 0; cc < header->num_clauses; ++cc) {
4572                                         clause = &header->clauses [cc];
4573                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
4574                                             (!nearest || (clause->token_or_filter > nearest->token_or_filter))) {
4575                                                 nearest = clause;
4576                                                 nearest_num = cc;
4577                                         }
4578                                 }
4579                                 g_assert (nearest);
4580                                 filter_lengths [nearest_num] = (ip - header->code) -  nearest->token_or_filter;
4581
4582                                 break;
4583                         }
4584                         case CEE_UNALIGNED_:
4585                                 ins_flag |= MONO_INST_UNALIGNED;
4586                                 ip += 3;
4587                                 break;
4588                         case CEE_VOLATILE_:
4589                                 ins_flag |= MONO_INST_VOLATILE;
4590                                 ip += 2;
4591                                 break;
4592                         case CEE_TAIL_:
4593                                 ins_flag |= MONO_INST_TAILCALL;
4594                                 ip += 2;
4595                                 break;
4596                         case CEE_INITOBJ:
4597                                 CHECK_STACK (1);
4598                                 --sp;
4599                                 token = read32 (ip + 2);
4600                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
4601                                         klass = mono_method_get_wrapper_data (method, token);
4602                                 else
4603                                         klass = mono_class_get (image, token);
4604                                 handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
4605                                 ip += 6;
4606                                 inline_costs += 1;
4607                                 break;
4608                         case CEE_CPBLK:
4609                         case CEE_INITBLK: {
4610                                 MonoInst *iargs [3];
4611                                 CHECK_STACK (3);
4612                                 sp -= 3;
4613                                 iargs [0] = sp [0];
4614                                 iargs [1] = sp [1];
4615                                 iargs [2] = sp [2];
4616                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4617                                 if (ip [1] == CEE_CPBLK) {
4618                                         mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
4619                                 } else {
4620                                         mono_emit_jit_icall (cfg, bblock, helper_memset, iargs, ip);
4621                                 }
4622                                 ip += 2;
4623                                 inline_costs += 1;
4624                                 break;
4625                         }
4626                         case CEE_RETHROW: {
4627                                 MonoInst *load;
4628                                 /* FIXME: check we are in a catch handler */
4629                                 NEW_TEMPLOAD (cfg, load, cfg->exvar->inst_c0);
4630                                 load->cil_code = ip;
4631                                 MONO_INST_NEW (cfg, ins, CEE_THROW);
4632                                 ins->inst_left = load;
4633                                 ins->cil_code = ip;
4634                                 MONO_ADD_INS (bblock, ins);
4635                                 sp = stack_start;
4636                                 start_new_bblock = 1;
4637                                 ip += 2;
4638                                 break;
4639                         }
4640                         case CEE_SIZEOF:
4641                                 CHECK_STACK_OVF (1);
4642                                 token = read32 (ip + 2);
4643                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
4644                                         MonoType *type = mono_type_create_from_typespec (image, token);
4645                                         token = mono_type_size (type, &align);
4646                                         mono_metadata_free_type (type);
4647                                 } else {
4648                                         MonoClass *szclass = mono_class_get (image, token);
4649                                         mono_class_init (szclass);
4650                                         token = mono_class_value_size (szclass, &align);
4651                                 }
4652                                 NEW_ICONST (cfg, ins, token);
4653                                 ins->cil_code = ip;
4654                                 *sp++= ins;
4655                                 ip += 6;
4656                                 break;
4657                         case CEE_REFANYTYPE:
4658                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
4659                                 break;
4660                         default:
4661                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
4662                         }
4663                         break;
4664                 }
4665                 default:
4666                         g_error ("opcode 0x%02x not handled", *ip);
4667                 }
4668         }
4669         if (start_new_bblock != 1)
4670                 goto unverified;
4671
4672         bblock->cil_length = ip - bblock->cil_code;
4673         bblock->next_bb = end_bblock;
4674         link_bblock (cfg, bblock, end_bblock);
4675
4676         if (cfg->method == method && cfg->domainvar) {
4677                 MonoCallInst *call;
4678                 MonoInst *store;
4679
4680                 MONO_INST_NEW_CALL (cfg, call, CEE_CALL);
4681                 call->signature = helper_sig_domain_get;
4682                 call->inst.type = STACK_PTR;
4683                 call->fptr = mono_domain_get;
4684                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, (MonoInst*)call);
4685                 
4686                 MONO_ADD_INS (init_localsbb, store);
4687         }
4688
4689         if (header->init_locals) {
4690                 MonoInst *store;
4691                 for (i = 0; i < header->num_locals; ++i) {
4692                         int t = header->locals [i]->type;
4693                         if (t == MONO_TYPE_VALUETYPE && header->locals [i]->data.klass->enumtype)
4694                                 t = header->locals [i]->data.klass->enum_basetype->type;
4695                         /* FIXME: use initobj for valuetypes, handle pointers, long, float. */
4696                         if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
4697                                 NEW_ICONST (cfg, ins, 0);
4698                                 NEW_LOCSTORE (cfg, store, i, ins);
4699                                 MONO_ADD_INS (init_localsbb, store);
4700                         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
4701                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
4702                                 ins->type = STACK_I8;
4703                                 ins->inst_l = 0;
4704                                 NEW_LOCSTORE (cfg, store, i, ins);
4705                                 MONO_ADD_INS (init_localsbb, store);
4706                         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
4707                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
4708                                 ins->type = STACK_R8;
4709                                 ins->inst_p0 = (void*)&r8_0;
4710                                 NEW_LOCSTORE (cfg, store, i, ins);
4711                                 MONO_ADD_INS (init_localsbb, store);
4712                         } else if (t == MONO_TYPE_VALUETYPE) {
4713                                 NEW_LOCLOADA (cfg, ins, i);
4714                                 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (header->locals [i]), NULL, NULL);
4715                                 break;
4716                         } else {
4717                                 NEW_PCONST (cfg, ins, NULL);
4718                                 NEW_LOCSTORE (cfg, store, i, ins);
4719                                 MONO_ADD_INS (init_localsbb, store);
4720                         }
4721                 }
4722         }
4723
4724         
4725         /* resolve backward branches in the middle of an existing basic block */
4726         for (tmp = bb_recheck; tmp; tmp = tmp->next) {
4727                 bblock = tmp->data;
4728                 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
4729                 tblock = find_previous (bbhash, start_bblock, bblock->cil_code);
4730                 if (tblock != start_bblock) {
4731                         int l;
4732                         split_bblock (cfg, tblock, bblock);
4733                         l = bblock->cil_code - header->code;
4734                         bblock->cil_length = tblock->cil_length - l;
4735                         tblock->cil_length = l;
4736                 } else {
4737                         g_print ("recheck failed.\n");
4738                 }
4739         }
4740
4741         /* we compute regions here, because the length of filter clauses is not known in advance.
4742         * It is computed in the CEE_ENDFILTER case in the above switch statement*/
4743         if (cfg->method == method) {
4744                 MonoBasicBlock *bb;
4745                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4746                         bb->region = mono_find_block_region (cfg, bb->real_offset, filter_lengths);
4747                         if (cfg->verbose_level > 2)
4748                                 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
4749                 }
4750         } else {
4751                 g_hash_table_destroy (bbhash);
4752         }
4753
4754         dont_inline = g_list_remove (dont_inline, method);
4755         return inline_costs;
4756
4757  inline_failure:
4758         if (cfg->method != method) 
4759                 g_hash_table_destroy (bbhash);
4760         dont_inline = g_list_remove (dont_inline, method);
4761         return -1;
4762
4763  unverified:
4764         if (cfg->method != method) 
4765                 g_hash_table_destroy (bbhash);
4766         g_error ("Invalid IL code at IL%04x in %s: %s\n", ip - header->code, 
4767                  mono_method_full_name (method, TRUE), mono_disasm_code_one (NULL, method, ip, NULL));
4768         dont_inline = g_list_remove (dont_inline, method);
4769         return -1;
4770 }
4771
4772 void
4773 mono_print_tree (MonoInst *tree) {
4774         int arity;
4775
4776         if (!tree)
4777                 return;
4778
4779         arity = mono_burg_arity [tree->opcode];
4780
4781         printf (" %s%s", arity?"(":"",  mono_inst_name (tree->opcode));
4782
4783         switch (tree->opcode) {
4784         case OP_ICONST:
4785                 printf ("[%d]", tree->inst_c0);
4786                 break;
4787         case OP_I8CONST:
4788                 printf ("[%lld]", tree->inst_l);
4789                 break;
4790         case OP_R8CONST:
4791                 printf ("[%f]", *(double*)tree->inst_p0);
4792                 break;
4793         case OP_R4CONST:
4794                 printf ("[%f]", *(float*)tree->inst_p0);
4795                 break;
4796         case OP_ARG:
4797         case OP_LOCAL:
4798                 printf ("[%d]", tree->inst_c0);
4799                 break;
4800         case OP_REGOFFSET:
4801                 printf ("[0x%x(%s)]", tree->inst_offset, mono_arch_regname (tree->inst_basereg));
4802                 break;
4803         case OP_REGVAR:
4804                 printf ("[%s]", mono_arch_regname (tree->dreg));
4805                 break;
4806         case CEE_NEWARR:
4807                 printf ("[%s]",  tree->inst_newa_class->name);
4808                 mono_print_tree (tree->inst_newa_len);
4809                 break;
4810         case CEE_CALL:
4811         case CEE_CALLVIRT:
4812         case OP_FCALL:
4813         case OP_FCALLVIRT:
4814         case OP_LCALL:
4815         case OP_LCALLVIRT:
4816         case OP_VCALL:
4817         case OP_VCALLVIRT:
4818         case OP_VOIDCALL:
4819         case OP_VOIDCALLVIRT: {
4820                 MonoCallInst *call = (MonoCallInst*)tree;
4821                 if (call->method)
4822                         printf ("[%s]", call->method->name);
4823                 break;
4824         }
4825         case OP_PHI: {
4826                 int i;
4827                 printf ("[%d (", tree->inst_c0);
4828                 for (i = 0; i < tree->inst_phi_args [0]; i++) {
4829                         if (i)
4830                                 printf (", ");
4831                         printf ("%d", tree->inst_phi_args [i + 1]);
4832                 }
4833                 printf (")]");
4834                 break;
4835         }
4836         case OP_RENAME:
4837         case OP_RETARG:
4838         case CEE_NOP:
4839         case CEE_JMP:
4840         case CEE_BREAK:
4841                 break;
4842         case CEE_BR:
4843                 printf ("[B%d]", tree->inst_target_bb->block_num);
4844                 break;
4845         case CEE_SWITCH:
4846         case CEE_ISINST:
4847         case CEE_CASTCLASS:
4848         case OP_OUTARG:
4849         case OP_CALL_REG:
4850         case OP_FCALL_REG:
4851         case OP_LCALL_REG:
4852         case OP_VCALL_REG:
4853         case OP_VOIDCALL_REG:
4854                 mono_print_tree (tree->inst_left);
4855                 break;
4856         case CEE_BNE_UN:
4857         case CEE_BEQ:
4858         case CEE_BLT:
4859         case CEE_BLT_UN:
4860         case CEE_BGT:
4861         case CEE_BGT_UN:
4862         case CEE_BGE:
4863         case CEE_BGE_UN:
4864         case CEE_BLE:
4865         case CEE_BLE_UN:
4866                 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
4867                 mono_print_tree (tree->inst_left);
4868                 break;
4869         default:
4870                 if (arity) {
4871                         mono_print_tree (tree->inst_left);
4872                         if (arity > 1)
4873                                 mono_print_tree (tree->inst_right);
4874                 }
4875                 break;
4876         }
4877
4878         if (arity)
4879                 printf (")");
4880 }
4881
4882 static void
4883 create_helper_signature (void)
4884 {
4885         /* FIXME: set call conv */
4886         /* MonoArray * mono_array_new (MonoDomain *domain, MonoClass *klass, gint32 len) */
4887         helper_sig_newarr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4888         helper_sig_newarr->params [0] = helper_sig_newarr->params [1] = &mono_defaults.int_class->byval_arg;
4889         helper_sig_newarr->ret = &mono_defaults.object_class->byval_arg;
4890         helper_sig_newarr->params [2] = &mono_defaults.int32_class->byval_arg;
4891         helper_sig_newarr->pinvoke = 1;
4892
4893         /* MonoArray * mono_array_new_specific (MonoVTable *vtable, guint32 len) */
4894         helper_sig_newarr_specific = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4895         helper_sig_newarr_specific->params [0] = &mono_defaults.int_class->byval_arg;
4896         helper_sig_newarr_specific->params [1] = &mono_defaults.int32_class->byval_arg;
4897         helper_sig_newarr_specific->ret = &mono_defaults.object_class->byval_arg;
4898         helper_sig_newarr_specific->pinvoke = 1;
4899
4900         /* MonoObject * mono_object_new (MonoDomain *domain, MonoClass *klass) */
4901         helper_sig_object_new = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4902         helper_sig_object_new->params [0] = helper_sig_object_new->params [1] = &mono_defaults.int_class->byval_arg;
4903         helper_sig_object_new->ret = &mono_defaults.object_class->byval_arg;
4904         helper_sig_object_new->pinvoke = 1;
4905
4906         /* MonoObject * mono_object_new_specific (MonoVTable *vtable) */
4907         helper_sig_object_new_specific = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4908         helper_sig_object_new_specific->params [0] = &mono_defaults.int_class->byval_arg;
4909         helper_sig_object_new_specific->ret = &mono_defaults.object_class->byval_arg;
4910         helper_sig_object_new_specific->pinvoke = 1;
4911
4912         /* void* mono_method_compile (MonoMethod*) */
4913         helper_sig_compile = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4914         helper_sig_compile->params [0] = helper_sig_compile->ret = &mono_defaults.int_class->byval_arg;
4915         helper_sig_compile->pinvoke = 1;
4916
4917         /* void* mono_ldvirtfn (MonoObject *, MonoMethod*) */
4918         helper_sig_compile_virt = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4919         helper_sig_compile_virt->params [0] = &mono_defaults.object_class->byval_arg;
4920         helper_sig_compile_virt->params [1] = helper_sig_compile_virt->ret = &mono_defaults.int_class->byval_arg;
4921         helper_sig_compile_virt->pinvoke = 1;
4922
4923         /* MonoString* mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 str_index) */
4924         helper_sig_ldstr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4925         helper_sig_ldstr->params [0] = helper_sig_ldstr->params [1] = &mono_defaults.int_class->byval_arg;
4926         helper_sig_ldstr->params [2] = &mono_defaults.int32_class->byval_arg;
4927         helper_sig_ldstr->ret = &mono_defaults.object_class->byval_arg;
4928         helper_sig_ldstr->pinvoke = 1;
4929
4930         /* MonoDomain *mono_domain_get (void) */
4931         helper_sig_domain_get = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4932         helper_sig_domain_get->ret = &mono_defaults.int_class->byval_arg;
4933         helper_sig_domain_get->pinvoke = 1;
4934
4935         /* void* stelem_ref (MonoArray *, int index, MonoObject *) */
4936         helper_sig_stelem_ref = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4937         helper_sig_stelem_ref->params [0] = &mono_defaults.array_class->byval_arg;
4938         helper_sig_stelem_ref->params [1] = &mono_defaults.int32_class->byval_arg;
4939         helper_sig_stelem_ref->params [2] = &mono_defaults.object_class->byval_arg;
4940         helper_sig_stelem_ref->ret = &mono_defaults.void_class->byval_arg;
4941         helper_sig_stelem_ref->pinvoke = 1;
4942
4943         /* long amethod (long, long) */
4944         helper_sig_long_long_long = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4945         helper_sig_long_long_long->params [0] = helper_sig_long_long_long->params [1] = 
4946                 &mono_defaults.int64_class->byval_arg;
4947         helper_sig_long_long_long->ret = &mono_defaults.int64_class->byval_arg;
4948         helper_sig_long_long_long->pinvoke = 1;
4949
4950         /* object  amethod (intptr) */
4951         helper_sig_obj_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4952         helper_sig_obj_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4953         helper_sig_obj_ptr->ret = &mono_defaults.object_class->byval_arg;
4954         helper_sig_obj_ptr->pinvoke = 1;
4955
4956         /* void amethod (intptr) */
4957         helper_sig_void_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4958         helper_sig_void_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4959         helper_sig_void_ptr->ret = &mono_defaults.void_class->byval_arg;
4960         helper_sig_void_ptr->pinvoke = 1;
4961
4962         /* void amethod (MonoObject *obj) */
4963         helper_sig_void_obj = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4964         helper_sig_void_obj->params [0] = &mono_defaults.object_class->byval_arg;
4965         helper_sig_void_obj->ret = &mono_defaults.void_class->byval_arg;
4966         helper_sig_void_obj->pinvoke = 1;
4967
4968         /* intptr amethod (void) */
4969         helper_sig_ptr_void = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4970         helper_sig_ptr_void->ret = &mono_defaults.int_class->byval_arg;
4971         helper_sig_ptr_void->pinvoke = 1;
4972
4973         /* void  amethod (intptr, intptr) */
4974         helper_sig_void_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4975         helper_sig_void_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4976         helper_sig_void_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
4977         helper_sig_void_ptr_ptr->ret = &mono_defaults.void_class->byval_arg;
4978         helper_sig_void_ptr_ptr->pinvoke = 1;
4979
4980         /* void  amethod (intptr, intptr, intptr) */
4981         helper_sig_void_ptr_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4982         helper_sig_void_ptr_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4983         helper_sig_void_ptr_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
4984         helper_sig_void_ptr_ptr_ptr->params [2] = &mono_defaults.int_class->byval_arg;
4985         helper_sig_void_ptr_ptr_ptr->ret = &mono_defaults.void_class->byval_arg;
4986         helper_sig_void_ptr_ptr_ptr->pinvoke = 1;
4987
4988         /* intptr  amethod (intptr, intptr) */
4989         helper_sig_ptr_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4990         helper_sig_ptr_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4991         helper_sig_ptr_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
4992         helper_sig_ptr_ptr_ptr->ret = &mono_defaults.int_class->byval_arg;
4993         helper_sig_ptr_ptr_ptr->pinvoke = 1;
4994
4995         /* IntPtr  amethod (object) */
4996         helper_sig_ptr_obj = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4997         helper_sig_ptr_obj->params [0] = &mono_defaults.object_class->byval_arg;
4998         helper_sig_ptr_obj->ret = &mono_defaults.int_class->byval_arg;
4999         helper_sig_ptr_obj->pinvoke = 1;
5000
5001         /* IntPtr  amethod (int) */
5002         helper_sig_ptr_int = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5003         helper_sig_ptr_int->params [0] = &mono_defaults.int32_class->byval_arg;
5004         helper_sig_ptr_int->ret = &mono_defaults.int_class->byval_arg;
5005         helper_sig_ptr_int->pinvoke = 1;
5006
5007         /* long amethod (long, guint32) */
5008         helper_sig_long_long_int = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5009         helper_sig_long_long_int->params [0] = &mono_defaults.int64_class->byval_arg;
5010         helper_sig_long_long_int->params [1] = &mono_defaults.int32_class->byval_arg;
5011         helper_sig_long_long_int->ret = &mono_defaults.int64_class->byval_arg;
5012         helper_sig_long_long_int->pinvoke = 1;
5013
5014         /* ulong amethod (double) */
5015         helper_sig_ulong_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5016         helper_sig_ulong_double->params [0] = &mono_defaults.double_class->byval_arg;
5017         helper_sig_ulong_double->ret = &mono_defaults.uint64_class->byval_arg;
5018         helper_sig_ulong_double->pinvoke = 1;
5019
5020         /* long amethod (double) */
5021         helper_sig_long_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5022         helper_sig_long_double->params [0] = &mono_defaults.double_class->byval_arg;
5023         helper_sig_long_double->ret = &mono_defaults.int64_class->byval_arg;
5024         helper_sig_long_double->pinvoke = 1;
5025
5026         /* uint amethod (double) */
5027         helper_sig_uint_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5028         helper_sig_uint_double->params [0] = &mono_defaults.double_class->byval_arg;
5029         helper_sig_uint_double->ret = &mono_defaults.uint32_class->byval_arg;
5030         helper_sig_uint_double->pinvoke = 1;
5031
5032         /* int amethod (double) */
5033         helper_sig_int_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
5034         helper_sig_int_double->params [0] = &mono_defaults.double_class->byval_arg;
5035         helper_sig_int_double->ret = &mono_defaults.int32_class->byval_arg;
5036         helper_sig_int_double->pinvoke = 1;
5037
5038         /* void  initobj (intptr, int size) */
5039         helper_sig_initobj = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
5040         helper_sig_initobj->params [0] = &mono_defaults.int_class->byval_arg;
5041         helper_sig_initobj->params [1] = &mono_defaults.int32_class->byval_arg;
5042         helper_sig_initobj->ret = &mono_defaults.void_class->byval_arg;
5043         helper_sig_initobj->pinvoke = 1;
5044
5045         /* void  memcpy (intptr, intptr, int size) */
5046         helper_sig_memcpy = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
5047         helper_sig_memcpy->params [0] = &mono_defaults.int_class->byval_arg;
5048         helper_sig_memcpy->params [1] = &mono_defaults.int_class->byval_arg;
5049         helper_sig_memcpy->params [2] = &mono_defaults.int32_class->byval_arg;
5050         helper_sig_memcpy->ret = &mono_defaults.void_class->byval_arg;
5051         helper_sig_memcpy->pinvoke = 1;
5052
5053         /* void  memset (intptr, int val, int size) */
5054         helper_sig_memset = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
5055         helper_sig_memset->params [0] = &mono_defaults.int_class->byval_arg;
5056         helper_sig_memset->params [1] = &mono_defaults.int32_class->byval_arg;
5057         helper_sig_memset->params [2] = &mono_defaults.int32_class->byval_arg;
5058         helper_sig_memset->ret = &mono_defaults.void_class->byval_arg;
5059         helper_sig_memset->pinvoke = 1;
5060 }
5061
5062 static GHashTable *jit_icall_hash_name = NULL;
5063 static GHashTable *jit_icall_hash_addr = NULL;
5064
5065 MonoJitICallInfo *
5066 mono_find_jit_icall_by_name (const char *name)
5067 {
5068         g_assert (jit_icall_hash_name);
5069
5070         //printf ("lookup addr %s %p\n", name, g_hash_table_lookup (jit_icall_hash_name, name));
5071         return g_hash_table_lookup (jit_icall_hash_name, name);
5072 }
5073
5074 MonoJitICallInfo *
5075 mono_find_jit_icall_by_addr (gconstpointer addr)
5076 {
5077         g_assert (jit_icall_hash_addr);
5078
5079         return g_hash_table_lookup (jit_icall_hash_addr, (gpointer)addr);
5080 }
5081
5082 gconstpointer
5083 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
5084 {
5085         char *name;
5086         MonoMethod *wrapper;
5087         
5088         if (callinfo->wrapper)
5089                 return callinfo->wrapper;
5090         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
5091         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func);
5092         callinfo->wrapper = mono_jit_compile_method (wrapper);
5093         g_free (name);
5094         return callinfo->wrapper;
5095 }
5096
5097 MonoJitICallInfo *
5098 mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save)
5099 {
5100         MonoJitICallInfo *info;
5101         
5102         g_assert (func);
5103         g_assert (name);
5104
5105         if (!jit_icall_hash_name) {
5106                 jit_icall_hash_name = g_hash_table_new (g_str_hash, g_str_equal);
5107                 jit_icall_hash_addr = g_hash_table_new (NULL, NULL);
5108         }
5109
5110         if (g_hash_table_lookup (jit_icall_hash_name, name)) {
5111                 g_warning ("jit icall already defined \"%s\"\n", name);
5112                 g_assert_not_reached ();
5113         }
5114
5115         info = g_new (MonoJitICallInfo, 1);
5116         
5117         info->name = name;
5118         info->func = func;
5119         info->sig = sig;
5120                 
5121         if (is_save
5122 #ifdef MONO_USE_EXC_TABLES
5123             || mono_arch_has_unwind_info (func)
5124 #endif
5125             ) {
5126                 info->wrapper = func;
5127         } else {
5128                 info->wrapper = NULL;
5129                 mono_icall_get_wrapper (info);
5130         }
5131
5132         g_hash_table_insert (jit_icall_hash_name, (gpointer)info->name, info);
5133         g_hash_table_insert (jit_icall_hash_addr, (gpointer)func, info);
5134         if (func != info->wrapper)
5135                 g_hash_table_insert (jit_icall_hash_addr, (gpointer)info->wrapper, info);
5136
5137         return info;
5138 }
5139
5140 static GHashTable *emul_opcode_hash = NULL;
5141
5142 static MonoJitICallInfo *
5143 mono_find_jit_opcode_emulation (int opcode)
5144 {
5145         if  (emul_opcode_hash)
5146                 return g_hash_table_lookup (emul_opcode_hash, (gpointer)opcode);
5147         else
5148                 return NULL;
5149 }
5150
5151 void
5152 mono_register_opcode_emulation (int opcode, const char *name, MonoMethodSignature *sig, gpointer func)
5153 {
5154         MonoJitICallInfo *info;
5155
5156         if (!emul_opcode_hash)
5157                 emul_opcode_hash = g_hash_table_new (NULL, NULL);
5158
5159         g_assert (!sig->hasthis);
5160         g_assert (sig->param_count < 3);
5161
5162         info = mono_register_jit_icall (func, name, sig, FALSE);
5163
5164         g_hash_table_insert (emul_opcode_hash, (gpointer)opcode, info);
5165 }
5166
5167 static void
5168 decompose_foreach (MonoInst *tree, gpointer data) 
5169 {
5170         static MonoJitICallInfo *newarr_info = NULL;
5171         static MonoJitICallInfo *newarr_specific_info = NULL;
5172         MonoJitICallInfo *info;
5173
5174         switch (tree->opcode) {
5175         case CEE_NEWARR: {
5176                 MonoCompile *cfg = data;
5177                 MonoInst *iargs [3];
5178
5179                 if (!newarr_info) {
5180                         newarr_info = mono_find_jit_icall_by_addr (mono_array_new);
5181                         g_assert (newarr_info);
5182                         newarr_specific_info = mono_find_jit_icall_by_addr (mono_array_new_specific);
5183                         g_assert (newarr_specific_info);
5184                 }
5185
5186                 if ((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot) {
5187                         NEW_DOMAINCONST (cfg, iargs [0]);
5188                         NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
5189                         iargs [2] = tree->inst_newa_len;
5190
5191                         info = newarr_info;
5192                 }
5193                 else {
5194                         MonoVTable *vtable = mono_class_vtable (cfg->domain, 
5195                                                                                                         mono_array_class_get (&tree->inst_newa_class->byval_arg, 1));
5196
5197                         NEW_PCONST (cfg, iargs [0], vtable);
5198                         iargs [1] = tree->inst_newa_len;
5199
5200                         info = newarr_specific_info;
5201                 }
5202
5203                 mono_emulate_opcode (cfg, tree, iargs, info);
5204                 break;
5205         }
5206
5207         default:
5208                 break;
5209         }
5210 }
5211
5212 void
5213 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
5214
5215         switch (mono_burg_arity [tree->opcode]) {
5216         case 0: break;
5217         case 1: 
5218                 mono_inst_foreach (tree->inst_left, func, data);
5219                 break;
5220         case 2: 
5221                 mono_inst_foreach (tree->inst_left, func, data);
5222                 mono_inst_foreach (tree->inst_right, func, data);
5223                 break;
5224         default:
5225                 g_assert_not_reached ();
5226         }
5227         func (tree, data);
5228 }
5229
5230 #if 0
5231 static void
5232 mono_print_bb_code (MonoBasicBlock *bb) {
5233         if (bb->code) {
5234                 MonoInst *c = bb->code;
5235                 while (c) {
5236                         mono_print_tree (c);
5237                         g_print ("\n");
5238                         c = c->next;
5239                 }
5240         }
5241 }
5242 #endif
5243
5244 static void
5245 print_dfn (MonoCompile *cfg) {
5246         int i, j;
5247         char *code;
5248         MonoBasicBlock *bb;
5249
5250         g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
5251
5252         for (i = 0; i < cfg->num_bblocks; ++i) {
5253                 bb = cfg->bblocks [i];
5254                 if (bb->cil_code) {
5255                         char* code1, *code2;
5256                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
5257                         if (bb->last_ins->cil_code)
5258                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
5259                         else
5260                                 code2 = g_strdup ("");
5261
5262                         code1 [strlen (code1) - 1] = 0;
5263                         code = g_strdup_printf ("%s -> %s", code1, code2);
5264                         g_free (code1);
5265                         g_free (code2);
5266                 } else
5267                         code = g_strdup ("\n");
5268                 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
5269                 if (bb->code) {
5270                         MonoInst *c = bb->code;
5271                         while (c) {
5272                                 mono_print_tree (c);
5273                                 g_print ("\n");
5274                                 c = c->next;
5275                         }
5276                 } else {
5277
5278                 }
5279
5280                 g_print ("\tprev:");
5281                 for (j = 0; j < bb->in_count; ++j) {
5282                         g_print (" BB%d", bb->in_bb [j]->block_num);
5283                 }
5284                 g_print ("\t\tsucc:");
5285                 for (j = 0; j < bb->out_count; ++j) {
5286                         g_print (" BB%d", bb->out_bb [j]->block_num);
5287                 }
5288                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
5289
5290                 if (bb->idom)
5291                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
5292
5293                 if (bb->dominators)
5294                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
5295                 if (bb->dfrontier)
5296                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
5297                 g_free (code);
5298         }
5299
5300         g_print ("\n");
5301 }
5302
5303 /*
5304  * returns the offset used by spillvar. It allocates a new
5305  * spill variable if necessary. 
5306  */
5307 int
5308 mono_spillvar_offset (MonoCompile *cfg, int spillvar)
5309 {
5310         MonoSpillInfo **si, *info;
5311         int i = 0;
5312
5313         si = &cfg->spill_info; 
5314         
5315         while (i <= spillvar) {
5316
5317                 if (!*si) {
5318                         *si = info = mono_mempool_alloc (cfg->mempool, sizeof (MonoSpillInfo));
5319                         info->next = NULL;
5320                         cfg->stack_offset -= sizeof (gpointer);
5321                         info->offset = cfg->stack_offset;
5322                 }
5323
5324                 if (i == spillvar)
5325                         return (*si)->offset;
5326
5327                 i++;
5328                 si = &(*si)->next;
5329         }
5330
5331         g_assert_not_reached ();
5332         return 0;
5333 }
5334
5335 void
5336 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
5337 {
5338         inst->next = NULL;
5339         if (bb->last_ins) {
5340                 g_assert (bb->code);
5341                 bb->last_ins->next = inst;
5342                 bb->last_ins = inst;
5343         } else {
5344                 bb->last_ins = bb->code = inst;
5345         }
5346 }
5347
5348 void
5349 mono_destroy_compile (MonoCompile *cfg)
5350 {
5351         //mono_mempool_stats (cfg->mempool);
5352         g_hash_table_destroy (cfg->bb_hash);
5353         if (cfg->rs)
5354                 mono_regstate_free (cfg->rs);
5355         mono_mempool_destroy (cfg->mempool);
5356         g_list_free (cfg->ldstr_list);
5357
5358         g_free (cfg->varinfo);
5359         g_free (cfg->vars);
5360         g_free (cfg);
5361 }
5362
5363 gpointer 
5364 mono_get_lmf_addr (void)
5365 {
5366         MonoJitTlsData *jit_tls;        
5367
5368         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
5369                 return &jit_tls->lmf;
5370
5371         g_assert_not_reached ();
5372         return NULL;
5373 }
5374
5375 /**
5376  * mono_thread_abort:
5377  * @obj: exception object
5378  *
5379  * abort the thread, print exception information and stack trace
5380  */
5381 static void
5382 mono_thread_abort (MonoObject *obj)
5383 {
5384         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
5385         
5386         g_free (jit_tls);
5387
5388         ExitThread (-1);
5389 }
5390
5391 static void
5392 mono_thread_start_cb (guint32 tid, gpointer stack_start, gpointer func)
5393 {
5394         MonoJitTlsData *jit_tls;
5395         MonoLMF *lmf;
5396
5397         jit_tls = g_new0 (MonoJitTlsData, 1);
5398
5399         TlsSetValue (mono_jit_tls_id, jit_tls);
5400
5401         jit_tls->abort_func = mono_thread_abort;
5402         jit_tls->end_of_stack = stack_start;
5403
5404         lmf = g_new0 (MonoLMF, 1);
5405         lmf->ebp = -1;
5406
5407         jit_tls->lmf = lmf;
5408 }
5409
5410 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
5411
5412 static void
5413 mono_thread_abort_dummy (MonoObject *obj)
5414 {
5415   if (mono_thread_attach_aborted_cb)
5416     mono_thread_attach_aborted_cb (obj);
5417   else
5418     mono_thread_abort (obj);
5419 }
5420
5421 static void
5422 mono_thread_attach_cb (guint32 tid, gpointer stack_start)
5423 {
5424         MonoJitTlsData *jit_tls;
5425         MonoLMF *lmf;
5426
5427         jit_tls = g_new0 (MonoJitTlsData, 1);
5428
5429         TlsSetValue (mono_jit_tls_id, jit_tls);
5430
5431         jit_tls->abort_func = mono_thread_abort_dummy;
5432         jit_tls->end_of_stack = stack_start;
5433
5434         lmf = g_new0 (MonoLMF, 1);
5435         lmf->ebp = -1;
5436
5437         jit_tls->lmf = lmf;
5438 }
5439
5440 void
5441 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
5442 {
5443         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
5444
5445         ji->ip.i = ip;
5446         ji->type = type;
5447         ji->data.target = target;
5448         ji->next = cfg->patch_info;
5449
5450         cfg->patch_info = ji;
5451 }
5452
5453 void
5454 mono_remove_patch_info (MonoCompile *cfg, int ip)
5455 {
5456         MonoJumpInfo **ji = &cfg->patch_info;
5457
5458         while (*ji) {
5459                 if ((*ji)->ip.i == ip)
5460                         *ji = (*ji)->next;
5461                 else
5462                         ji = &((*ji)->next);
5463         }
5464 }
5465
5466 static void
5467 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
5468         MonoJitICallInfo *info;
5469
5470         switch (mono_burg_arity [tree->opcode]) {
5471         case 0: break;
5472         case 1: 
5473                 dec_foreach (tree->inst_left, cfg);
5474
5475                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
5476                         MonoInst *iargs [2];
5477                 
5478                         iargs [0] = tree->inst_left;
5479
5480                         mono_emulate_opcode (cfg, tree, iargs, info);
5481                         return;
5482                 }
5483
5484                 break;
5485         case 2:
5486                 if (tree->opcode == OP_LMUL
5487                                 && (cfg->opt & MONO_OPT_INTRINS)
5488                                 && (tree->inst_left->opcode == CEE_CONV_I8 
5489                                         || tree->inst_left->opcode == CEE_CONV_U8)
5490                                 && tree->inst_left->inst_left->type == STACK_I4
5491                                 && (tree->inst_right->opcode == CEE_CONV_I8 
5492                                         || tree->inst_right->opcode == CEE_CONV_U8)
5493                                 && tree->inst_right->inst_left->type == STACK_I4) {
5494                         tree->opcode = OP_BIGMUL;
5495                         tree->inst_left = tree->inst_left->inst_left;
5496                         tree->inst_right = tree->inst_right->inst_left;
5497                         dec_foreach (tree, cfg);
5498                 } else if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
5499                         MonoInst *iargs [2];
5500                 
5501                         iargs [0] = tree->inst_i0;
5502                         iargs [1] = tree->inst_i1;
5503                 
5504                         mono_emulate_opcode (cfg, tree, iargs, info);
5505
5506                         dec_foreach (iargs [0], cfg);
5507                         dec_foreach (iargs [1], cfg);
5508                         return;
5509                 } else {
5510                         dec_foreach (tree->inst_left, cfg);
5511                         dec_foreach (tree->inst_right, cfg);
5512                 }
5513                 break;
5514         default:
5515                 g_assert_not_reached ();
5516         }
5517         decompose_foreach (tree, cfg);
5518 }
5519
5520 static void
5521 decompose_pass (MonoCompile *cfg) {
5522         MonoBasicBlock *bb;
5523
5524         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5525                 MonoInst *tree;
5526                 cfg->cbb = bb;
5527                 cfg->prev_ins = NULL;
5528                 for (tree = cfg->cbb->code; tree; tree = tree->next) {
5529                         dec_foreach (tree, cfg);
5530                         cfg->prev_ins = tree;
5531                 }
5532         }
5533 }
5534
5535 static void
5536 nullify_basic_block (MonoBasicBlock *bb) 
5537 {
5538         bb->in_count = 0;
5539         bb->out_count = 0;
5540         bb->in_bb = NULL;
5541         bb->out_bb = NULL;
5542         bb->next_bb = NULL;
5543         bb->code = bb->last_ins = NULL;
5544 }
5545
5546 static void 
5547 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
5548 {
5549         int i, j;
5550
5551         for (i = 0; i < bb->out_count; i++) {
5552                 MonoBasicBlock *ob = bb->out_bb [i];
5553                 for (j = 0; j < ob->in_count; j++) {
5554                         if (ob->in_bb [j] == orig)
5555                                 ob->in_bb [j] = repl;
5556                 }
5557         }
5558
5559 }
5560
5561 static void
5562 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn) 
5563 {
5564         bb->out_count = bbn->out_count;
5565         bb->out_bb = bbn->out_bb;
5566
5567         replace_basic_block (bb, bbn, bb);
5568
5569         if (bb->last_ins) {
5570                 if (bbn->code) {
5571                         bb->last_ins->next = bbn->code;
5572                         bb->last_ins = bbn->last_ins;
5573                 }
5574         } else {
5575                 bb->code = bbn->code;
5576                 bb->last_ins = bbn->last_ins;
5577         }
5578         bb->next_bb = bbn->next_bb;
5579         nullify_basic_block (bbn);
5580 }
5581
5582 static void
5583 optimize_branches (MonoCompile *cfg) {
5584         int changed = FALSE;
5585         MonoBasicBlock *bb, *bbn;
5586
5587         do {
5588                 changed = FALSE;
5589
5590                 /* we skip the entry block (exit is handled specially instead ) */
5591                 for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
5592
5593                         /* dont touch code inside exception clauses */
5594                         if (bb->region != -1)
5595                                 continue;
5596
5597                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
5598                                 if (cfg->verbose_level > 2)
5599                                         g_print ("nullify block triggered %d\n", bbn->block_num);
5600
5601                                 bb->next_bb = bbn->next_bb;
5602                                 nullify_basic_block (bbn);                      
5603                                 changed = TRUE;
5604                         }
5605
5606                         if (bb->out_count == 1) {
5607                                 bbn = bb->out_bb [0];
5608
5609                                 if (bb->region == bbn->region && bb->next_bb == bbn) {
5610                                 /* the block are in sequence anyway ... */
5611
5612                                         /* 
5613                                          * miguel: I do not understand what the test below does, could we
5614                                          * use a macro, or a comment here?  opcode > CEE_BEQ && <= BLT_UN
5615                                          *
5616                                          * It could also test for bb->last_in only once, and the value
5617                                          * could be cached (last_ins->opcode)
5618                                          */
5619                                         if (bb->last_ins && (bb->last_ins->opcode == CEE_BR || (
5620                                                 (bb->last_ins && bb->last_ins->opcode >= CEE_BEQ && bb->last_ins->opcode <= CEE_BLT_UN)))) {
5621                                                 bb->last_ins->opcode = CEE_NOP;
5622                                                 changed = TRUE;
5623                                                 if (cfg->verbose_level > 2)
5624                                                         g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
5625                                         }
5626                                         if (bbn->in_count == 1) {
5627
5628                                                 if (bbn != cfg->bb_exit) {
5629                                                         if (cfg->verbose_level > 2)
5630                                                                 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
5631                                                         merge_basic_blocks (bb, bbn);
5632                                                         changed = TRUE;
5633                                                 }
5634
5635                                                 //mono_print_bb_code (bb);
5636                                         }
5637                                 }
5638                         }
5639                 }
5640         } while (changed);
5641
5642         do {
5643                 changed = FALSE;
5644
5645                 /* we skip the entry block (exit is handled specially instead ) */
5646                 for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
5647
5648                         /* dont touch code inside exception clauses */
5649                         if (bb->region != -1)
5650                                 continue;
5651
5652                         if (bb->out_count == 1) {
5653                                 bbn = bb->out_bb [0];
5654
5655                                 if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
5656                                         bbn = bb->last_ins->inst_target_bb;
5657                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
5658                                             bbn->code->inst_target_bb->region == bb->region) {
5659                                                 
5660                                                 if (cfg->verbose_level > 2)
5661                                                         g_print ("in %s branch to branch triggered %d -> %d\n", cfg->method->name, 
5662                                                                  bb->block_num, bbn->block_num);
5663                                                 
5664                                                 replace_basic_block (bb, bb->out_bb [0], bbn->code->inst_target_bb);
5665                                                 bb->last_ins->inst_target_bb = bbn->code->inst_target_bb;
5666                                                 changed = TRUE;
5667                                                 break;
5668                                         }
5669                                 }
5670                         } else if (bb->out_count == 2) {
5671                                 /* fixme: this does not correctly - no idea whats wrong */
5672                                 if (0 && bb->last_ins && bb->last_ins->opcode >= CEE_BEQ && bb->last_ins->opcode <= CEE_BLT_UN) {
5673                                         bbn = bb->last_ins->inst_true_bb;
5674                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
5675                                             bbn->code->inst_target_bb->region == bb->region) {
5676                                                 if (cfg->verbose_level > 2)
5677                                                         g_print ("cbranch to branch triggered %d -> %d (0x%02x)\n", bb->block_num, 
5678                                                                  bbn->block_num, bbn->code->opcode);
5679                 
5680                                                 replace_basic_block (bb, bb->out_bb [0], bbn->code->inst_target_bb);
5681                                                 bb->last_ins->inst_true_bb = bbn->code->inst_target_bb;
5682                                                 changed = TRUE;
5683                                         }
5684
5685                                         bbn = bb->last_ins->inst_false_bb;
5686                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
5687                                             bbn->code->inst_target_bb->region == bb->region) {
5688                                                 if (cfg->verbose_level > 2)
5689                                                         g_print ("cbranch to branch triggered %d -> %d (0x%02x)\n", bb->block_num, 
5690                                                                  bbn->block_num, bbn->code->opcode);
5691                 
5692                                                 replace_basic_block (bb, bb->out_bb [0], bbn->code->inst_target_bb);
5693                                                 bb->last_ins->inst_false_bb = bbn->code->inst_target_bb;
5694                                                 changed = TRUE;
5695                                                 break;
5696                                         }
5697                                 }
5698                         }
5699                 }
5700         } while (changed);
5701
5702 }
5703
5704 static void
5705 mono_compile_create_vars (MonoCompile *cfg)
5706 {
5707         MonoMethodSignature *sig;
5708         MonoMethodHeader *header;
5709         int i;
5710
5711         header = ((MonoMethodNormal *)cfg->method)->header;
5712
5713         sig = cfg->method->signature;
5714         
5715         if (!MONO_TYPE_IS_VOID (sig->ret)) {
5716                 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
5717                 cfg->ret->opcode = OP_RETARG;
5718                 cfg->ret->inst_vtype = sig->ret;
5719                 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
5720         }
5721
5722         if (sig->hasthis)
5723                 mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
5724
5725         for (i = 0; i < sig->param_count; ++i)
5726                 mono_compile_create_var (cfg, sig->params [i], OP_ARG);
5727
5728         cfg->locals_start = cfg->num_varinfo;
5729
5730         for (i = 0; i < header->num_locals; ++i)
5731                 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
5732 }
5733
5734 #if 0
5735 static void
5736 mono_print_code (MonoCompile *cfg)
5737 {
5738         MonoBasicBlock *bb;
5739         
5740         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5741                 MonoInst *tree = bb->code;      
5742
5743                 if (!tree)
5744                         continue;
5745                 
5746                 g_print ("CODE BLOCK %d (nesting %d):\n", bb->block_num, bb->nesting);
5747
5748                 for (; tree; tree = tree->next) {
5749                         mono_print_tree (tree);
5750                         g_print ("\n");
5751                 }
5752
5753                 if (bb->last_ins)
5754                         bb->last_ins->next = NULL;
5755         }
5756 }
5757 #endif
5758
5759 extern const char * const mono_burg_rule_string [];
5760
5761 static void
5762 emit_state (MonoCompile *cfg, MBState *state, int goal)
5763 {
5764         MBState *kids [10];
5765         int ern = mono_burg_rule (state, goal);
5766         const guint16 *nts = mono_burg_nts [ern];
5767         MBEmitFunc emit;
5768
5769         //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
5770         switch (goal) {
5771         case MB_NTERM_reg:
5772                 //if (state->reg2)
5773                 //      state->reg1 = state->reg2; /* chain rule */
5774                 //else
5775                 state->reg1 = mono_regstate_next_int (cfg->rs);
5776                 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
5777                 break;
5778         case MB_NTERM_lreg:
5779                 state->reg1 = mono_regstate_next_int (cfg->rs);
5780                 state->reg2 = mono_regstate_next_int (cfg->rs);
5781                 break;
5782         case MB_NTERM_freg:
5783                 state->reg1 = mono_regstate_next_float (cfg->rs);
5784                 break;
5785         default:
5786                 /* do nothing */
5787                 break;
5788         }
5789         if (nts [0]) {
5790                 mono_burg_kids (state, ern, kids);
5791
5792                 emit_state (cfg, kids [0], nts [0]);
5793                 if (nts [1]) {
5794                         emit_state (cfg, kids [1], nts [1]);
5795                         if (nts [2]) {
5796                                 g_assert (!nts [3]);
5797                                 emit_state (cfg, kids [2], nts [2]);
5798                         }
5799                 }
5800         }
5801
5802 //      g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
5803         if ((emit = mono_burg_func [ern]))
5804                 emit (state, state->tree, cfg); 
5805 }
5806
5807 #define DEBUG_SELECTION
5808
5809 static void 
5810 mini_select_instructions (MonoCompile *cfg)
5811 {
5812         MonoBasicBlock *bb;
5813         
5814         cfg->state_pool = mono_mempool_new ();
5815         cfg->rs = mono_regstate_new ();
5816
5817 #ifdef DEBUG_SELECTION
5818         if (cfg->verbose_level >= 4) {
5819         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5820                 MonoInst *tree = bb->code;      
5821                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
5822                 if (!tree)
5823                         continue;
5824                 for (; tree; tree = tree->next) {
5825                         mono_print_tree (tree);
5826                         g_print ("\n");
5827                 }
5828         }
5829         }
5830 #endif
5831
5832         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5833                 MonoInst *tree = bb->code, *next;       
5834                 MBState *mbstate;
5835
5836                 if (!tree)
5837                         continue;
5838                 bb->code = NULL;
5839                 bb->last_ins = NULL;
5840                 
5841                 cfg->cbb = bb;
5842                 mono_regstate_reset (cfg->rs);
5843
5844 #ifdef DEBUG_SELECTION
5845                 if (cfg->verbose_level >= 3)
5846                         g_print ("LABEL BLOCK %d:\n", bb->block_num);
5847 #endif
5848                 for (; tree; tree = next) {
5849                         next = tree->next;
5850 #ifdef DEBUG_SELECTION
5851                         if (cfg->verbose_level >= 3) {
5852                                 mono_print_tree (tree);
5853                                 g_print ("\n");
5854                         }
5855 #endif
5856
5857                         if (!(mbstate = mono_burg_label (tree, cfg))) {
5858                                 g_warning ("unabled to label tree %p", tree);
5859                                 mono_print_tree (tree);
5860                                 g_print ("\n");                         
5861                                 g_assert_not_reached ();
5862                         }
5863                         emit_state (cfg, mbstate, MB_NTERM_stmt);
5864                 }
5865                 bb->max_ireg = cfg->rs->next_vireg;
5866                 bb->max_freg = cfg->rs->next_vfreg;
5867
5868                 if (bb->last_ins)
5869                         bb->last_ins->next = NULL;
5870
5871                 mono_mempool_empty (cfg->state_pool); 
5872         }
5873         mono_mempool_destroy (cfg->state_pool); 
5874 }
5875
5876 void
5877 mono_codegen (MonoCompile *cfg)
5878 {
5879         MonoJumpInfo *patch_info;
5880         MonoBasicBlock *bb;
5881         int i, max_epilog_size;
5882         guint8 *code;
5883
5884         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5885                 cfg->spill_count = 0;
5886                 /* we reuse dfn here */
5887                 /* bb->dfn = bb_count++; */
5888                 mono_arch_local_regalloc (cfg, bb);
5889         }
5890
5891         if (mono_trace_coverage)
5892                 mono_allocate_coverage_info (cfg->method, cfg->num_bblocks);
5893
5894         code = mono_arch_emit_prolog (cfg);
5895
5896         if (mono_jit_profile)
5897                 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
5898
5899         cfg->code_len = code - cfg->native_code;
5900         cfg->prolog_end = cfg->code_len;
5901
5902         mono_debug_open_method (cfg);
5903              
5904         /* emit code all basic blocks */
5905         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5906                 bb->native_offset = cfg->code_len;
5907                 mono_arch_output_basic_block (cfg, bb);
5908         }
5909         cfg->bb_exit->native_offset = cfg->code_len;
5910
5911         code = cfg->native_code + cfg->code_len;
5912
5913         max_epilog_size = mono_arch_max_epilog_size (cfg);
5914
5915         /* we always allocate code in cfg->domain->code_mp to increase locality */
5916         cfg->code_size = cfg->code_len + max_epilog_size;
5917         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
5918         code = mono_mempool_alloc (cfg->domain->code_mp, cfg->code_size);
5919         memcpy (code, cfg->native_code, cfg->code_len);
5920         g_free (cfg->native_code);
5921         cfg->native_code = code;
5922         code = cfg->native_code + cfg->code_len;
5923   
5924         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
5925
5926         cfg->epilog_begin = cfg->code_len;
5927
5928         if (mono_jit_profile)
5929                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
5930
5931         cfg->code_len = code - cfg->native_code;
5932
5933         mono_arch_emit_epilog (cfg);
5934
5935         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5936                 switch (patch_info->type) {
5937                 case MONO_PATCH_INFO_ABS: {
5938                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
5939                         if (info) {
5940                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
5941                                 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
5942                                 patch_info->data.name = info->name;
5943                         }
5944                         break;
5945                 }
5946                 case MONO_PATCH_INFO_SWITCH: {
5947                         gpointer *table = g_new (gpointer, patch_info->table_size);
5948                         patch_info->ip.i = patch_info->ip.label->inst_c0;
5949                         for (i = 0; i < patch_info->table_size; i++) {
5950                                 table [i] = (gpointer)patch_info->data.table [i]->native_offset;
5951                         }
5952                         patch_info->data.target = table;
5953                         break;
5954                 }
5955                 default:
5956                         /* do nothing */
5957                         break;
5958                 }
5959         }
5960        
5961         if (cfg->verbose_level > 1)
5962                 g_print ("Method %s::%s emmitted at %p to %p\n", cfg->method->klass->name, 
5963                          cfg->method->name, cfg->native_code, cfg->native_code + cfg->code_len);
5964
5965         mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info);
5966
5967         mono_debug_close_method (cfg);
5968 }
5969
5970 static void
5971 mono_cprop_copy_values (MonoCompile *cfg, MonoInst *tree, MonoInst **acp)
5972 {
5973         MonoInst *cp;
5974         int arity;
5975
5976         if (tree->ssa_op == MONO_SSA_LOAD && (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG) && 
5977             (cp = acp [tree->inst_i0->inst_c0]) && !tree->inst_i0->flags) {
5978
5979                 if (cp->opcode == OP_ICONST) {
5980                         if (cfg->opt & MONO_OPT_CONSPROP) {
5981                                 //{ static int c = 0; printf ("CCOPY %d %d %s\n", c++, cp->inst_c0, mono_method_full_name (cfg->method, TRUE)); }
5982                                 *tree = *cp;
5983                         }
5984                 } else {
5985                         if (tree->inst_i0->inst_vtype->type == cp->inst_vtype->type) {
5986                                 if (cfg->opt & MONO_OPT_COPYPROP) {
5987                                         //{ static int c = 0; printf ("VCOPY %d\n", ++c); }
5988                                         tree->inst_i0 = cp;
5989                                 } 
5990                         }
5991                 } 
5992         } else {
5993                 arity = mono_burg_arity [tree->opcode];
5994
5995                 if (arity) {
5996                         mono_cprop_copy_values (cfg, tree->inst_i0, acp);
5997                         if (cfg->opt & MONO_OPT_CFOLD)
5998                                 mono_constant_fold_inst (tree, NULL); 
5999                         if (arity > 1) {
6000                                 mono_cprop_copy_values (cfg, tree->inst_i1, acp);
6001                                 if (cfg->opt & MONO_OPT_CFOLD)
6002                                         mono_constant_fold_inst (tree, NULL); 
6003                         }
6004                         mono_constant_fold_inst (tree, NULL); 
6005                 }
6006         }
6007 }
6008
6009 static void
6010 mono_cprop_invalidate_values (MonoInst *tree, MonoInst **acp, int acp_size)
6011 {
6012         int arity;
6013
6014         switch (tree->opcode) {
6015         case CEE_STIND_I:
6016         case CEE_STIND_I1:
6017         case CEE_STIND_I2:
6018         case CEE_STIND_I4:
6019         case CEE_STIND_REF:
6020         case CEE_STIND_I8:
6021         case CEE_STIND_R4:
6022         case CEE_STIND_R8:
6023         case CEE_STOBJ:
6024                 if (tree->ssa_op == MONO_SSA_NOP) {
6025                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
6026                         return;
6027                 }
6028
6029                 break;
6030         case CEE_CALL:
6031         case OP_CALL_REG:
6032         case CEE_CALLVIRT:
6033         case OP_LCALL_REG:
6034         case OP_LCALLVIRT:
6035         case OP_LCALL:
6036         case OP_FCALL_REG:
6037         case OP_FCALLVIRT:
6038         case OP_FCALL:
6039         case OP_VCALL_REG:
6040         case OP_VCALLVIRT:
6041         case OP_VCALL:
6042         case OP_VOIDCALL_REG:
6043         case OP_VOIDCALLVIRT:
6044         case OP_VOIDCALL: {
6045                 MonoCallInst *call = (MonoCallInst *)tree;
6046                 MonoMethodSignature *sig = call->signature;
6047                 int i, byref = FALSE;
6048
6049                 for (i = 0; i < sig->param_count; i++) {
6050                         if (sig->params [i]->byref) {
6051                                 byref = TRUE;
6052                                 break;
6053                         }
6054                 }
6055
6056                 if (byref)
6057                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
6058
6059                 return;
6060         }
6061         default:
6062                 break;
6063         }
6064
6065         arity = mono_burg_arity [tree->opcode];
6066
6067         switch (arity) {
6068         case 0:
6069                 break;
6070         case 1:
6071                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
6072                 break;
6073         case 2:
6074                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
6075                 mono_cprop_invalidate_values (tree->inst_i1, acp, acp_size);
6076                 break;
6077         default:
6078                 g_assert_not_reached ();
6079         }
6080 }
6081
6082 static void
6083 mono_local_cprop_bb (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **acp, int acp_size)
6084 {
6085         MonoInst *tree = bb->code;      
6086         int i;
6087
6088         if (!tree)
6089                 return;
6090
6091         for (; tree; tree = tree->next) {
6092
6093                 mono_cprop_copy_values (cfg, tree, acp);
6094
6095                 mono_cprop_invalidate_values (tree, acp, acp_size);
6096
6097                 if (tree->ssa_op == MONO_SSA_STORE  && 
6098                     (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG)) {
6099                         MonoInst *i1 = tree->inst_i1;
6100
6101                         acp [tree->inst_i0->inst_c0] = NULL;
6102
6103                         for (i = 0; i < acp_size; i++) {
6104                                 if (acp [i] && acp [i]->opcode != OP_ICONST && 
6105                                     acp [i]->inst_c0 == tree->inst_i0->inst_c0) {
6106                                         acp [i] = NULL;
6107                                 }
6108                         }
6109
6110                         if (i1->opcode == OP_ICONST) {
6111                                 acp [tree->inst_i0->inst_c0] = i1;
6112                                 //printf ("DEF1 BB%d %d\n", bb->block_num,tree->inst_i0->inst_c0);
6113                         }
6114                         if (i1->ssa_op == MONO_SSA_LOAD && 
6115                             (i1->inst_i0->opcode == OP_LOCAL || i1->inst_i0->opcode == OP_ARG) &&
6116                             (i1->inst_i0->inst_c0 != tree->inst_i0->inst_c0)) {
6117                                 acp [tree->inst_i0->inst_c0] = i1->inst_i0;
6118                                 //printf ("DEF2 BB%d %d %d\n", bb->block_num,tree->inst_i0->inst_c0,i1->inst_i0->inst_c0);
6119                         }
6120                 }
6121
6122                 /*
6123                   if (tree->opcode == CEE_BEQ) {
6124                   g_assert (tree->inst_i0->opcode == OP_COMPARE);
6125                   if (tree->inst_i0->inst_i0->opcode == OP_ICONST &&
6126                   tree->inst_i0->inst_i1->opcode == OP_ICONST) {
6127                   
6128                   tree->opcode = CEE_BR;
6129                   if (tree->inst_i0->inst_i0->opcode == tree->inst_i0->inst_i1->opcode) {
6130                   tree->inst_target_bb = tree->inst_true_bb;
6131                   } else {
6132                   tree->inst_target_bb = tree->inst_false_bb;
6133                   }
6134                   }
6135                   }
6136                 */
6137         }
6138 }
6139
6140 static void
6141 mono_local_cprop (MonoCompile *cfg)
6142 {
6143         MonoBasicBlock *bb;
6144         MonoInst **acp;
6145
6146         acp = alloca (sizeof (MonoInst *) * cfg->num_varinfo);
6147
6148         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
6149                 memset (acp, 0, sizeof (MonoInst *) * cfg->num_varinfo);
6150                 mono_local_cprop_bb (cfg, bb, acp, cfg->num_varinfo);
6151         }
6152 }
6153
6154 MonoCompile*
6155 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, int parts)
6156 {
6157         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
6158         guint8 *ip = (guint8 *)header->code;
6159         MonoCompile *cfg;
6160         MonoJitInfo *jinfo;
6161         int dfn = 0, i, code_size_ratio;
6162
6163         mono_jit_stats.methods_compiled++;
6164         if (mono_jit_profile)
6165                 mono_profiler_method_jit (method);
6166
6167         cfg = g_new0 (MonoCompile, 1);
6168         cfg->method = method;
6169         cfg->mempool = mono_mempool_new ();
6170         cfg->opt = opts;
6171         cfg->bb_hash = g_hash_table_new (g_direct_hash, NULL);
6172         cfg->domain = domain;
6173         cfg->verbose_level = mini_verbose;
6174         cfg->intvars = mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * 
6175                                             ((MonoMethodNormal *)method)->header->max_stack);
6176
6177         /*
6178          * create MonoInst* which represents arguments and local variables
6179          */
6180         mono_compile_create_vars (cfg);
6181
6182         if (cfg->verbose_level > 2)
6183                 g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
6184
6185         if ((i = mono_method_to_ir (cfg, method, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
6186                 mono_destroy_compile (cfg);
6187                 if (mono_jit_profile)
6188                         mono_profiler_method_end_jit (method, MONO_PROFILE_FAILED);
6189                 return NULL;
6190         }
6191
6192         mono_jit_stats.basic_blocks += cfg->num_bblocks;
6193         mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
6194
6195         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
6196
6197         /* Depth-first ordering on basic blocks */
6198         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
6199
6200         if (cfg->opt & MONO_OPT_BRANCH)
6201                 optimize_branches (cfg);
6202
6203         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
6204         if (cfg->num_bblocks != dfn + 1) {
6205                 MonoBasicBlock *bb;
6206
6207                 cfg->num_bblocks = dfn + 1;
6208
6209                 /* we always remove unreachable code, because the code in them may be 
6210                  * inconsistent  (access to dead variables for example) */
6211                 for (bb = cfg->bb_entry; bb;) {
6212                         MonoBasicBlock *bbn = bb->next_bb;
6213
6214                         if (bbn && bbn->region == -1 && !bbn->dfn) {
6215                                 if (cfg->verbose_level > 1)
6216                                         g_print ("found unreachabel code in BB%d\n", bbn->block_num);
6217                                 bb->next_bb = bbn->next_bb;
6218                                 nullify_basic_block (bbn);                      
6219                         } else {
6220                                 bb = bb->next_bb;
6221                         }
6222                 }
6223         }
6224
6225         if (cfg->opt & MONO_OPT_LOOP) {
6226                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
6227                 mono_compute_natural_loops (cfg);
6228         }
6229
6230
6231         /* after method_to_ir */
6232         if (parts == 1)
6233                 return cfg;
6234
6235 //#define DEBUGSSA "logic_run"
6236 #define DEBUGSSA_CLASS "Tests"
6237 #ifdef DEBUGSSA
6238
6239
6240         if (!header->num_clauses && !cfg->disable_ssa) {
6241                 mono_local_cprop (cfg);
6242                 mono_ssa_compute (cfg);
6243         }
6244 #else 
6245
6246         /* fixme: add all optimizations which requires SSA */
6247         if (cfg->opt & (MONO_OPT_DEADCE)) {
6248                 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
6249                         mono_local_cprop (cfg);
6250                         mono_ssa_compute (cfg);
6251
6252                         if (cfg->verbose_level >= 2) {
6253                                 print_dfn (cfg);
6254                         }
6255                 }
6256         }
6257 #endif
6258
6259         /* after SSA translation */
6260         if (parts == 2)
6261                 return cfg;
6262
6263         if ((cfg->opt & MONO_OPT_CONSPROP) ||  (cfg->opt & MONO_OPT_COPYPROP)) {
6264                 if (cfg->comp_done & MONO_COMP_SSA) {
6265                         mono_ssa_cprop (cfg);
6266                 } else {
6267                         mono_local_cprop (cfg);
6268                 }
6269         }
6270
6271         if (cfg->comp_done & MONO_COMP_SSA) {                   
6272                 mono_ssa_deadce (cfg);
6273
6274                 //mono_ssa_strength_reduction (cfg);
6275
6276                 mono_ssa_remove (cfg);
6277
6278                 if (cfg->opt & MONO_OPT_BRANCH)
6279                         optimize_branches (cfg);
6280         }
6281
6282         /* after SSA removal */
6283         if (parts == 3)
6284                 return cfg;
6285         
6286         decompose_pass (cfg);
6287
6288         /* FIXME: disabled with exception clauses: bug #42136 */
6289         if ((!header->num_clauses) && (cfg->opt & MONO_OPT_LINEARS)) {
6290                 GList *vars, *regs;
6291
6292                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
6293                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
6294                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
6295                         mono_analyze_liveness (cfg);
6296
6297                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
6298                         regs = mono_arch_get_global_int_regs (cfg);
6299                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
6300                 }
6301         }
6302
6303         //mono_print_code (cfg);
6304         
6305         //print_dfn (cfg);
6306
6307         /* variables are allocated after decompose, since decompose could create temps */
6308         mono_arch_allocate_vars (cfg);
6309
6310         if (cfg->opt & MONO_OPT_CFOLD)
6311                 mono_constant_fold (cfg);
6312
6313         mini_select_instructions (cfg);
6314
6315         mono_codegen (cfg);
6316         if (cfg->verbose_level >= 2) {
6317                 char *id =  mono_method_full_name (cfg->method, FALSE);
6318                 mono_disassemble_code (cfg->native_code, cfg->code_len, id + 3);
6319                 g_free (id);
6320         }
6321         
6322         jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo));
6323
6324         jinfo = g_new0 (MonoJitInfo, 1);
6325         jinfo->method = method;
6326         jinfo->code_start = cfg->native_code;
6327         jinfo->code_size = cfg->code_len;
6328         jinfo->used_regs = cfg->used_int_regs;
6329
6330         if (header->num_clauses) {
6331                 int i;
6332
6333                 jinfo->exvar_offset = cfg->exvar? cfg->exvar->inst_offset: 0;
6334                 jinfo->num_clauses = header->num_clauses;
6335                 jinfo->clauses = mono_mempool_alloc0 (cfg->domain->mp, 
6336                         sizeof (MonoJitExceptionInfo) * header->num_clauses);
6337
6338                 for (i = 0; i < header->num_clauses; i++) {
6339                         MonoExceptionClause *ec = &header->clauses [i];
6340                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
6341                         MonoBasicBlock *tblock;
6342
6343                         ei->flags = ec->flags;
6344
6345                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
6346                                 tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->token_or_filter);
6347                                 g_assert (tblock);
6348                                 ei->data.filter = cfg->native_code + tblock->native_offset;
6349                         } else {
6350                                 ei->data.token = ec->token_or_filter;
6351                         }
6352
6353                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset);
6354                         g_assert (tblock);
6355                         ei->try_start = cfg->native_code + tblock->native_offset;
6356                         g_assert (tblock->native_offset);
6357                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset + ec->try_len);
6358                         g_assert (tblock);
6359                         ei->try_end = cfg->native_code + tblock->native_offset;
6360                         g_assert (tblock->native_offset);
6361                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->handler_offset);
6362                         g_assert (tblock);
6363                         ei->handler_start = cfg->native_code + tblock->native_offset;
6364                 }
6365         }
6366
6367         mono_jit_info_table_add (cfg->domain, jinfo);
6368
6369         /* collect statistics */
6370         mono_jit_stats.allocated_code_size += cfg->code_len;
6371         code_size_ratio = cfg->code_len;
6372         if (code_size_ratio > mono_jit_stats.biggest_method_size) {
6373                         mono_jit_stats.biggest_method_size = code_size_ratio;
6374                         mono_jit_stats.biggest_method = method;
6375         }
6376         code_size_ratio = (code_size_ratio * 100) / ((MonoMethodNormal *)method)->header->code_size;
6377         if (code_size_ratio > mono_jit_stats.max_code_size_ratio) {
6378                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
6379                 mono_jit_stats.max_ratio_method = method;
6380         }
6381         mono_jit_stats.native_code_size += cfg->code_len;
6382
6383         if (mono_jit_profile)
6384                 mono_profiler_method_end_jit (method, MONO_PROFILE_OK);
6385
6386         return cfg;
6387 }
6388
6389 static gpointer
6390 mono_jit_compile_method (MonoMethod *method)
6391 {
6392         /* FIXME: later copy the code from mono */
6393         MonoDomain *target_domain, *domain = mono_domain_get ();
6394         MonoCompile *cfg;
6395         GHashTable *jit_code_hash;
6396         gpointer code;
6397
6398         if (default_opt & MONO_OPT_SHARED)
6399                 target_domain = mono_root_domain;
6400         else 
6401                 target_domain = domain;
6402
6403         jit_code_hash = target_domain->jit_code_hash;
6404
6405         if ((code = g_hash_table_lookup (jit_code_hash, method))) {
6406                 mono_jit_stats.methods_lookups++;
6407                 return code;
6408         }
6409
6410 #ifdef MONO_USE_AOT_COMPILER
6411         if (!mono_compile_aot) {
6412                 mono_class_init (method->klass);
6413                 if ((code = mono_aot_get_method (method))) {
6414                         g_hash_table_insert (jit_code_hash, method, code);
6415                         return code;
6416                 }
6417         }
6418 #endif
6419
6420         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
6421             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
6422                 if (!method->info) {
6423                         MonoMethod *nm;
6424
6425                         if (!method->addr && (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
6426                                 mono_lookup_pinvoke_call (method);
6427 #ifdef MONO_USE_EXC_TABLES
6428                         if (mono_method_blittable (method)) {
6429                                 method->info = method->addr;
6430                         } else {
6431 #endif
6432                                 nm = mono_marshal_get_native_wrapper (method);
6433                                 method->info = mono_compile_method (nm);
6434
6435                                 //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE) 
6436                                 //mono_debug_add_wrapper (method, nm);
6437 #ifdef MONO_USE_EXC_TABLES
6438                         }
6439 #endif
6440                 }
6441                 return method->info;
6442         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
6443                 const char *name = method->name;
6444                 MonoMethod *nm;
6445
6446                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
6447                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
6448                                 /* FIXME: uhm, we need a wrapper to handle exceptions? */
6449                                 return (gpointer)mono_delegate_ctor;
6450                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
6451                                 nm = mono_marshal_get_delegate_invoke (method);
6452                                 return mono_jit_compile_method (nm);
6453                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
6454                                 nm = mono_marshal_get_delegate_begin_invoke (method);
6455                                 return mono_jit_compile_method (nm);
6456                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
6457                                 nm = mono_marshal_get_delegate_end_invoke (method);
6458                                 return mono_jit_compile_method (nm);
6459                         }
6460                 }
6461                 return NULL;
6462         }
6463
6464         cfg = mini_method_compile (method, default_opt, target_domain, 0);
6465         code = cfg->native_code;
6466         mono_destroy_compile (cfg);
6467
6468         g_hash_table_insert (jit_code_hash, method, code);
6469
6470         if (target_domain->jump_target_hash) {
6471                 MonoJumpInfo patch_info;
6472                 GSList *list, *tmp;
6473                 list = g_hash_table_lookup (target_domain->jump_target_hash, method);
6474                 if (list) {
6475                         patch_info.next = NULL;
6476                         patch_info.ip.i = 0;
6477                         patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
6478                         patch_info.data.method = method;
6479                         g_hash_table_remove (target_domain->jump_target_hash, method);
6480                 }
6481                 for (tmp = list; tmp; tmp = tmp->next)
6482                         mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info);
6483                 g_slist_free (list);
6484         }
6485         /* make sure runtime_init is called */
6486         mono_runtime_class_init (mono_class_vtable (target_domain, method->klass));
6487
6488         return code;
6489 }
6490
6491 /**
6492  * mono_jit_runtime_invoke:
6493  * @method: the method to invoke
6494  * @obj: this pointer
6495  * @params: array of parameter values.
6496  * @exc: used to catch exceptions objects
6497  */
6498 static MonoObject*
6499 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
6500 {
6501         MonoMethod *invoke;
6502         MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc);
6503         invoke = mono_marshal_get_runtime_invoke (method);
6504         runtime_invoke = mono_jit_compile_method (invoke);      
6505         return runtime_invoke (obj, params, exc);
6506 }
6507
6508 #ifdef PLATFORM_WIN32
6509 #define GET_CONTEXT \
6510         struct sigcontext *ctx = (struct sigcontext*)_dummy;
6511 #else
6512 #define GET_CONTEXT \
6513         void **_p = (void **)&_dummy; \
6514         struct sigcontext *ctx = (struct sigcontext *)++_p;
6515 #endif
6516
6517 static void
6518 sigfpe_signal_handler (int _dummy)
6519 {
6520         MonoException *exc;
6521         GET_CONTEXT
6522
6523         exc = mono_get_exception_divide_by_zero ();
6524         
6525         mono_arch_handle_exception (ctx, exc, FALSE);
6526 }
6527
6528 static void
6529 sigill_signal_handler (int _dummy)
6530 {
6531         MonoException *exc;
6532         GET_CONTEXT
6533         exc = mono_get_exception_execution_engine ("SIGILL");
6534         
6535         mono_arch_handle_exception (ctx, exc, FALSE);
6536 }
6537
6538 static void
6539 sigsegv_signal_handler (int _dummy)
6540 {
6541         MonoException *exc;
6542         GET_CONTEXT
6543
6544         exc = mono_get_exception_null_reference ();
6545         
6546         mono_arch_handle_exception (ctx, exc, FALSE);
6547 }
6548
6549 static void
6550 sigusr1_signal_handler (int _dummy)
6551 {
6552         MonoThread *thread;
6553         GET_CONTEXT
6554         
6555         thread = mono_thread_current ();
6556         
6557         g_assert (thread->abort_exc);
6558
6559         mono_arch_handle_exception (ctx, thread->abort_exc, FALSE);
6560 }
6561
6562 static void
6563 mono_runtime_install_handlers (void)
6564 {
6565 #ifndef PLATFORM_WIN32
6566         struct sigaction sa;
6567 #endif
6568
6569 #ifdef PLATFORM_WIN32
6570         win32_seh_init();
6571         win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
6572         win32_seh_set_handler(SIGILL, sigill_signal_handler);
6573         win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
6574 #else /* !PLATFORM_WIN32 */
6575
6576         /* libpthreads has its own implementation of sigaction(),
6577          * but it seems to work well with our current exception
6578          * handlers. If not we must call syscall directly instead 
6579          * of sigaction */
6580         
6581         /* catch SIGFPE */
6582         sa.sa_handler = sigfpe_signal_handler;
6583         sigemptyset (&sa.sa_mask);
6584         sa.sa_flags = 0;
6585         //g_assert (syscall (SYS_sigaction, SIGFPE, &sa, NULL) != -1);
6586         g_assert (sigaction (SIGFPE, &sa, NULL) != -1);
6587
6588         /* catch SIGILL */
6589         sa.sa_handler = sigill_signal_handler;
6590         sigemptyset (&sa.sa_mask);
6591         sa.sa_flags = 0;
6592         //g_assert (syscall (SYS_sigaction, SIGILL, &sa, NULL) != -1);
6593         g_assert (sigaction (SIGILL, &sa, NULL) != -1);
6594
6595         /* catch thread abort signal */
6596         sa.sa_handler = sigusr1_signal_handler;
6597         sigemptyset (&sa.sa_mask);
6598         sa.sa_flags = 0;
6599         //g_assert (syscall (SYS_sigaction, SIGILL, &sa, NULL) != -1);
6600         g_assert (sigaction (mono_thread_get_abort_signal (), &sa, NULL) != -1);
6601
6602 #if 1
6603         /* catch SIGSEGV */
6604         sa.sa_handler = sigsegv_signal_handler;
6605         sigemptyset (&sa.sa_mask);
6606         sa.sa_flags = 0;
6607         //g_assert (syscall (SYS_sigaction, SIGSEGV, &sa, NULL) != -1);
6608         g_assert (sigaction (SIGSEGV, &sa, NULL) != -1);
6609 #endif
6610 #endif /* PLATFORM_WIN32 */
6611 }
6612
6613 /* mono_jit_create_remoting_trampoline:
6614  * @method: pointer to the method info
6615  *
6616  * Creates a trampoline which calls the remoting functions. This
6617  * is used in the vtable of transparent proxies.
6618  * 
6619  * Returns: a pointer to the newly created code 
6620  */
6621 static gpointer
6622 mono_jit_create_remoting_trampoline (MonoMethod *method)
6623 {
6624         MonoMethod *nm;
6625         guint8 *addr = NULL;
6626
6627         if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || 
6628             (method->signature->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
6629                 nm = mono_marshal_get_remoting_invoke (method);
6630                 addr = mono_compile_method (nm);
6631         } else {
6632                 addr = mono_compile_method (method);
6633         }
6634         return addr;
6635 }
6636
6637 static CRITICAL_SECTION ms;
6638
6639 MonoDomain *
6640 mini_init (const char *filename)
6641 {
6642         MonoDomain *domain;
6643         
6644         metadata_section = &ms;
6645         InitializeCriticalSection (metadata_section);
6646
6647         mono_jit_tls_id = TlsAlloc ();
6648         mono_thread_start_cb (GetCurrentThreadId (), (gpointer)-1, NULL);
6649
6650         mono_burg_init ();
6651
6652         mono_runtime_install_handlers ();
6653
6654         mono_install_compile_method (mono_jit_compile_method);
6655         mono_install_trampoline (mono_arch_create_jit_trampoline);
6656         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
6657         mono_install_runtime_invoke (mono_jit_runtime_invoke);
6658         mono_install_handler (mono_arch_get_throw_exception ());
6659         mono_install_stack_walk (mono_jit_walk_stack);
6660         mono_install_get_config_dir ();
6661
6662         domain = mono_init (filename);
6663         mono_init_icall ();
6664
6665         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info", 
6666                                 ves_icall_get_frame_info);
6667         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace", 
6668                                 ves_icall_get_trace);
6669         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers", 
6670                                 mono_runtime_install_handlers);
6671
6672
6673         create_helper_signature ();
6674
6675         mono_arch_register_lowlevel_calls ();
6676         mono_register_jit_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
6677         mono_register_jit_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
6678
6679         mono_register_jit_icall (mono_get_lmf_addr, "mono_get_lmf_addr", helper_sig_ptr_void, TRUE);
6680         mono_register_jit_icall (mono_domain_get, "mono_domain_get", helper_sig_domain_get, TRUE);
6681
6682         /* fixme: we cant hanlde vararg methods this way, because the signature is not constant */
6683         //mono_register_jit_icall (ves_array_element_address, "ves_array_element_address", NULL);
6684         //mono_register_jit_icall (mono_array_new_va, "mono_array_new_va", NULL);
6685
6686         mono_register_jit_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", helper_sig_void_obj, TRUE);
6687         mono_register_jit_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", 
6688                                  helper_sig_void_ptr, TRUE);
6689
6690         /* 
6691          * NOTE, NOTE, NOTE, NOTE:
6692          * when adding emulation for some opcodes, remember to also add a dummy
6693          * rule to the burg files, because we need the arity information to be correct.
6694          */
6695         mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", helper_sig_long_long_long, mono_llmult);
6696         mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", helper_sig_long_long_long, mono_llmult_ovf_un);
6697         mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", helper_sig_long_long_long, mono_llmult_ovf);
6698         mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", helper_sig_long_long_long, mono_lldiv);
6699         mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", helper_sig_long_long_long, mono_lldiv_un);
6700         mono_register_opcode_emulation (OP_LREM, "__emul_lrem", helper_sig_long_long_long, mono_llrem);
6701         mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", helper_sig_long_long_long, mono_llrem_un);
6702
6703         mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", helper_sig_long_long_int, mono_lshl);
6704         mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", helper_sig_long_long_int, mono_lshr);
6705         mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", helper_sig_long_long_int, mono_lshr_un);
6706
6707         mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", helper_sig_ulong_double, mono_fconv_u8);
6708         mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", helper_sig_uint_double, mono_fconv_u4);
6709         mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", helper_sig_long_double, mono_fconv_ovf_i8);
6710         mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", helper_sig_ulong_double, mono_fconv_ovf_u8);
6711
6712 #if SIZEOF_VOID_P == 4
6713         mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", helper_sig_uint_double, mono_fconv_u4);
6714 #else
6715 #warning "fixme: add opcode emulation"
6716 #endif
6717
6718         /* other jit icalls */
6719         mono_register_jit_icall (mono_class_static_field_address , "mono_class_static_field_address", 
6720                                  helper_sig_ptr_ptr_ptr, FALSE);
6721         mono_register_jit_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", helper_sig_ptr_ptr_ptr, FALSE);
6722         mono_register_jit_icall (mono_threads_get_static_data, "mono_threads_get_static_data", helper_sig_ptr_int, FALSE);
6723         mono_register_jit_icall (mono_ldstr, "mono_ldstr", helper_sig_ldstr, FALSE);
6724         mono_register_jit_icall (helper_memcpy, "helper_memcpy", helper_sig_memcpy, FALSE);
6725         mono_register_jit_icall (helper_memset, "helper_memset", helper_sig_memset, FALSE);
6726         mono_register_jit_icall (helper_initobj, "helper_initobj", helper_sig_initobj, FALSE);
6727         mono_register_jit_icall (helper_stelem_ref, "helper_stelem_ref", helper_sig_stelem_ref, FALSE);
6728         mono_register_jit_icall (mono_object_new, "mono_object_new", helper_sig_object_new, FALSE);
6729         mono_register_jit_icall (mono_object_new_specific, "mono_object_new_specific", helper_sig_object_new_specific, FALSE);
6730         mono_register_jit_icall (mono_array_new, "mono_array_new", helper_sig_newarr, FALSE);
6731         mono_register_jit_icall (mono_array_new_specific, "mono_array_new_specific", helper_sig_newarr_specific, FALSE);
6732         mono_register_jit_icall (mono_string_to_utf16, "mono_string_to_utf16", helper_sig_ptr_obj, FALSE);
6733         mono_register_jit_icall (mono_string_from_utf16, "mono_string_from_utf16", helper_sig_obj_ptr, FALSE);
6734         mono_register_jit_icall (mono_string_new_wrapper, "mono_string_new_wrapper", helper_sig_obj_ptr, FALSE);
6735         mono_register_jit_icall (mono_string_to_utf8, "mono_string_to_utf8", helper_sig_ptr_obj, FALSE);
6736         mono_register_jit_icall (mono_string_to_bstr, "mono_string_to_bstr", helper_sig_ptr_obj, FALSE);
6737         mono_register_jit_icall (mono_string_to_ansibstr, "mono_string_to_ansibstr", helper_sig_ptr_obj, FALSE);
6738         mono_register_jit_icall (mono_string_builder_to_utf8, "mono_string_builder_to_utf8", helper_sig_ptr_obj, FALSE);
6739         mono_register_jit_icall (mono_array_to_savearray, "mono_array_to_savearray", helper_sig_ptr_obj, FALSE);
6740         mono_register_jit_icall (mono_array_to_lparray, "mono_array_to_lparray", helper_sig_ptr_obj, FALSE);
6741         mono_register_jit_icall (mono_delegate_to_ftnptr, "mono_delegate_to_ftnptr", helper_sig_ptr_obj, FALSE);
6742         mono_register_jit_icall (mono_marshal_string_array, "mono_marshal_string_array", helper_sig_ptr_obj, FALSE);
6743         mono_register_jit_icall (mono_string_utf8_to_builder, "mono_string_utf8_to_builder", helper_sig_void_ptr_ptr, FALSE);
6744         mono_register_jit_icall (mono_marshal_free_array, "mono_marshal_free_array", helper_sig_void_ptr_ptr, FALSE);
6745         mono_register_jit_icall (mono_string_to_byvalstr, "mono_string_to_byvalstr", helper_sig_void_ptr_ptr_ptr, FALSE);
6746         mono_register_jit_icall (mono_string_to_byvalwstr, "mono_string_to_byvalwstr", helper_sig_void_ptr_ptr_ptr, FALSE);
6747         mono_register_jit_icall (g_free, "g_free", helper_sig_void_ptr, FALSE);
6748         mono_register_jit_icall (mono_runtime_class_init, "mono_runtime_class_init", helper_sig_void_ptr, FALSE);
6749         mono_register_jit_icall (mono_ldftn, "mono_ldftn", helper_sig_compile, FALSE);
6750         mono_register_jit_icall (mono_ldvirtfn, "mono_ldvirtfn", helper_sig_compile_virt, FALSE);
6751
6752         mono_runtime_init (domain, mono_thread_start_cb,
6753                            mono_thread_attach_cb);
6754
6755         //mono_thread_attach (domain);
6756         return domain;
6757 }
6758
6759 MonoJitStats mono_jit_stats = {0};
6760
6761 static void 
6762 print_jit_stats (void)
6763 {
6764         if (mono_jit_stats.enabled) {
6765                 g_print ("Mono Jit statistics\n");
6766                 g_print ("Compiled methods:       %ld\n", mono_jit_stats.methods_compiled);
6767                 g_print ("Methods from AOT:       %ld\n", mono_jit_stats.methods_aot);
6768                 g_print ("Methods cache lookup:   %ld\n", mono_jit_stats.methods_lookups);
6769                 g_print ("Method trampolines:     %ld\n", mono_jit_stats.method_trampolines);
6770                 g_print ("Basic blocks:           %ld\n", mono_jit_stats.basic_blocks);
6771                 g_print ("Max basic blocks:       %ld\n", mono_jit_stats.max_basic_blocks);
6772                 g_print ("Allocated vars:         %ld\n", mono_jit_stats.allocate_var);
6773                 g_print ("Analyze stack repeat:   %ld\n", mono_jit_stats.analyze_stack_repeat);
6774                 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
6775                 g_print ("Native code size:       %ld\n", mono_jit_stats.native_code_size);
6776                 g_print ("Max code size ratio:    %.2f (%s::%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
6777                                 mono_jit_stats.max_ratio_method->klass->name, mono_jit_stats.max_ratio_method->name);
6778                 g_print ("Biggest method:         %ld (%s::%s)\n", mono_jit_stats.biggest_method_size,
6779                                 mono_jit_stats.biggest_method->klass->name, mono_jit_stats.biggest_method->name);
6780                 g_print ("Code reallocs:          %ld\n", mono_jit_stats.code_reallocs);
6781                 g_print ("Allocated code size:    %ld\n", mono_jit_stats.allocated_code_size);
6782                 g_print ("Inlineable methods:     %ld\n", mono_jit_stats.inlineable_methods);
6783                 g_print ("Inlined methods:        %ld\n", mono_jit_stats.inlined_methods);
6784                 
6785                 g_print ("\nCreated object count:   %ld\n", mono_stats.new_object_count);
6786                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
6787                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
6788                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
6789                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
6790         }
6791 }
6792
6793 void
6794 mini_cleanup (MonoDomain *domain)
6795 {
6796         /* 
6797          * mono_runtime_cleanup() and mono_domain_finalize () need to
6798          * be called early since they need the execution engine still
6799          * fully working (mono_domain_finalize may invoke managed finalizers
6800          * and mono_runtime_cleanup will wait for other threads to finish).
6801          */
6802         mono_domain_finalize (domain);
6803
6804         mono_runtime_cleanup (domain);
6805
6806         mono_profiler_shutdown ();
6807
6808         mono_debug_cleanup ();
6809 #ifdef PLATFORM_WIN32
6810         win32_seh_cleanup();
6811 #endif
6812
6813         mono_domain_unload (domain, TRUE);
6814
6815         print_jit_stats ();
6816         DeleteCriticalSection (metadata_section);
6817 }
6818
6819 void
6820 mono_set_defaults (int verbose_level, guint32 opts)
6821 {
6822         mini_verbose = verbose_level;
6823         default_opt = opts;
6824 }
6825