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