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