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