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