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