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