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