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