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