2007-11-28 Zoltan Varga <vargaz@gmail.com>
[mono.git] / mono / mini / mini.c
1 /*
2  * mini.c: The new Mono code generator.
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * (C) 2002 Ximian, Inc.
9  */
10
11 #include <config.h>
12 #include <signal.h>
13 #ifdef HAVE_UNISTD_H
14 #include <unistd.h>
15 #endif
16 #include <math.h>
17 #ifdef HAVE_SYS_TIME_H
18 #include <sys/time.h>
19 #endif
20
21 #ifdef PLATFORM_MACOSX
22 #include <mach/mach.h>
23 #include <mach/mach_error.h>
24 #include <mach/exception.h>
25 #include <mach/task.h>
26 #include <pthread.h>
27 #endif
28
29 #ifdef PLATFORM_WIN32
30 #define _WIN32_WINNT 0x0500
31 #endif
32
33 #ifdef HAVE_VALGRIND_MEMCHECK_H
34 #include <valgrind/memcheck.h>
35 #endif
36
37 #include <mono/metadata/assembly.h>
38 #include <mono/metadata/loader.h>
39 #include <mono/metadata/tabledefs.h>
40 #include <mono/metadata/class.h>
41 #include <mono/metadata/object.h>
42 #include <mono/metadata/exception.h>
43 #include <mono/metadata/opcodes.h>
44 #include <mono/metadata/mono-endian.h>
45 #include <mono/metadata/tokentype.h>
46 #include <mono/metadata/tabledefs.h>
47 #include <mono/metadata/threads.h>
48 #include <mono/metadata/marshal.h>
49 #include <mono/metadata/socket-io.h>
50 #include <mono/metadata/appdomain.h>
51 #include <mono/metadata/debug-helpers.h>
52 #include <mono/io-layer/io-layer.h>
53 #include "mono/metadata/profiler.h"
54 #include <mono/metadata/profiler-private.h>
55 #include <mono/metadata/mono-config.h>
56 #include <mono/metadata/environment.h>
57 #include <mono/metadata/mono-debug.h>
58 #include <mono/metadata/monitor.h>
59 #include <mono/metadata/gc-internal.h>
60 #include <mono/metadata/security-manager.h>
61 #include <mono/metadata/threads-types.h>
62 #include <mono/metadata/rawbuffer.h>
63 #include <mono/metadata/security-core-clr.h>
64 #include <mono/utils/mono-math.h>
65 #include <mono/utils/mono-compiler.h>
66 #include <mono/utils/mono-counters.h>
67 #include <mono/utils/mono-logger.h>
68 #include <mono/utils/mono-mmap.h>
69 #include <mono/os/gc_wrapper.h>
70
71 #include "mini.h"
72 #include <string.h>
73 #include <ctype.h>
74 #include "inssel.h"
75 #include "trace.h"
76
77 #include "jit-icalls.h"
78
79 #include "aliasing.h"
80
81 #include "debug-mini.h"
82
83 #define BRANCH_COST 100
84 #define INLINE_LENGTH_LIMIT 20
85 #define INLINE_FAILURE do {\
86                 if ((cfg->method != method) && (method->wrapper_type == MONO_WRAPPER_NONE))\
87                         goto inline_failure;\
88         } while (0)
89 #define CHECK_CFG_EXCEPTION do {\
90                 if (cfg->exception_type != MONO_EXCEPTION_NONE)\
91                         goto exception_exit;\
92         } while (0)
93 #define METHOD_ACCESS_FAILURE do {      \
94                 char *method_fname = mono_method_full_name (method, TRUE);      \
95                 char *cil_method_fname = mono_method_full_name (cil_method, TRUE);      \
96                 cfg->exception_type = MONO_EXCEPTION_METHOD_ACCESS;     \
97                 cfg->exception_message = g_strdup_printf ("Method `%s' is inaccessible from method `%s'\n", cil_method_fname, method_fname);    \
98                 g_free (method_fname);  \
99                 g_free (cil_method_fname);      \
100                 goto exception_exit;    \
101         } while (0)
102 #define FIELD_ACCESS_FAILURE do {       \
103                 char *method_fname = mono_method_full_name (method, TRUE);      \
104                 char *field_fname = mono_field_full_name (field);       \
105                 cfg->exception_type = MONO_EXCEPTION_FIELD_ACCESS;      \
106                 cfg->exception_message = g_strdup_printf ("Field `%s' is inaccessible from method `%s'\n", field_fname, method_fname);  \
107                 g_free (method_fname);  \
108                 g_free (field_fname);   \
109                 goto exception_exit;    \
110         } while (0)
111 #define GENERIC_SHARING_FAILURE(opcode) do {            \
112                 if (cfg->generic_sharing_context) {     \
113                         if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) \
114                                 /*g_print ("sharing failed for method %s.%s.%s/%d opcode %s line %d\n", method->klass->name_space, method->klass->name, method->name, method->signature->param_count, mono_opcode_name ((opcode)), __LINE__)*/; \
115                         cfg->exception_type = MONO_EXCEPTION_GENERIC_SHARING_FAILED;    \
116                         goto exception_exit;    \
117                 }                       \
118         } while (0)
119
120 /* 
121  * this is used to determine when some branch optimizations are possible: we exclude FP compares
122  * because they have weird semantics with NaNs.
123  */
124 #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))
125 #define MONO_IS_COND_BRANCH_NOFP(ins) (MONO_IS_COND_BRANCH_OP(ins) && (ins)->inst_left->inst_left->type != STACK_R8)
126
127 #define MONO_IS_BRANCH_OP(ins) (MONO_IS_COND_BRANCH_OP(ins) || ((ins)->opcode == OP_BR) || ((ins)->opcode == OP_BR_REG) || ((ins)->opcode == CEE_SWITCH))
128
129 #define MONO_CHECK_THIS(ins) (mono_method_signature (cfg->method)->hasthis && (ins)->ssa_op == MONO_SSA_LOAD && (ins)->inst_left->inst_c0 == 0)
130
131 static void setup_stat_profiler (void);
132 gboolean  mono_arch_print_tree(MonoInst *tree, int arity);
133 static gpointer mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt);
134 static gpointer mono_jit_compile_method (MonoMethod *method);
135 static gpointer mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method);
136 static gpointer mono_create_jit_trampoline_in_domain (MonoDomain *domain, MonoMethod *method);
137 inline static int mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip);
138
139 static void handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, 
140                           const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native, gboolean write_barrier);
141
142 static void dec_foreach (MonoInst *tree, MonoCompile *cfg);
143
144 static int mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
145                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
146                    guint inline_offset, gboolean is_virtual_call);
147
148 #ifdef MONO_ARCH_SOFT_FLOAT
149 static void
150 handle_store_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, MonoInst *val, const unsigned char *ip);
151 #endif
152
153 /* helper methods signature */
154 static MonoMethodSignature *helper_sig_class_init_trampoline = NULL;
155 static MonoMethodSignature *helper_sig_domain_get = NULL;
156
157 static guint32 default_opt = 0;
158 static gboolean default_opt_set = FALSE;
159
160 guint32 mono_jit_tls_id = -1;
161 MonoTraceSpec *mono_jit_trace_calls = NULL;
162 gboolean mono_break_on_exc = FALSE;
163 #ifndef DISABLE_AOT
164 gboolean mono_compile_aot = FALSE;
165 #endif
166 MonoMethodDesc *mono_inject_async_exc_method = NULL;
167 int mono_inject_async_exc_pos;
168
169 static int mini_verbose = 0;
170
171 #define mono_jit_lock() EnterCriticalSection (&jit_mutex)
172 #define mono_jit_unlock() LeaveCriticalSection (&jit_mutex)
173 static CRITICAL_SECTION jit_mutex;
174
175 static GHashTable *class_init_hash_addr = NULL;
176
177 static MonoCodeManager *global_codeman = NULL;
178
179 static GHashTable *jit_icall_name_hash = NULL;
180
181 static MonoDebugOptions debug_options;
182
183 #ifdef VALGRIND_JIT_REGISTER_MAP
184 static int valgrind_register = 0;
185 #endif
186
187 /*
188  * Address of the trampoline code.  This is used by the debugger to check
189  * whether a method is a trampoline.
190  */
191 guint8* mono_trampoline_code [MONO_TRAMPOLINE_NUM];
192
193 /*
194  * Table written to by the debugger with a 1-based index into the
195  * mono_breakpoint_info table, which contains changes made to
196  * the JIT instructions by the debugger.
197  */
198 gssize
199 mono_breakpoint_info_index [MONO_BREAKPOINT_ARRAY_SIZE];
200
201 gboolean
202 mono_running_on_valgrind (void)
203 {
204 #ifdef HAVE_VALGRIND_MEMCHECK_H
205                 if (RUNNING_ON_VALGRIND){
206 #ifdef VALGRIND_JIT_REGISTER_MAP
207                         valgrind_register = TRUE;
208 #endif
209                         return TRUE;
210                 } else
211                         return FALSE;
212 #else
213                 return FALSE;
214 #endif
215 }
216
217 typedef struct {
218         void *ip;
219         MonoMethod *method;
220 } FindTrampUserData;
221
222 static void
223 find_tramp (gpointer key, gpointer value, gpointer user_data)
224 {
225         FindTrampUserData *ud = (FindTrampUserData*)user_data;
226
227         if (value == ud->ip)
228                 ud->method = (MonoMethod*)key;
229 }
230
231 /* debug function */
232 G_GNUC_UNUSED static char*
233 get_method_from_ip (void *ip)
234 {
235         MonoJitInfo *ji;
236         char *method;
237         char *res;
238         MonoDomain *domain = mono_domain_get ();
239         MonoDebugSourceLocation *location;
240         FindTrampUserData user_data;
241         
242         ji = mono_jit_info_table_find (domain, ip);
243         if (!ji) {
244                 user_data.ip = ip;
245                 user_data.method = NULL;
246                 mono_domain_lock (domain);
247                 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
248                 mono_domain_unlock (domain);
249                 if (user_data.method) {
250                         char *mname = mono_method_full_name (user_data.method, TRUE);
251                         res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
252                         g_free (mname);
253                         return res;
254                 }
255                 else
256                         return NULL;
257         }
258         method = mono_method_full_name (ji->method, TRUE);
259         /* FIXME: unused ? */
260         location = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
261
262         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);
263
264         mono_debug_free_source_location (location);
265         g_free (method);
266
267         return res;
268 }
269
270 /** 
271  * mono_pmip:
272  * @ip: an instruction pointer address
273  *
274  * This method is used from a debugger to get the name of the
275  * method at address @ip.   This routine is typically invoked from
276  * a debugger like this:
277  *
278  * (gdb) print mono_pmip ($pc)
279  *
280  * Returns: the name of the method at address @ip.
281  */
282 G_GNUC_UNUSED char *
283 mono_pmip (void *ip)
284 {
285         return get_method_from_ip (ip);
286 }
287
288 /** 
289  * mono_print_method_from_ip
290  * @ip: an instruction pointer address
291  *
292  * This method is used from a debugger to get the name of the
293  * method at address @ip.
294  *
295  * This prints the name of the method at address @ip in the standard
296  * output.  Unlike mono_pmip which returns a string, this routine
297  * prints the value on the standard output. 
298  */
299 void
300 mono_print_method_from_ip (void *ip)
301 {
302         MonoJitInfo *ji;
303         char *method;
304         MonoDebugSourceLocation *source;
305         MonoDomain *domain = mono_domain_get ();
306         FindTrampUserData user_data;
307         
308         ji = mono_jit_info_table_find (domain, ip);
309         if (!ji) {
310                 user_data.ip = ip;
311                 user_data.method = NULL;
312                 mono_domain_lock (domain);
313                 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
314                 mono_domain_unlock (domain);
315                 if (user_data.method) {
316                         char *mname = mono_method_full_name (user_data.method, TRUE);
317                         printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
318                         g_free (mname);
319                 }
320                 else
321                         g_print ("No method at %p\n", ip);
322                 return;
323         }
324         method = mono_method_full_name (ji->method, TRUE);
325         source = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
326
327         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);
328
329         if (source)
330                 g_print ("%s:%d\n", source->source_file, source->row);
331
332         mono_debug_free_source_location (source);
333         g_free (method);
334 }
335         
336 /* 
337  * mono_method_same_domain:
338  *
339  * Determine whenever two compiled methods are in the same domain, thus
340  * the address of the callee can be embedded in the caller.
341  */
342 gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
343 {
344         if (!caller || !callee)
345                 return FALSE;
346
347         /*
348          * If the call was made from domain-neutral to domain-specific 
349          * code, we can't patch the call site.
350          */
351         if (caller->domain_neutral && !callee->domain_neutral)
352                 return FALSE;
353
354         if ((caller->method->klass == mono_defaults.appdomain_class) &&
355                 (strstr (caller->method->name, "InvokeInDomain"))) {
356                  /* The InvokeInDomain methods change the current appdomain */
357                 return FALSE;
358         }
359
360         return TRUE;
361 }
362
363 /*
364  * mono_global_codeman_reserve:
365  *
366  *  Allocate code memory from the global code manager.
367  */
368 void *mono_global_codeman_reserve (int size)
369 {
370         void *ptr;
371
372         if (!global_codeman) {
373                 /* This can happen during startup */
374                 global_codeman = mono_code_manager_new ();
375                 return mono_code_manager_reserve (global_codeman, size);
376         }
377         else {
378                 mono_jit_lock ();
379                 ptr = mono_code_manager_reserve (global_codeman, size);
380                 mono_jit_unlock ();
381                 return ptr;
382         }
383 }
384
385 MonoJumpInfoToken *
386 mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
387 {
388         MonoJumpInfoToken *res = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
389         res->image = image;
390         res->token = token;
391
392         return res;
393 }
394
395 #define MONO_INIT_VARINFO(vi,id) do { \
396         (vi)->range.first_use.pos.bid = 0xffff; \
397         (vi)->reg = -1; \
398         (vi)->idx = (id); \
399 } while (0)
400
401 //#define UNVERIFIED do { G_BREAKPOINT (); goto unverified; } while (0)
402 #define UNVERIFIED do { if (debug_options.break_on_unverified) G_BREAKPOINT (); else goto unverified; } while (0)
403
404 /*
405  * Basic blocks have two numeric identifiers:
406  * dfn: Depth First Number
407  * block_num: unique ID assigned at bblock creation
408  */
409 #define NEW_BBLOCK(cfg) (mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock)))
410 #define ADD_BBLOCK(cfg,b) do {  \
411                 cfg->cil_offset_to_bb [(b)->cil_code - cfg->cil_start] = (b);   \
412                 (b)->block_num = cfg->num_bblocks++;    \
413                 (b)->real_offset = real_offset; \
414         } while (0)
415
416 #define GET_BBLOCK(cfg,tblock,ip) do {  \
417                 (tblock) = cfg->cil_offset_to_bb [(ip) - cfg->cil_start]; \
418                 if (!(tblock)) {        \
419                         if ((ip) >= end || (ip) < header->code) UNVERIFIED; \
420                         (tblock) = NEW_BBLOCK (cfg);    \
421                         (tblock)->cil_code = (ip);      \
422                         ADD_BBLOCK (cfg, (tblock));     \
423                 } \
424         } while (0)
425
426 #define CHECK_BBLOCK(target,ip,tblock) do {     \
427                 if ((target) < (ip) && !(tblock)->code) {       \
428                         bb_recheck = g_list_prepend (bb_recheck, (tblock));     \
429                         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));     \
430                 }       \
431         } while (0)
432
433 #define NEW_ICONST(cfg,dest,val) do {   \
434                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
435                 (dest)->opcode = OP_ICONST;     \
436                 (dest)->inst_c0 = (val);        \
437                 (dest)->type = STACK_I4;        \
438         } while (0)
439
440 #define NEW_PCONST(cfg,dest,val) do {   \
441                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
442                 (dest)->opcode = OP_PCONST;     \
443                 (dest)->inst_p0 = (val);        \
444                 (dest)->type = STACK_PTR;       \
445         } while (0)
446
447
448 #ifdef MONO_ARCH_NEED_GOT_VAR
449
450 #define NEW_PATCH_INFO(cfg,dest,el1,el2) do {   \
451                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
452                 (dest)->opcode = OP_PATCH_INFO; \
453                 (dest)->inst_left = (gpointer)(el1);    \
454                 (dest)->inst_right = (gpointer)(el2);   \
455         } while (0)
456
457 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do {                     \
458                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
459                 (dest)->opcode = cfg->compile_aot ? OP_GOT_ENTRY : OP_PCONST; \
460                 if (cfg->compile_aot) {                                 \
461                         MonoInst *group, *got_var, *got_loc;            \
462                         got_loc = mono_get_got_var (cfg);               \
463                         NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0); \
464                         NEW_PATCH_INFO ((cfg), group, cons, patch_type); \
465                         (dest)->inst_p0 = got_var;                      \
466                         (dest)->inst_p1 = group;                        \
467                 } else {                                                \
468                         (dest)->inst_p0 = (cons);                       \
469                         (dest)->inst_i1 = (gpointer)(patch_type);       \
470                 }                                                       \
471                 (dest)->type = STACK_PTR;                               \
472         } while (0)
473
474 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type,stack_class) do { \
475                 MonoInst *group, *got_var, *got_loc;                    \
476                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
477                 (dest)->opcode = OP_GOT_ENTRY;                          \
478                 got_loc = mono_get_got_var (cfg);                       \
479                 NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0);        \
480                 NEW_PATCH_INFO ((cfg), group, NULL, patch_type);        \
481                 group->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token)); \
482                 (dest)->inst_p0 = got_var;                              \
483                 (dest)->inst_p1 = group;                                \
484                 (dest)->type = (stack_type);                    \
485         (dest)->klass = (stack_class);          \
486         } while (0)
487
488 #else
489
490 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do {    \
491                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
492                 (dest)->opcode = cfg->compile_aot ? OP_AOTCONST : OP_PCONST;    \
493                 (dest)->inst_p0 = (cons);       \
494                 (dest)->inst_i1 = (gpointer)(patch_type); \
495                 (dest)->type = STACK_PTR;       \
496     } while (0)
497
498 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type,stack_class) do { \
499                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
500                 (dest)->opcode = OP_AOTCONST;   \
501                 (dest)->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token));  \
502                 (dest)->inst_p1 = (gpointer)(patch_type); \
503                 (dest)->type = (stack_type);    \
504         (dest)->klass = (stack_class);          \
505     } while (0)
506
507 #endif
508
509 #define NEW_CLASSCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_CLASS, (val))
510
511 #define NEW_IMAGECONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_IMAGE, (val))
512
513 #define NEW_FIELDCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_FIELD, (val))
514
515 #define NEW_METHODCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_METHODCONST, (val))
516
517 #define NEW_VTABLECONST(cfg,dest,vtable) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_VTABLE, cfg->compile_aot ? (gpointer)((vtable)->klass) : (vtable))
518
519 #define NEW_SFLDACONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_SFLDA, (val))
520
521 #define NEW_LDSTRCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDSTR, (image), (token), STACK_OBJ, mono_defaults.string_class)
522
523 #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)
524
525 #define NEW_LDTOKENCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDTOKEN, (image), (token), STACK_PTR, NULL)
526
527 #define NEW_DECLSECCONST(cfg,dest,image,entry) do { \
528                 if (cfg->compile_aot) { \
529                         NEW_AOTCONST_TOKEN (cfg, dest, MONO_PATCH_INFO_DECLSEC, image, (entry).index, STACK_OBJ, NULL); \
530                 } else { \
531                         NEW_PCONST (cfg, args [0], (entry).blob); \
532                 } \
533         } while (0)
534
535 #define NEW_DOMAINCONST(cfg,dest) do { \
536                 if (cfg->opt & MONO_OPT_SHARED) { \
537                         /* avoid depending on undefined C behavior in sequence points */ \
538                         MonoInst* __domain_var = mono_get_domainvar (cfg); \
539                         NEW_TEMPLOAD (cfg, dest, __domain_var->inst_c0); \
540                 } else { \
541                         NEW_PCONST (cfg, dest, (cfg)->domain); \
542                 } \
543         } while (0)
544
545 #define GET_VARINFO_INST(cfg,num) ((cfg)->varinfo [(num)]->inst)
546
547 #define NEW_ARGLOAD(cfg,dest,num) do {  \
548                 if (arg_array [(num)]->opcode == OP_ICONST) (dest) = arg_array [(num)]; else { \
549                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
550                 (dest)->ssa_op = MONO_SSA_LOAD; \
551                 (dest)->inst_i0 = arg_array [(num)];    \
552                 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
553                 type_to_eval_stack_type ((cfg), param_types [(num)], (dest));   \
554                 (dest)->klass = (dest)->inst_i0->klass; \
555         }} while (0)
556
557 #define NEW_LOCLOAD(cfg,dest,num) do {  \
558                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
559                 (dest)->ssa_op = MONO_SSA_LOAD; \
560                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
561                 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
562                 type_to_eval_stack_type ((cfg), header->locals [(num)], (dest));        \
563                 (dest)->klass = (dest)->inst_i0->klass; \
564         } while (0)
565
566 #define NEW_LOCLOADA(cfg,dest,num) do { \
567                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
568                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
569                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
570                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
571                 (dest)->opcode = OP_LDADDR;     \
572                 (dest)->type = STACK_MP;        \
573                 (dest)->klass = (dest)->inst_i0->klass; \
574         if (!MONO_TYPE_ISSTRUCT (header->locals [(num)])) \
575            (cfg)->disable_ssa = TRUE; \
576         } while (0)
577
578 #define NEW_RETLOADA(cfg,dest) do {     \
579                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
580                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
581                 (dest)->inst_i0 = (cfg)->ret;   \
582                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
583                 (dest)->opcode = cfg->ret_var_is_local ? OP_LDADDR : CEE_LDIND_I;       \
584                 (dest)->type = STACK_MP;        \
585                 (dest)->klass = (dest)->inst_i0->klass; \
586                 (cfg)->disable_ssa = TRUE; \
587         } while (0)
588
589 #define NEW_ARGLOADA(cfg,dest,num) do { \
590                 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
591                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
592                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
593                 (dest)->inst_i0 = arg_array [(num)];    \
594                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
595                 (dest)->opcode = OP_LDADDR;     \
596                 (dest)->type = STACK_MP;        \
597                 (dest)->klass = (dest)->inst_i0->klass; \
598                 (cfg)->disable_ssa = TRUE; \
599         } while (0)
600
601 #define NEW_TEMPLOAD(cfg,dest,num) do { \
602                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
603                 (dest)->ssa_op = MONO_SSA_LOAD; \
604                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
605                 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
606                 type_to_eval_stack_type ((cfg), (dest)->inst_i0->inst_vtype, (dest));   \
607                 (dest)->klass = (dest)->inst_i0->klass; \
608         } while (0)
609
610 #define NEW_TEMPLOADA(cfg,dest,num) do {        \
611                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
612                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
613                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
614                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
615                 (dest)->opcode = OP_LDADDR;     \
616                 (dest)->type = STACK_MP;        \
617                 (dest)->klass = (dest)->inst_i0->klass; \
618         if (!MONO_TYPE_ISSTRUCT (cfg->varinfo [(num)]->inst_vtype)) \
619            (cfg)->disable_ssa = TRUE; \
620         } while (0)
621
622
623 #define NEW_INDLOAD(cfg,dest,addr,vtype) do {   \
624                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
625                 (dest)->inst_left = addr;       \
626                 (dest)->opcode = mini_type_to_ldind ((cfg), vtype);     \
627                 type_to_eval_stack_type ((cfg), vtype, (dest)); \
628                 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/     \
629         } while (0)
630
631 #define NEW_INDSTORE(cfg,dest,addr,value,vtype) do {    \
632                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
633                 (dest)->inst_i0 = addr; \
634                 (dest)->opcode = mini_type_to_stind ((cfg), vtype);     \
635                 (dest)->inst_i1 = (value);      \
636                 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/     \
637         } while (0)
638
639 #define NEW_TEMPSTORE(cfg,dest,num,inst) do {   \
640                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
641                 (dest)->ssa_op = MONO_SSA_STORE;        \
642                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
643                 (dest)->opcode = mini_type_to_stind ((cfg), (dest)->inst_i0->inst_vtype); \
644                 (dest)->inst_i1 = (inst);       \
645                 (dest)->klass = (dest)->inst_i0->klass; \
646         } while (0)
647
648 #define NEW_LOCSTORE(cfg,dest,num,inst) do {    \
649                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
650                 (dest)->opcode = mini_type_to_stind ((cfg), header->locals [(num)]); \
651                 (dest)->ssa_op = MONO_SSA_STORE;        \
652                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
653                 (dest)->inst_i1 = (inst);       \
654                 (dest)->klass = (dest)->inst_i0->klass; \
655         } while (0)
656
657 #define NEW_ARGSTORE(cfg,dest,num,inst) do {    \
658                 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
659                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
660                 (dest)->opcode = mini_type_to_stind ((cfg), param_types [(num)]); \
661                 (dest)->ssa_op = MONO_SSA_STORE;        \
662                 (dest)->inst_i0 = arg_array [(num)];    \
663                 (dest)->inst_i1 = (inst);       \
664                 (dest)->klass = (dest)->inst_i0->klass; \
665         } while (0)
666
667 #define NEW_MEMCPY(cfg,dest,dst,src,memcpy_size,memcpy_align) do { \
668                 MONO_INST_NEW (cfg, dest, OP_MEMCPY); \
669         (dest)->inst_left = (dst); \
670                 (dest)->inst_right = (src); \
671                 (dest)->cil_code = ip; \
672         (dest)->backend.memcpy_args = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoMemcpyArgs)); \
673                 (dest)->backend.memcpy_args->size = (memcpy_size); \
674                 (dest)->backend.memcpy_args->align = (memcpy_align); \
675     } while (0)
676
677 #define NEW_MEMSET(cfg,dest,dst,imm,memcpy_size,memcpy_align) do { \
678                 MONO_INST_NEW (cfg, dest, OP_MEMSET); \
679         (dest)->inst_left = (dst); \
680                 (dest)->inst_imm = (imm); \
681                 (dest)->cil_code = ip; \
682         (dest)->backend.memcpy_args = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoMemcpyArgs)); \
683                 (dest)->backend.memcpy_args->size = (memcpy_size); \
684                 (dest)->backend.memcpy_args->align = (memcpy_align); \
685     } while (0)
686
687 #define NEW_DUMMY_USE(cfg,dest,load) do { \
688                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
689                 (dest)->opcode = OP_DUMMY_USE; \
690                 (dest)->inst_left = (load); \
691     } while (0)
692
693 #define NEW_DUMMY_STORE(cfg,dest,num) do { \
694                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
695                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
696                 (dest)->opcode = OP_DUMMY_STORE; \
697                 (dest)->klass = (dest)->inst_i0->klass; \
698         } while (0)
699
700 #define ADD_BINOP(op) do {      \
701                 MONO_INST_NEW (cfg, ins, (op)); \
702                 ins->cil_code = ip;     \
703                 sp -= 2;        \
704                 ins->inst_i0 = sp [0];  \
705                 ins->inst_i1 = sp [1];  \
706                 *sp++ = ins;    \
707                 type_from_op (ins);     \
708                 CHECK_TYPE (ins);       \
709         } while (0)
710
711 #define ADD_UNOP(op) do {       \
712                 MONO_INST_NEW (cfg, ins, (op)); \
713                 ins->cil_code = ip;     \
714                 sp--;   \
715                 ins->inst_i0 = sp [0];  \
716                 *sp++ = ins;    \
717                 type_from_op (ins);     \
718                 CHECK_TYPE (ins);       \
719         } while (0)
720
721 #define ADD_BINCOND(next_block) do {    \
722                 MonoInst *cmp;  \
723                 sp -= 2;                \
724                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
725                 cmp->inst_i0 = sp [0];  \
726                 cmp->inst_i1 = sp [1];  \
727                 cmp->cil_code = ins->cil_code;  \
728                 type_from_op (cmp);     \
729                 CHECK_TYPE (cmp);       \
730                 ins->inst_i0 = cmp;     \
731                 MONO_ADD_INS (bblock, ins);     \
732                 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);      \
733                 GET_BBLOCK (cfg, tblock, target);               \
734                 link_bblock (cfg, bblock, tblock);      \
735                 ins->inst_true_bb = tblock;     \
736                 CHECK_BBLOCK (target, ip, tblock);      \
737                 if ((next_block)) {     \
738                         link_bblock (cfg, bblock, (next_block));        \
739                         ins->inst_false_bb = (next_block);      \
740                         start_new_bblock = 1;   \
741                 } else {        \
742                         GET_BBLOCK (cfg, tblock, ip);           \
743                         link_bblock (cfg, bblock, tblock);      \
744                         ins->inst_false_bb = tblock;    \
745                         start_new_bblock = 2;   \
746                 }       \
747         } while (0)
748
749 /* FIXME: handle float, long ... */
750 #define ADD_UNCOND(istrue) do { \
751                 MonoInst *cmp;  \
752                 sp--;           \
753                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
754                 cmp->inst_i0 = sp [0];  \
755                 switch (cmp->inst_i0->type) { \
756                 case STACK_I8: \
757                         cmp->inst_i1 = zero_int64; break; \
758                 case STACK_R8: \
759                         cmp->inst_i1 = zero_r8; break; \
760                 case STACK_PTR: \
761                 case STACK_MP: \
762                         cmp->inst_i1 = zero_ptr; break; \
763                 case STACK_OBJ: \
764                         cmp->inst_i1 = zero_obj; break; \
765                 default: \
766                         cmp->inst_i1 = zero_int32;  \
767                 }  \
768                 cmp->cil_code = ins->cil_code;  \
769                 type_from_op (cmp);     \
770                 CHECK_TYPE (cmp);       \
771                 ins->inst_i0 = cmp;     \
772                 ins->opcode = (istrue)? CEE_BNE_UN: CEE_BEQ;    \
773                 MONO_ADD_INS (bblock, ins);     \
774                 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);      \
775                 GET_BBLOCK (cfg, tblock, target);               \
776                 link_bblock (cfg, bblock, tblock);      \
777                 ins->inst_true_bb = tblock;     \
778                 CHECK_BBLOCK (target, ip, tblock);      \
779                 GET_BBLOCK (cfg, tblock, ip);           \
780                 link_bblock (cfg, bblock, tblock);      \
781                 ins->inst_false_bb = tblock;    \
782                 start_new_bblock = 2;   \
783         } while (0)
784
785 #define NEW_LDELEMA(cfg,dest,sp,k) do { \
786                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
787                 (dest)->opcode = CEE_LDELEMA;   \
788                 (dest)->inst_left = (sp) [0];   \
789                 (dest)->inst_right = (sp) [1];  \
790                 (dest)->type = STACK_MP;        \
791                 (dest)->klass = (k);    \
792                 (cfg)->flags |= MONO_CFG_HAS_LDELEMA; \
793         } while (0)
794
795 #define NEW_GROUP(cfg,dest,el1,el2) do {        \
796                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
797                 (dest)->opcode = OP_GROUP;      \
798                 (dest)->inst_left = (el1);      \
799                 (dest)->inst_right = (el2);     \
800         } while (0)
801
802 #if 0
803 static gint
804 compare_bblock (gconstpointer a, gconstpointer b)
805 {
806         const MonoBasicBlock *b1 = a;
807         const MonoBasicBlock *b2 = b;
808
809         return b2->cil_code - b1->cil_code;
810 }
811 #endif
812
813 /* *
814  * link_bblock: Links two basic blocks
815  *
816  * links two basic blocks in the control flow graph, the 'from'
817  * argument is the starting block and the 'to' argument is the block
818  * the control flow ends to after 'from'.
819  */
820 static void
821 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
822 {
823         MonoBasicBlock **newa;
824         int i, found;
825
826 #if 0
827         if (from->cil_code) {
828                 if (to->cil_code)
829                         g_print ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
830                 else
831                         g_print ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
832         } else {
833                 if (to->cil_code)
834                         g_print ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
835                 else
836                         g_print ("edge from entry to exit\n");
837         }
838 #endif
839         found = FALSE;
840         for (i = 0; i < from->out_count; ++i) {
841                 if (to == from->out_bb [i]) {
842                         found = TRUE;
843                         break;
844                 }
845         }
846         if (!found) {
847                 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
848                 for (i = 0; i < from->out_count; ++i) {
849                         newa [i] = from->out_bb [i];
850                 }
851                 newa [i] = to;
852                 from->out_count++;
853                 from->out_bb = newa;
854         }
855
856         found = FALSE;
857         for (i = 0; i < to->in_count; ++i) {
858                 if (from == to->in_bb [i]) {
859                         found = TRUE;
860                         break;
861                 }
862         }
863         if (!found) {
864                 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
865                 for (i = 0; i < to->in_count; ++i) {
866                         newa [i] = to->in_bb [i];
867                 }
868                 newa [i] = from;
869                 to->in_count++;
870                 to->in_bb = newa;
871         }
872 }
873
874 /**
875  * mono_unlink_bblock:
876  *
877  *   Unlink two basic blocks.
878  */
879 static void
880 mono_unlink_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
881 {
882         int i, pos;
883         gboolean found;
884
885         found = FALSE;
886         for (i = 0; i < from->out_count; ++i) {
887                 if (to == from->out_bb [i]) {
888                         found = TRUE;
889                         break;
890                 }
891         }
892         if (found) {
893                 pos = 0;
894                 for (i = 0; i < from->out_count; ++i) {
895                         if (from->out_bb [i] != to)
896                                 from->out_bb [pos ++] = from->out_bb [i];
897                 }
898                 g_assert (pos == from->out_count - 1);
899                 from->out_count--;
900         }
901
902         found = FALSE;
903         for (i = 0; i < to->in_count; ++i) {
904                 if (from == to->in_bb [i]) {
905                         found = TRUE;
906                         break;
907                 }
908         }
909         if (found) {
910                 pos = 0;
911                 for (i = 0; i < to->in_count; ++i) {
912                         if (to->in_bb [i] != from)
913                                 to->in_bb [pos ++] = to->in_bb [i];
914                 }
915                 g_assert (pos == to->in_count - 1);
916                 to->in_count--;
917         }
918 }
919
920 /**
921  * mono_find_block_region:
922  *
923  *   We mark each basic block with a region ID. We use that to avoid BB
924  *   optimizations when blocks are in different regions.
925  *
926  * Returns:
927  *   A region token that encodes where this region is, and information
928  *   about the clause owner for this block.
929  *
930  *   The region encodes the try/catch/filter clause that owns this block
931  *   as well as the type.  -1 is a special value that represents a block
932  *   that is in none of try/catch/filter.
933  */
934 static int
935 mono_find_block_region (MonoCompile *cfg, int offset)
936 {
937         MonoMethod *method = cfg->method;
938         MonoMethodHeader *header = mono_method_get_header (method);
939         MonoExceptionClause *clause;
940         int i;
941
942         /* first search for handlers and filters */
943         for (i = 0; i < header->num_clauses; ++i) {
944                 clause = &header->clauses [i];
945                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
946                     (offset < (clause->handler_offset)))
947                         return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
948                            
949                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
950                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
951                                 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
952                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
953                                 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
954                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
955                                 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
956                 }
957         }
958
959         /* search the try blocks */
960         for (i = 0; i < header->num_clauses; ++i) {
961                 clause = &header->clauses [i];
962                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
963                         return ((i + 1) << 8) | clause->flags;
964         }
965
966         return -1;
967 }
968
969 static GList*
970 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
971 {
972         MonoMethod *method = cfg->method;
973         MonoMethodHeader *header = mono_method_get_header (method);
974         MonoExceptionClause *clause;
975         MonoBasicBlock *handler;
976         int i;
977         GList *res = NULL;
978
979         for (i = 0; i < header->num_clauses; ++i) {
980                 clause = &header->clauses [i];
981                 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) && 
982                     (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
983                         if (clause->flags == type) {
984                                 handler = cfg->cil_offset_to_bb [clause->handler_offset];
985                                 g_assert (handler);
986                                 res = g_list_append (res, handler);
987                         }
988                 }
989         }
990         return res;
991 }
992
993 MonoInst *
994 mono_find_spvar_for_region (MonoCompile *cfg, int region)
995 {
996         return g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
997 }
998
999 static void
1000 mono_create_spvar_for_region (MonoCompile *cfg, int region)
1001 {
1002         MonoInst *var;
1003
1004         var = g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
1005         if (var)
1006                 return;
1007
1008         var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1009         /* prevent it from being register allocated */
1010         var->flags |= MONO_INST_INDIRECT;
1011
1012         g_hash_table_insert (cfg->spvars, GINT_TO_POINTER (region), var);
1013 }
1014
1015 static MonoInst *
1016 mono_find_exvar_for_offset (MonoCompile *cfg, int offset)
1017 {
1018         return g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
1019 }
1020
1021 static MonoInst*
1022 mono_create_exvar_for_offset (MonoCompile *cfg, int offset)
1023 {
1024         MonoInst *var;
1025
1026         var = g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
1027         if (var)
1028                 return var;
1029
1030         var = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
1031         /* prevent it from being register allocated */
1032         var->flags |= MONO_INST_INDIRECT;
1033
1034         g_hash_table_insert (cfg->exvars, GINT_TO_POINTER (offset), var);
1035
1036         return var;
1037 }
1038
1039 static void
1040 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
1041 {
1042         int i;
1043
1044         array [*dfn] = start;
1045         /*g_print ("visit %d at %p (BB%ld)\n", *dfn, start->cil_code, start->block_num);*/
1046         for (i = 0; i < start->out_count; ++i) {
1047                 if (start->out_bb [i]->dfn)
1048                         continue;
1049                 (*dfn)++;
1050                 start->out_bb [i]->dfn = *dfn;
1051                 start->out_bb [i]->df_parent = start;
1052                 array [*dfn] = start->out_bb [i];
1053                 df_visit (start->out_bb [i], dfn, array);
1054         }
1055 }
1056
1057 static MonoBasicBlock*
1058 find_previous (MonoBasicBlock **bblocks, guint32 n_bblocks, MonoBasicBlock *start, const guchar *code)
1059 {
1060         MonoBasicBlock *best = start;
1061         int i;
1062
1063         for (i = 0; i < n_bblocks; ++i) {
1064                 if (bblocks [i]) {
1065                         MonoBasicBlock *bb = bblocks [i];
1066
1067                         if (bb->cil_code && bb->cil_code < code && bb->cil_code > best->cil_code)
1068                                 best = bb;
1069                 }
1070         }
1071
1072         return best;
1073 }
1074
1075 static void
1076 split_bblock (MonoCompile *cfg, MonoBasicBlock *first, MonoBasicBlock *second) {
1077         int i, j;
1078         MonoInst *inst;
1079         MonoBasicBlock *bb;
1080
1081         if (second->code)
1082                 return;
1083         
1084         /* 
1085          * FIXME: take into account all the details:
1086          * second may have been the target of more than one bblock
1087          */
1088         second->out_count = first->out_count;
1089         second->out_bb = first->out_bb;
1090
1091         for (i = 0; i < first->out_count; ++i) {
1092                 bb = first->out_bb [i];
1093                 for (j = 0; j < bb->in_count; ++j) {
1094                         if (bb->in_bb [j] == first)
1095                                 bb->in_bb [j] = second;
1096                 }
1097         }
1098
1099         first->out_count = 0;
1100         first->out_bb = NULL;
1101         link_bblock (cfg, first, second);
1102
1103         second->last_ins = first->last_ins;
1104
1105         /*g_print ("start search at %p for %p\n", first->cil_code, second->cil_code);*/
1106         for (inst = first->code; inst && inst->next; inst = inst->next) {
1107                 /*char *code = mono_disasm_code_one (NULL, cfg->method, inst->next->cil_code, NULL);
1108                 g_print ("found %p: %s", inst->next->cil_code, code);
1109                 g_free (code);*/
1110                 if (inst->cil_code < second->cil_code && inst->next->cil_code >= second->cil_code) {
1111                         second->code = inst->next;
1112                         inst->next = NULL;
1113                         first->last_ins = inst;
1114                         second->next_bb = first->next_bb;
1115                         first->next_bb = second;
1116                         return;
1117                 }
1118         }
1119         if (!second->code) {
1120                 g_warning ("bblock split failed in %s::%s\n", cfg->method->klass->name, cfg->method->name);
1121                 //G_BREAKPOINT ();
1122         }
1123 }
1124
1125 static guint32
1126 reverse_branch_op (guint32 opcode)
1127 {
1128         static const int reverse_map [] = {
1129                 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
1130                 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
1131         };
1132         static const int reverse_fmap [] = {
1133                 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
1134                 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
1135         };
1136         static const int reverse_lmap [] = {
1137                 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
1138                 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
1139         };
1140         static const int reverse_imap [] = {
1141                 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
1142                 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
1143         };
1144                                 
1145         if (opcode >= CEE_BEQ && opcode <= CEE_BLT_UN) {
1146                 opcode = reverse_map [opcode - CEE_BEQ];
1147         } else if (opcode >= OP_FBEQ && opcode <= OP_FBLT_UN) {
1148                 opcode = reverse_fmap [opcode - OP_FBEQ];
1149         } else if (opcode >= OP_LBEQ && opcode <= OP_LBLT_UN) {
1150                 opcode = reverse_lmap [opcode - OP_LBEQ];
1151         } else if (opcode >= OP_IBEQ && opcode <= OP_IBLT_UN) {
1152                 opcode = reverse_imap [opcode - OP_IBEQ];
1153         } else
1154                 g_assert_not_reached ();
1155
1156         return opcode;
1157 }
1158
1159 #ifdef MONO_ARCH_SOFT_FLOAT
1160 static int
1161 condbr_to_fp_br (int opcode)
1162 {
1163         switch (opcode) {
1164         case CEE_BEQ: return OP_FBEQ;
1165         case CEE_BGE: return OP_FBGE;
1166         case CEE_BGT: return OP_FBGT;
1167         case CEE_BLE: return OP_FBLE;
1168         case CEE_BLT: return OP_FBLT;
1169         case CEE_BNE_UN: return OP_FBNE_UN;
1170         case CEE_BGE_UN: return OP_FBGE_UN;
1171         case CEE_BGT_UN: return OP_FBGT_UN;
1172         case CEE_BLE_UN: return OP_FBLE_UN;
1173         case CEE_BLT_UN: return OP_FBLT_UN;
1174         }
1175         g_assert_not_reached ();
1176         return 0;
1177 }
1178 #endif
1179
1180 /*
1181  * Returns the type used in the eval stack when @type is loaded.
1182  * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
1183  */
1184 static void
1185 type_to_eval_stack_type (MonoCompile *cfg, MonoType *type, MonoInst *inst)
1186 {
1187         MonoClass *klass;
1188
1189         inst->klass = klass = mono_class_from_mono_type (type);
1190         if (type->byref) {
1191                 inst->type = STACK_MP;
1192                 return;
1193         }
1194
1195 handle_enum:
1196         switch (type->type) {
1197         case MONO_TYPE_VOID:
1198                 inst->type = STACK_INV;
1199                 return;
1200         case MONO_TYPE_I1:
1201         case MONO_TYPE_U1:
1202         case MONO_TYPE_BOOLEAN:
1203         case MONO_TYPE_I2:
1204         case MONO_TYPE_U2:
1205         case MONO_TYPE_CHAR:
1206         case MONO_TYPE_I4:
1207         case MONO_TYPE_U4:
1208                 inst->type = STACK_I4;
1209                 return;
1210         case MONO_TYPE_I:
1211         case MONO_TYPE_U:
1212         case MONO_TYPE_PTR:
1213         case MONO_TYPE_FNPTR:
1214                 inst->type = STACK_PTR;
1215                 return;
1216         case MONO_TYPE_CLASS:
1217         case MONO_TYPE_STRING:
1218         case MONO_TYPE_OBJECT:
1219         case MONO_TYPE_SZARRAY:
1220         case MONO_TYPE_ARRAY:    
1221                 inst->type = STACK_OBJ;
1222                 return;
1223         case MONO_TYPE_I8:
1224         case MONO_TYPE_U8:
1225                 inst->type = STACK_I8;
1226                 return;
1227         case MONO_TYPE_R4:
1228         case MONO_TYPE_R8:
1229                 inst->type = STACK_R8;
1230                 return;
1231         case MONO_TYPE_VALUETYPE:
1232                 if (type->data.klass->enumtype) {
1233                         type = type->data.klass->enum_basetype;
1234                         goto handle_enum;
1235                 } else {
1236                         inst->klass = klass;
1237                         inst->type = STACK_VTYPE;
1238                         return;
1239                 }
1240         case MONO_TYPE_TYPEDBYREF:
1241                 inst->klass = mono_defaults.typed_reference_class;
1242                 inst->type = STACK_VTYPE;
1243                 return;
1244         case MONO_TYPE_GENERICINST:
1245                 type = &type->data.generic_class->container_class->byval_arg;
1246                 goto handle_enum;
1247         case MONO_TYPE_VAR :
1248         case MONO_TYPE_MVAR :
1249                 /* FIXME: all the arguments must be references for now,
1250                  * later look inside cfg and see if the arg num is
1251                  * really a reference
1252                  */
1253                 g_assert (cfg->generic_sharing_context);
1254                 inst->type = STACK_OBJ;
1255                 return;
1256         default:
1257                 g_error ("unknown type 0x%02x in eval stack type", type->type);
1258         }
1259 }
1260
1261 /*
1262  * The following tables are used to quickly validate the IL code in type_from_op ().
1263  */
1264 static const char
1265 bin_num_table [STACK_MAX] [STACK_MAX] = {
1266         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1267         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
1268         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1269         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
1270         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8,  STACK_INV, STACK_INV, STACK_INV},
1271         {STACK_INV, STACK_MP,  STACK_INV, STACK_MP,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
1272         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1273         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1274 };
1275
1276 static const char 
1277 neg_table [] = {
1278         STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV
1279 };
1280
1281 /* reduce the size of this table */
1282 static const char
1283 bin_int_table [STACK_MAX] [STACK_MAX] = {
1284         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1285         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1286         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1287         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1288         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1289         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1290         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1291         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1292 };
1293
1294 static const char
1295 bin_comp_table [STACK_MAX] [STACK_MAX] = {
1296 /*      Inv i  L  p  F  &  O  vt */
1297         {0},
1298         {0, 1, 0, 1, 0, 0, 0, 0}, /* i, int32 */
1299         {0, 0, 1, 0, 0, 0, 0, 0}, /* L, int64 */
1300         {0, 1, 0, 1, 0, 2, 4, 0}, /* p, ptr */
1301         {0, 0, 0, 0, 1, 0, 0, 0}, /* F, R8 */
1302         {0, 0, 0, 2, 0, 1, 0, 0}, /* &, managed pointer */
1303         {0, 0, 0, 4, 0, 0, 3, 0}, /* O, reference */
1304         {0, 0, 0, 0, 0, 0, 0, 0}, /* vt value type */
1305 };
1306
1307 /* reduce the size of this table */
1308 static const char
1309 shift_table [STACK_MAX] [STACK_MAX] = {
1310         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1311         {STACK_INV, STACK_I4,  STACK_INV, STACK_I4,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1312         {STACK_INV, STACK_I8,  STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1313         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1314         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1315         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1316         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1317         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1318 };
1319
1320 /*
1321  * Tables to map from the non-specific opcode to the matching
1322  * type-specific opcode.
1323  */
1324 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
1325 static const guint16
1326 binops_op_map [STACK_MAX] = {
1327         0, 0, OP_LADD-CEE_ADD, OP_PADD-CEE_ADD, OP_FADD-CEE_ADD, OP_PADD-CEE_ADD
1328 };
1329
1330 /* handles from CEE_NEG to CEE_CONV_U8 */
1331 static const guint16
1332 unops_op_map [STACK_MAX] = {
1333         0, 0, OP_LNEG-CEE_NEG, OP_PNEG-CEE_NEG, OP_FNEG-CEE_NEG, OP_PNEG-CEE_NEG
1334 };
1335
1336 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
1337 static const guint16
1338 ovfops_op_map [STACK_MAX] = {
1339         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
1340 };
1341
1342 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
1343 static const guint16
1344 ovf2ops_op_map [STACK_MAX] = {
1345         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
1346 };
1347
1348 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
1349 static const guint16
1350 ovf3ops_op_map [STACK_MAX] = {
1351         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
1352 };
1353
1354 /* handles from CEE_CEQ to CEE_CLT_UN */
1355 static const guint16
1356 ceqops_op_map [STACK_MAX] = {
1357         0, 0, OP_LCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, OP_FCEQ-OP_CEQ, OP_LCEQ-OP_CEQ
1358 };
1359
1360 /*
1361  * Sets ins->type (the type on the eval stack) according to the
1362  * type of the opcode and the arguments to it.
1363  * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
1364  *
1365  * FIXME: this function sets ins->type unconditionally in some cases, but
1366  * it should set it to invalid for some types (a conv.x on an object)
1367  */
1368 static void
1369 type_from_op (MonoInst *ins) {
1370         switch (ins->opcode) {
1371         /* binops */
1372         case CEE_ADD:
1373         case CEE_SUB:
1374         case CEE_MUL:
1375         case CEE_DIV:
1376         case CEE_REM:
1377                 /* FIXME: check unverifiable args for STACK_MP */
1378                 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1379                 ins->opcode += binops_op_map [ins->type];
1380                 return;
1381         case CEE_DIV_UN:
1382         case CEE_REM_UN:
1383         case CEE_AND:
1384         case CEE_OR:
1385         case CEE_XOR:
1386                 ins->type = bin_int_table [ins->inst_i0->type] [ins->inst_i1->type];
1387                 ins->opcode += binops_op_map [ins->type];
1388                 return;
1389         case CEE_SHL:
1390         case CEE_SHR:
1391         case CEE_SHR_UN:
1392                 ins->type = shift_table [ins->inst_i0->type] [ins->inst_i1->type];
1393                 ins->opcode += binops_op_map [ins->type];
1394                 return;
1395         case OP_COMPARE:
1396         case OP_LCOMPARE:
1397                 /* FIXME: handle some specifics with ins->next->type */
1398                 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1399                 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))))
1400                         ins->opcode = OP_LCOMPARE;
1401                 return;
1402         case OP_CEQ:
1403                 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1404                 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1405                 return;
1406                 
1407         case OP_CGT:
1408         case OP_CGT_UN:
1409         case OP_CLT:
1410         case OP_CLT_UN:
1411                 ins->type = (bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] & 1) ? STACK_I4: STACK_INV;
1412                 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1413                 return;
1414         /* unops */
1415         case CEE_NEG:
1416                 ins->type = neg_table [ins->inst_i0->type];
1417                 ins->opcode += unops_op_map [ins->type];
1418                 return;
1419         case CEE_NOT:
1420                 if (ins->inst_i0->type >= STACK_I4 && ins->inst_i0->type <= STACK_PTR)
1421                         ins->type = ins->inst_i0->type;
1422                 else
1423                         ins->type = STACK_INV;
1424                 ins->opcode += unops_op_map [ins->type];
1425                 return;
1426         case CEE_CONV_I1:
1427         case CEE_CONV_I2:
1428         case CEE_CONV_I4:
1429         case CEE_CONV_U4:
1430                 ins->type = STACK_I4;
1431                 ins->opcode += unops_op_map [ins->inst_i0->type];
1432                 return;
1433         case CEE_CONV_R_UN:
1434                 ins->type = STACK_R8;
1435                 switch (ins->inst_i0->type) {
1436                 case STACK_I4:
1437                 case STACK_PTR:
1438                         break;
1439                 case STACK_I8:
1440                         ins->opcode = OP_LCONV_TO_R_UN; 
1441                         break;
1442                 }
1443                 return;
1444         case CEE_CONV_OVF_I1:
1445         case CEE_CONV_OVF_U1:
1446         case CEE_CONV_OVF_I2:
1447         case CEE_CONV_OVF_U2:
1448         case CEE_CONV_OVF_I4:
1449         case CEE_CONV_OVF_U4:
1450                 ins->type = STACK_I4;
1451                 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1452                 return;
1453         case CEE_CONV_OVF_I_UN:
1454         case CEE_CONV_OVF_U_UN:
1455                 ins->type = STACK_PTR;
1456                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1457                 return;
1458         case CEE_CONV_OVF_I1_UN:
1459         case CEE_CONV_OVF_I2_UN:
1460         case CEE_CONV_OVF_I4_UN:
1461         case CEE_CONV_OVF_U1_UN:
1462         case CEE_CONV_OVF_U2_UN:
1463         case CEE_CONV_OVF_U4_UN:
1464                 ins->type = STACK_I4;
1465                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1466                 return;
1467         case CEE_CONV_U:
1468                 ins->type = STACK_PTR;
1469                 switch (ins->inst_i0->type) {
1470                 case STACK_I4:
1471                         break;
1472                 case STACK_PTR:
1473                 case STACK_MP:
1474 #if SIZEOF_VOID_P == 8
1475                         ins->opcode = OP_LCONV_TO_U;
1476 #endif
1477                         break;
1478                 case STACK_I8:
1479                         ins->opcode = OP_LCONV_TO_U;
1480                         break;
1481                 case STACK_R8:
1482                         ins->opcode = OP_FCONV_TO_U;
1483                         break;
1484                 }
1485                 return;
1486         case CEE_CONV_I8:
1487         case CEE_CONV_U8:
1488                 ins->type = STACK_I8;
1489                 ins->opcode += unops_op_map [ins->inst_i0->type];
1490                 return;
1491         case CEE_CONV_OVF_I8:
1492         case CEE_CONV_OVF_U8:
1493                 ins->type = STACK_I8;
1494                 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1495                 return;
1496         case CEE_CONV_OVF_U8_UN:
1497         case CEE_CONV_OVF_I8_UN:
1498                 ins->type = STACK_I8;
1499                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1500                 return;
1501         case CEE_CONV_R4:
1502         case CEE_CONV_R8:
1503                 ins->type = STACK_R8;
1504                 ins->opcode += unops_op_map [ins->inst_i0->type];
1505                 return;
1506         case OP_CKFINITE:
1507                 ins->type = STACK_R8;           
1508                 return;
1509         case CEE_CONV_U2:
1510         case CEE_CONV_U1:
1511                 ins->type = STACK_I4;
1512                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1513                 break;
1514         case CEE_CONV_I:
1515         case CEE_CONV_OVF_I:
1516         case CEE_CONV_OVF_U:
1517                 ins->type = STACK_PTR;
1518                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1519                 return;
1520         case CEE_ADD_OVF:
1521         case CEE_ADD_OVF_UN:
1522         case CEE_MUL_OVF:
1523         case CEE_MUL_OVF_UN:
1524         case CEE_SUB_OVF:
1525         case CEE_SUB_OVF_UN:
1526                 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1527                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1528                 return;
1529         default:
1530                 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1531                 break;
1532         }
1533 }
1534
1535 static const char 
1536 ldind_type [] = {
1537         STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_R8, STACK_OBJ
1538 };
1539
1540 /* map ldelem.x to the matching ldind.x opcode */
1541 static const guchar
1542 ldelem_to_ldind [] = {
1543         CEE_LDIND_I1,
1544         CEE_LDIND_U1,
1545         CEE_LDIND_I2,
1546         CEE_LDIND_U2,
1547         CEE_LDIND_I4,
1548         CEE_LDIND_U4,
1549         CEE_LDIND_I8,
1550         CEE_LDIND_I,
1551         CEE_LDIND_R4,
1552         CEE_LDIND_R8,
1553         CEE_LDIND_REF
1554 };
1555
1556 /* map stelem.x to the matching stind.x opcode */
1557 static const guchar
1558 stelem_to_stind [] = {
1559         CEE_STIND_I,
1560         CEE_STIND_I1,
1561         CEE_STIND_I2,
1562         CEE_STIND_I4,
1563         CEE_STIND_I8,
1564         CEE_STIND_R4,
1565         CEE_STIND_R8,
1566         CEE_STIND_REF
1567 };
1568
1569 #if 0
1570
1571 static const char
1572 param_table [STACK_MAX] [STACK_MAX] = {
1573         {0},
1574 };
1575
1576 static int
1577 check_values_to_signature (MonoInst *args, MonoType *this, MonoMethodSignature *sig) {
1578         int i;
1579
1580         if (sig->hasthis) {
1581                 switch (args->type) {
1582                 case STACK_I4:
1583                 case STACK_I8:
1584                 case STACK_R8:
1585                 case STACK_VTYPE:
1586                 case STACK_INV:
1587                         return 0;
1588                 }
1589                 args++;
1590         }
1591         for (i = 0; i < sig->param_count; ++i) {
1592                 switch (args [i].type) {
1593                 case STACK_INV:
1594                         return 0;
1595                 case STACK_MP:
1596                         if (!sig->params [i]->byref)
1597                                 return 0;
1598                         continue;
1599                 case STACK_OBJ:
1600                         if (sig->params [i]->byref)
1601                                 return 0;
1602                         switch (sig->params [i]->type) {
1603                         case MONO_TYPE_CLASS:
1604                         case MONO_TYPE_STRING:
1605                         case MONO_TYPE_OBJECT:
1606                         case MONO_TYPE_SZARRAY:
1607                         case MONO_TYPE_ARRAY:
1608                                 break;
1609                         default:
1610                                 return 0;
1611                         }
1612                         continue;
1613                 case STACK_R8:
1614                         if (sig->params [i]->byref)
1615                                 return 0;
1616                         if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1617                                 return 0;
1618                         continue;
1619                 case STACK_PTR:
1620                 case STACK_I4:
1621                 case STACK_I8:
1622                 case STACK_VTYPE:
1623                         break;
1624                 }
1625                 /*if (!param_table [args [i].type] [sig->params [i]->type])
1626                         return 0;*/
1627         }
1628         return 1;
1629 }
1630 #endif
1631
1632 static guint
1633 mini_type_to_ldind (MonoCompile* cfg, MonoType *type)
1634 {
1635         if (cfg->generic_sharing_context && !type->byref) {
1636                 /* FIXME: all the arguments must be references for now,
1637                  * later look inside cfg and see if the arg num is
1638                  * really a reference
1639                  */
1640                 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
1641                         return CEE_LDIND_REF;
1642         }
1643         return mono_type_to_ldind (type);
1644 }
1645
1646 static guint
1647 mini_type_to_stind (MonoCompile* cfg, MonoType *type)
1648 {
1649         if (cfg->generic_sharing_context && !type->byref) {
1650                 /* FIXME: all the arguments must be references for now,
1651                  * later look inside cfg and see if the arg num is
1652                  * really a reference
1653                  */
1654                 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
1655                         return CEE_STIND_REF;
1656         }
1657         return mono_type_to_stind (type);
1658 }
1659
1660 /*
1661  * When we need a pointer to the current domain many times in a method, we
1662  * call mono_domain_get() once and we store the result in a local variable.
1663  * This function returns the variable that represents the MonoDomain*.
1664  */
1665 inline static MonoInst *
1666 mono_get_domainvar (MonoCompile *cfg)
1667 {
1668         if (!cfg->domainvar)
1669                 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1670         return cfg->domainvar;
1671 }
1672
1673 /*
1674  * The got_var contains the address of the Global Offset Table when AOT 
1675  * compiling.
1676  */
1677 inline static MonoInst *
1678 mono_get_got_var (MonoCompile *cfg)
1679 {
1680 #ifdef MONO_ARCH_NEED_GOT_VAR
1681         if (!cfg->compile_aot)
1682                 return NULL;
1683         if (!cfg->got_var) {
1684                 cfg->got_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1685         }
1686         return cfg->got_var;
1687 #else
1688         return NULL;
1689 #endif
1690 }
1691
1692 MonoInst*
1693 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1694 {
1695         MonoInst *inst;
1696         int num = cfg->num_varinfo;
1697
1698         if ((num + 1) >= cfg->varinfo_count) {
1699                 cfg->varinfo_count = (cfg->varinfo_count + 2) * 2;
1700                 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
1701                 cfg->vars = (MonoMethodVar **)g_realloc (cfg->vars, sizeof (MonoMethodVar*) * cfg->varinfo_count);      
1702         }
1703
1704         /*g_print ("created temp %d of type 0x%x\n", num, type->type);*/
1705         mono_jit_stats.allocate_var++;
1706
1707         MONO_INST_NEW (cfg, inst, opcode);
1708         inst->inst_c0 = num;
1709         inst->inst_vtype = type;
1710         inst->klass = mono_class_from_mono_type (type);
1711         /* if set to 1 the variable is native */
1712         inst->backend.is_pinvoke = 0;
1713
1714         cfg->varinfo [num] = inst;
1715
1716         cfg->vars [num] = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoMethodVar));
1717         MONO_INIT_VARINFO (cfg->vars [num], num);
1718
1719         cfg->num_varinfo++;
1720         if (cfg->verbose_level > 2)
1721                 g_print ("created temp %d of type %s\n", num, mono_type_get_name (type));
1722         return inst;
1723 }
1724
1725 /*
1726  * Transform a MonoInst into a load from the variable of index var_index.
1727  */
1728 void
1729 mono_compile_make_var_load (MonoCompile *cfg, MonoInst *dest, gssize var_index) {
1730         memset (dest, 0, sizeof (MonoInst));
1731         dest->ssa_op = MONO_SSA_LOAD;
1732         dest->inst_i0 = cfg->varinfo [var_index];
1733         dest->opcode = mini_type_to_ldind (cfg, dest->inst_i0->inst_vtype);
1734         type_to_eval_stack_type (cfg, dest->inst_i0->inst_vtype, dest);
1735         dest->klass = dest->inst_i0->klass;
1736 }
1737
1738 /*
1739  * Create a MonoInst that is a load from the variable of index var_index.
1740  */
1741 MonoInst*
1742 mono_compile_create_var_load (MonoCompile *cfg, gssize var_index) {
1743         MonoInst *dest;
1744         NEW_TEMPLOAD (cfg,dest,var_index);
1745         return dest;
1746 }
1747
1748 /*
1749  * Create a MonoInst that is a store of the given value into the variable of index var_index.
1750  */
1751 MonoInst*
1752 mono_compile_create_var_store (MonoCompile *cfg, gssize var_index, MonoInst *value) {
1753         MonoInst *dest;
1754         NEW_TEMPSTORE (cfg, dest, var_index, value);
1755         return dest;
1756 }
1757
1758 static MonoType*
1759 type_from_stack_type (MonoInst *ins) {
1760         switch (ins->type) {
1761         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1762         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1763         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1764         case STACK_R8: return &mono_defaults.double_class->byval_arg;
1765         case STACK_MP:
1766                 /* 
1767                  * this if used to be commented without any specific reason, but
1768                  * it breaks #80235 when commented
1769                  */
1770                 if (ins->klass)
1771                         return &ins->klass->this_arg;
1772                 else
1773                         return &mono_defaults.object_class->this_arg;
1774         case STACK_OBJ:
1775                 /* ins->klass may not be set for ldnull.
1776                  * Also, if we have a boxed valuetype, we want an object lass,
1777                  * not the valuetype class
1778                  */
1779                 if (ins->klass && !ins->klass->valuetype)
1780                         return &ins->klass->byval_arg;
1781                 return &mono_defaults.object_class->byval_arg;
1782         case STACK_VTYPE: return &ins->klass->byval_arg;
1783         default:
1784                 g_error ("stack type %d to montype not handled\n", ins->type);
1785         }
1786         return NULL;
1787 }
1788
1789 MonoType*
1790 mono_type_from_stack_type (MonoInst *ins) {
1791         return type_from_stack_type (ins);
1792 }
1793
1794 static MonoClass*
1795 array_access_to_klass (int opcode, MonoInst *array_obj)
1796 {
1797         switch (opcode) {
1798         case CEE_LDELEM_U1:
1799                 return mono_defaults.byte_class;
1800         case CEE_LDELEM_U2:
1801                 return mono_defaults.uint16_class;
1802         case CEE_LDELEM_I:
1803         case CEE_STELEM_I:
1804                 return mono_defaults.int_class;
1805         case CEE_LDELEM_I1:
1806         case CEE_STELEM_I1:
1807                 return mono_defaults.sbyte_class;
1808         case CEE_LDELEM_I2:
1809         case CEE_STELEM_I2:
1810                 return mono_defaults.int16_class;
1811         case CEE_LDELEM_I4:
1812         case CEE_STELEM_I4:
1813                 return mono_defaults.int32_class;
1814         case CEE_LDELEM_U4:
1815                 return mono_defaults.uint32_class;
1816         case CEE_LDELEM_I8:
1817         case CEE_STELEM_I8:
1818                 return mono_defaults.int64_class;
1819         case CEE_LDELEM_R4:
1820         case CEE_STELEM_R4:
1821                 return mono_defaults.single_class;
1822         case CEE_LDELEM_R8:
1823         case CEE_STELEM_R8:
1824                 return mono_defaults.double_class;
1825         case CEE_LDELEM_REF:
1826         case CEE_STELEM_REF: {
1827                 MonoClass *klass = array_obj->klass;
1828                 /* FIXME: add assert */
1829                 if (klass && klass->rank)
1830                         return klass->element_class;
1831                 return mono_defaults.object_class;
1832         }
1833         default:
1834                 g_assert_not_reached ();
1835         }
1836         return NULL;
1837 }
1838
1839 void
1840 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
1841 {
1842         MonoInst *prev;
1843         if (!bb->code) {
1844                 MONO_ADD_INS (bb, inst);
1845                 return;
1846         }
1847         switch (bb->last_ins->opcode) {
1848         case CEE_BEQ:
1849         case CEE_BGE:
1850         case CEE_BGT:
1851         case CEE_BLE:
1852         case CEE_BLT:
1853         case CEE_BNE_UN:
1854         case CEE_BGE_UN:
1855         case CEE_BGT_UN:
1856         case CEE_BLE_UN:
1857         case CEE_BLT_UN:
1858         case OP_BR:
1859         case CEE_SWITCH:
1860                 prev = bb->code;
1861                 while (prev->next && prev->next != bb->last_ins)
1862                         prev = prev->next;
1863                 if (prev == bb->code) {
1864                         if (bb->last_ins == bb->code) {
1865                                 inst->next = bb->code;
1866                                 bb->code = inst;
1867                         } else {
1868                                 inst->next = prev->next;
1869                                 prev->next = inst;
1870                         }
1871                 } else {
1872                         inst->next = bb->last_ins;
1873                         prev->next = inst;
1874                 }
1875                 break;
1876         //      g_warning ("handle conditional jump in add_ins_to_end ()\n");
1877         default:
1878                 MONO_ADD_INS (bb, inst);
1879                 break;
1880         }
1881 }
1882
1883 void
1884 mono_add_varcopy_to_end (MonoCompile *cfg, MonoBasicBlock *bb, int src, int dest)
1885 {
1886         MonoInst *inst, *load;
1887
1888         NEW_TEMPLOAD (cfg, load, src);
1889
1890         NEW_TEMPSTORE (cfg, inst, dest, load);
1891         /* FIXME: handle CEE_STIND_R4 */
1892         if (inst->opcode == CEE_STOBJ) {
1893                 NEW_TEMPLOADA (cfg, inst, dest);
1894                 handle_stobj (cfg, bb, inst, load, NULL, inst->klass, TRUE, FALSE, FALSE);
1895         } else {
1896                 inst->cil_code = NULL;
1897                 mono_add_ins_to_end (bb, inst);
1898         }
1899 }
1900
1901 /*
1902  * merge_stacks:
1903  *
1904  * Merge stack state between two basic blocks according to Ecma 335, Partition III,
1905  * section 1.8.1.1. Store the resulting stack state into stack_2.
1906  * Returns: TRUE, if verification succeeds, FALSE otherwise.
1907  * FIXME: We should store the stack state in a dedicated structure instead of in
1908  * MonoInst's.
1909  */
1910 static gboolean
1911 merge_stacks (MonoCompile *cfg, MonoStackSlot *state_1, MonoStackSlot *state_2, guint32 size)
1912 {
1913         int i;
1914
1915         if (cfg->dont_verify_stack_merge)
1916                 return TRUE;
1917
1918         /* FIXME: Implement all checks from the spec */
1919
1920         for (i = 0; i < size; ++i) {
1921                 MonoStackSlot *slot1 = &state_1 [i];
1922                 MonoStackSlot *slot2 = &state_2 [i];
1923
1924                 if (slot1->type != slot2->type)
1925                         return FALSE;
1926
1927                 switch (slot1->type) {
1928                 case STACK_PTR:
1929                         /* FIXME: Perform merge ? */
1930                         /* klass == NULL means a native int */
1931                         if (slot1->klass && slot2->klass) {
1932                                 if (slot1->klass != slot2->klass)
1933                                         return FALSE;
1934                         }
1935                         break;
1936                 case STACK_MP:
1937                         /* FIXME: Change this to an assert and fix the JIT to allways fill this */
1938                         if (slot1->klass && slot2->klass) {
1939                                 if (slot1->klass != slot2->klass)
1940                                         return FALSE;
1941                         }
1942                         break;
1943                 case STACK_OBJ: {
1944                         MonoClass *klass1 = slot1->klass;
1945                         MonoClass *klass2 = slot2->klass;
1946
1947                         if (!klass1) {
1948                                 /* slot1 is ldnull */
1949                         } else if (!klass2) {
1950                                 /* slot2 is ldnull */
1951                                 slot2->klass = slot1->klass;
1952                         }
1953                         break;
1954                 }
1955                 }
1956         }
1957
1958         return TRUE;
1959 }
1960
1961 /*
1962  * This function is called to handle items that are left on the evaluation stack
1963  * at basic block boundaries. What happens is that we save the values to local variables
1964  * and we reload them later when first entering the target basic block (with the
1965  * handle_loaded_temps () function).
1966  * It is also used to handle items on the stack in store opcodes, since it is
1967  * possible that the variable to be stored into is already on the stack, in
1968  * which case its old value should be used.
1969  * A single joint point will use the same variables (stored in the array bb->out_stack or
1970  * bb->in_stack, if the basic block is before or after the joint point).
1971  * If the stack merge fails at a join point, cfg->unverifiable is set.
1972  */
1973 static int
1974 handle_stack_args (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **sp, int count) {
1975         int i, bindex;
1976         MonoBasicBlock *outb;
1977         MonoInst *inst, **locals;
1978         MonoStackSlot *stack_state;
1979         gboolean found;
1980
1981         if (!count)
1982                 return 0;
1983         if (cfg->verbose_level > 3)
1984                 g_print ("%d item(s) on exit from B%d\n", count, bb->block_num);
1985
1986         stack_state = mono_mempool_alloc (cfg->mempool, sizeof (MonoStackSlot) * count);
1987         for (i = 0; i < count; ++i) {
1988                 stack_state [i].type = sp [i]->type;
1989                 stack_state [i].klass = sp [i]->klass;
1990
1991                 /* Check that instructions other than ldnull have ins->klass set */
1992                 if (!cfg->dont_verify_stack_merge && (sp [i]->type == STACK_OBJ) && !((sp [i]->opcode == OP_PCONST) && sp [i]->inst_c0 == 0))
1993                         g_assert (sp [i]->klass);
1994         }
1995
1996         /* Perform verification and stack state merge */
1997         for (i = 0; i < bb->out_count; ++i) {
1998                 outb = bb->out_bb [i];
1999
2000                 /* exception handlers are linked, but they should not be considered for stack args */
2001                 if (outb->flags & BB_EXCEPTION_HANDLER)
2002                         continue;
2003                 if (outb->stack_state) {
2004                         gboolean verified;
2005
2006                         if (count != outb->in_scount) {
2007                                 cfg->unverifiable = TRUE;
2008                                 return 0;
2009                         }
2010                         verified = merge_stacks (cfg, stack_state, outb->stack_state, count);
2011                         if (!verified) {
2012                                 cfg->unverifiable = TRUE;
2013                                 return 0;
2014                         }
2015
2016                         if (cfg->verbose_level > 3) {
2017                                 int j;
2018
2019                                 for (j = 0; j < count; ++j)
2020                                         printf ("\tStack state of BB%d, slot %d=%d\n", outb->block_num, j, outb->stack_state [j].type);
2021                         }
2022                 } else {
2023                         /* Make a copy of the stack state */
2024                         outb->stack_state = mono_mempool_alloc (cfg->mempool, sizeof (MonoStackSlot) * count);
2025                         memcpy (outb->stack_state, stack_state, sizeof (MonoStackSlot) * count);
2026                 }
2027         }
2028
2029         if (!bb->out_scount) {
2030                 bb->out_scount = count;
2031                 //g_print ("bblock %d has out:", bb->block_num);
2032                 found = FALSE;
2033                 for (i = 0; i < bb->out_count; ++i) {
2034                         outb = bb->out_bb [i];
2035                         /* exception handlers are linked, but they should not be considered for stack args */
2036                         if (outb->flags & BB_EXCEPTION_HANDLER)
2037                                 continue;
2038                         //g_print (" %d", outb->block_num);
2039                         if (outb->in_stack) {
2040                                 found = TRUE;
2041                                 bb->out_stack = outb->in_stack;
2042                                 break;
2043                         }
2044                 }
2045                 //g_print ("\n");
2046                 if (!found) {
2047                         bb->out_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
2048                         for (i = 0; i < count; ++i) {
2049                                 /* 
2050                                  * try to reuse temps already allocated for this purpouse, if they occupy the same
2051                                  * stack slot and if they are of the same type.
2052                                  * This won't cause conflicts since if 'local' is used to 
2053                                  * store one of the values in the in_stack of a bblock, then
2054                                  * the same variable will be used for the same outgoing stack 
2055                                  * slot as well. 
2056                                  * This doesn't work when inlining methods, since the bblocks
2057                                  * in the inlined methods do not inherit their in_stack from
2058                                  * the bblock they are inlined to. See bug #58863 for an
2059                                  * example.
2060                                  * This hack is disabled since it also prevents proper tracking of types.
2061                                  */
2062 #if 1
2063                                 bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
2064 #else
2065                                 if (cfg->inlined_method)
2066                                         bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
2067                                 else
2068                                         bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
2069 #endif
2070                         }
2071                 }
2072         }
2073
2074         for (i = 0; i < bb->out_count; ++i) {
2075                 outb = bb->out_bb [i];
2076                 /* exception handlers are linked, but they should not be considered for stack args */
2077                 if (outb->flags & BB_EXCEPTION_HANDLER)
2078                         continue;
2079                 if (outb->in_scount) {
2080                         if (outb->in_scount != bb->out_scount)
2081                                 G_BREAKPOINT ();
2082                         continue; /* check they are the same locals */
2083                 }
2084                 outb->in_scount = count;
2085                 outb->in_stack = bb->out_stack;
2086         }
2087
2088         locals = bb->out_stack;
2089         for (i = 0; i < count; ++i) {
2090                 /* add store ops at the end of the bb, before the branch */
2091                 NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
2092                 /* FIXME: handle CEE_STIND_R4 */
2093                 if (inst->opcode == CEE_STOBJ) {
2094                         NEW_TEMPLOADA (cfg, inst, locals [i]->inst_c0);
2095                         handle_stobj (cfg, bb, inst, sp [i], sp [i]->cil_code, inst->klass, TRUE, FALSE, FALSE);
2096                 } else {
2097                         inst->cil_code = sp [i]->cil_code;
2098                         mono_add_ins_to_end (bb, inst);
2099                 }
2100                 if (cfg->verbose_level > 3)
2101                         g_print ("storing %d to temp %d\n", i, (int)locals [i]->inst_c0);
2102         }
2103
2104         /*
2105          * It is possible that the out bblocks already have in_stack assigned, and
2106          * the in_stacks differ. In this case, we will store to all the different 
2107          * in_stacks.
2108          */
2109
2110         found = TRUE;
2111         bindex = 0;
2112         while (found) {
2113                 /* Find a bblock which has a different in_stack */
2114                 found = FALSE;
2115                 while (bindex < bb->out_count) {
2116                         outb = bb->out_bb [bindex];
2117                         /* exception handlers are linked, but they should not be considered for stack args */
2118                         if (outb->flags & BB_EXCEPTION_HANDLER) {
2119                                 bindex++;
2120                                 continue;
2121                         }
2122                         if (outb->in_stack != locals) {
2123                                 /* 
2124                                  * Instead of storing sp [i] to locals [i], we need to store
2125                                  * locals [i] to <new locals>[i], since the sp [i] tree can't
2126                                  * be shared between trees.
2127                                  */
2128                                 for (i = 0; i < count; ++i)
2129                                         mono_add_varcopy_to_end (cfg, bb, locals [i]->inst_c0, outb->in_stack [i]->inst_c0);
2130                                 locals = outb->in_stack;
2131                                 found = TRUE;
2132                                 break;
2133                         }
2134                         bindex ++;
2135                 }
2136         }
2137         
2138         return 0;
2139 }
2140
2141 static int
2142 ret_type_to_call_opcode (MonoType *type, int calli, int virt, MonoGenericSharingContext *gsctx)
2143 {
2144         if (type->byref)
2145                 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
2146
2147 handle_enum:
2148         type = mini_get_basic_type_from_generic (gsctx, type);
2149         switch (type->type) {
2150         case MONO_TYPE_VOID:
2151                 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALLVIRT: OP_VOIDCALL;
2152         case MONO_TYPE_I1:
2153         case MONO_TYPE_U1:
2154         case MONO_TYPE_BOOLEAN:
2155         case MONO_TYPE_I2:
2156         case MONO_TYPE_U2:
2157         case MONO_TYPE_CHAR:
2158         case MONO_TYPE_I4:
2159         case MONO_TYPE_U4:
2160                 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
2161         case MONO_TYPE_I:
2162         case MONO_TYPE_U:
2163         case MONO_TYPE_PTR:
2164         case MONO_TYPE_FNPTR:
2165                 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
2166         case MONO_TYPE_CLASS:
2167         case MONO_TYPE_STRING:
2168         case MONO_TYPE_OBJECT:
2169         case MONO_TYPE_SZARRAY:
2170         case MONO_TYPE_ARRAY:    
2171                 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
2172         case MONO_TYPE_I8:
2173         case MONO_TYPE_U8:
2174                 return calli? OP_LCALL_REG: virt? OP_LCALLVIRT: OP_LCALL;
2175         case MONO_TYPE_R4:
2176         case MONO_TYPE_R8:
2177                 return calli? OP_FCALL_REG: virt? OP_FCALLVIRT: OP_FCALL;
2178         case MONO_TYPE_VALUETYPE:
2179                 if (type->data.klass->enumtype) {
2180                         type = type->data.klass->enum_basetype;
2181                         goto handle_enum;
2182                 } else
2183                         return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
2184         case MONO_TYPE_TYPEDBYREF:
2185                 return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
2186         case MONO_TYPE_GENERICINST:
2187                 type = &type->data.generic_class->container_class->byval_arg;
2188                 goto handle_enum;
2189         default:
2190                 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
2191         }
2192         return -1;
2193 }
2194
2195 void
2196 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
2197 {
2198         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
2199         MonoJumpInfoBBTable *table;
2200
2201         table = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
2202         table->table = bbs;
2203         table->table_size = num_blocks;
2204         
2205         ji->ip.label = label;
2206         ji->type = MONO_PATCH_INFO_SWITCH;
2207         ji->data.table = table;
2208         ji->next = cfg->patch_info;
2209         cfg->patch_info = ji;
2210 }
2211
2212 static void
2213 mono_save_token_info (MonoCompile *cfg, MonoImage *image, guint32 token, gpointer key)
2214 {
2215         if (cfg->compile_aot) {
2216                 MonoJumpInfoToken *jump_info_token = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoToken));
2217                 jump_info_token->image = image;
2218                 jump_info_token->token = token;
2219                 g_hash_table_insert (cfg->token_info_hash, key, jump_info_token);
2220         }
2221 }
2222
2223 /*
2224  * When we add a tree of instructions, we need to ensure the instructions currently
2225  * on the stack are executed before (like, if we load a value from a local).
2226  * We ensure this by saving the currently loaded values to temps and rewriting the
2227  * instructions to load the values.
2228  * This is not done for opcodes that terminate a basic block (because it's handled already
2229  * by handle_stack_args ()) and for opcodes that can't change values, like POP.
2230  */
2231 static void
2232 handle_loaded_temps (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst **stack, MonoInst **sp)
2233 {
2234         MonoInst *load, *store, *temp, *ins;
2235
2236         while (stack < sp) {
2237                 ins = *stack;
2238                 /* handle also other constants */
2239                 if ((ins->opcode != OP_ICONST) &&
2240                     /* temps never get written to again, so we can safely avoid duplicating them */
2241                     !(ins->ssa_op == MONO_SSA_LOAD && ins->inst_i0->opcode == OP_LOCAL && ins->inst_i0->flags & MONO_INST_IS_TEMP)) {
2242                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
2243                         temp->flags |= MONO_INST_IS_TEMP;
2244                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2245                         store->cil_code = ins->cil_code;
2246                         /* FIXME: handle CEE_STIND_R4 */
2247                         if (store->opcode == CEE_STOBJ) {
2248                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2249                                 handle_stobj (cfg, bblock, store, ins, ins->cil_code, temp->klass, FALSE, FALSE, FALSE);
2250                         } else
2251                                 MONO_ADD_INS (bblock, store);
2252                         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2253                         load->cil_code = ins->cil_code;
2254                         *stack = load;
2255                 }
2256                 stack++;
2257         }
2258 }
2259
2260 /*
2261  * target_type_is_incompatible:
2262  * @cfg: MonoCompile context
2263  *
2264  * Check that the item @arg on the evaluation stack can be stored
2265  * in the target type (can be a local, or field, etc).
2266  * The cfg arg can be used to check if we need verification or just
2267  * validity checks.
2268  *
2269  * Returns: non-0 value if arg can't be stored on a target.
2270  */
2271 static int
2272 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
2273 {
2274         MonoType *simple_type;
2275         MonoClass *klass;
2276
2277         if (target->byref) {
2278                 /* FIXME: check that the pointed to types match */
2279                 if (arg->type == STACK_MP)
2280                         return arg->klass != mono_class_from_mono_type (target);
2281                 if (arg->type == STACK_PTR)
2282                         return 0;
2283                 return 1;
2284         }
2285         simple_type = mono_type_get_underlying_type (target);
2286         switch (simple_type->type) {
2287         case MONO_TYPE_VOID:
2288                 return 1;
2289         case MONO_TYPE_I1:
2290         case MONO_TYPE_U1:
2291         case MONO_TYPE_BOOLEAN:
2292         case MONO_TYPE_I2:
2293         case MONO_TYPE_U2:
2294         case MONO_TYPE_CHAR:
2295         case MONO_TYPE_I4:
2296         case MONO_TYPE_U4:
2297                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2298                         return 1;
2299                 return 0;
2300         case MONO_TYPE_PTR:
2301                 /* STACK_MP is needed when setting pinned locals */
2302                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
2303                         return 1;
2304                 return 0;
2305         case MONO_TYPE_I:
2306         case MONO_TYPE_U:
2307         case MONO_TYPE_FNPTR:
2308                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2309                         return 1;
2310                 return 0;
2311         case MONO_TYPE_OBJECT:
2312                 if (arg->type != STACK_OBJ)
2313                         return 1;
2314                 return 0;
2315         case MONO_TYPE_STRING:
2316                 if (arg->type != STACK_OBJ)
2317                         return 1;
2318                 /* ldnull has arg->klass unset */
2319                 /*if (arg->klass && arg->klass != mono_defaults.string_class) {
2320                         G_BREAKPOINT ();
2321                         return 1;
2322                 }*/
2323                 return 0;
2324         case MONO_TYPE_CLASS:
2325         case MONO_TYPE_SZARRAY:
2326         case MONO_TYPE_ARRAY:    
2327                 if (arg->type != STACK_OBJ)
2328                         return 1;
2329                 /* FIXME: check type compatibility */
2330                 return 0;
2331         case MONO_TYPE_I8:
2332         case MONO_TYPE_U8:
2333                 if (arg->type != STACK_I8)
2334                         return 1;
2335                 return 0;
2336         case MONO_TYPE_R4:
2337         case MONO_TYPE_R8:
2338                 if (arg->type != STACK_R8)
2339                         return 1;
2340                 return 0;
2341         case MONO_TYPE_VALUETYPE:
2342                 if (arg->type != STACK_VTYPE)
2343                         return 1;
2344                 klass = mono_class_from_mono_type (simple_type);
2345                 if (klass != arg->klass)
2346                         return 1;
2347                 return 0;
2348         case MONO_TYPE_TYPEDBYREF:
2349                 if (arg->type != STACK_VTYPE)
2350                         return 1;
2351                 klass = mono_class_from_mono_type (simple_type);
2352                 if (klass != arg->klass)
2353                         return 1;
2354                 return 0;
2355         case MONO_TYPE_GENERICINST:
2356                 if (mono_type_generic_inst_is_valuetype (simple_type)) {
2357                         klass = mono_class_from_mono_type (simple_type);
2358                         if (klass->enumtype)
2359                                 return target_type_is_incompatible (cfg, klass->enum_basetype, arg);
2360                         if (arg->type != STACK_VTYPE)
2361                                 return 1;
2362                         if (klass != arg->klass)
2363                                 return 1;
2364                         return 0;
2365                 } else {
2366                         if (arg->type != STACK_OBJ)
2367                                 return 1;
2368                         /* FIXME: check type compatibility */
2369                         return 0;
2370                 }
2371         case MONO_TYPE_VAR:
2372         case MONO_TYPE_MVAR:
2373                 /* FIXME: all the arguments must be references for now,
2374                  * later look inside cfg and see if the arg num is
2375                  * really a reference
2376                  */
2377                 g_assert (cfg->generic_sharing_context);
2378                 if (arg->type != STACK_OBJ)
2379                         return 1;
2380                 return 0;
2381         default:
2382                 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
2383         }
2384         return 1;
2385 }
2386
2387 /*
2388  * Prepare arguments for passing to a function call.
2389  * Return a non-zero value if the arguments can't be passed to the given
2390  * signature.
2391  * The type checks are not yet complete and some conversions may need
2392  * casts on 32 or 64 bit architectures.
2393  *
2394  * FIXME: implement this using target_type_is_incompatible ()
2395  */
2396 static int
2397 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
2398 {
2399         MonoType *simple_type;
2400         int i;
2401
2402         if (sig->hasthis) {
2403                 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
2404                         return 1;
2405                 args++;
2406         }
2407         for (i = 0; i < sig->param_count; ++i) {
2408                 if (sig->params [i]->byref) {
2409                         if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
2410                                 return 1;
2411                         continue;
2412                 }
2413                 simple_type = sig->params [i];
2414                 simple_type = mini_get_basic_type_from_generic (cfg->generic_sharing_context, simple_type);
2415 handle_enum:
2416                 switch (simple_type->type) {
2417                 case MONO_TYPE_VOID:
2418                         return 1;
2419                         continue;
2420                 case MONO_TYPE_I1:
2421                 case MONO_TYPE_U1:
2422                 case MONO_TYPE_BOOLEAN:
2423                 case MONO_TYPE_I2:
2424                 case MONO_TYPE_U2:
2425                 case MONO_TYPE_CHAR:
2426                 case MONO_TYPE_I4:
2427                 case MONO_TYPE_U4:
2428                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2429                                 return 1;
2430                         continue;
2431                 case MONO_TYPE_I:
2432                 case MONO_TYPE_U:
2433                 case MONO_TYPE_PTR:
2434                 case MONO_TYPE_FNPTR:
2435                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2436                                 return 1;
2437                         continue;
2438                 case MONO_TYPE_CLASS:
2439                 case MONO_TYPE_STRING:
2440                 case MONO_TYPE_OBJECT:
2441                 case MONO_TYPE_SZARRAY:
2442                 case MONO_TYPE_ARRAY:    
2443                         if (args [i]->type != STACK_OBJ)
2444                                 return 1;
2445                         continue;
2446                 case MONO_TYPE_I8:
2447                 case MONO_TYPE_U8:
2448                         if (args [i]->type != STACK_I8)
2449                                 return 1;
2450                         continue;
2451                 case MONO_TYPE_R4:
2452                 case MONO_TYPE_R8:
2453                         if (args [i]->type != STACK_R8)
2454                                 return 1;
2455                         continue;
2456                 case MONO_TYPE_VALUETYPE:
2457                         if (simple_type->data.klass->enumtype) {
2458                                 simple_type = simple_type->data.klass->enum_basetype;
2459                                 goto handle_enum;
2460                         }
2461                         if (args [i]->type != STACK_VTYPE)
2462                                 return 1;
2463                         continue;
2464                 case MONO_TYPE_TYPEDBYREF:
2465                         if (args [i]->type != STACK_VTYPE)
2466                                 return 1;
2467                         continue;
2468                 case MONO_TYPE_GENERICINST:
2469                         simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2470                         goto handle_enum;
2471
2472                 default:
2473                         g_error ("unknown type 0x%02x in check_call_signature",
2474                                  simple_type->type);
2475                 }
2476         }
2477         return 0;
2478 }
2479
2480 inline static int
2481 mono_spill_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoCallInst *call, MonoMethodSignature *sig, gboolean ret_object, 
2482                  const guint8 *ip, gboolean to_end)
2483 {
2484         MonoInst *temp, *store, *ins = (MonoInst*)call;
2485         MonoType *ret = sig->ret;
2486
2487         if (!MONO_TYPE_IS_VOID (ret) || ret_object) {
2488                 if (ret_object) {
2489                         call->inst.type = STACK_OBJ;
2490                         call->inst.opcode = CEE_CALL;
2491                         temp = mono_compile_create_var (cfg, &mono_defaults.string_class->byval_arg, OP_LOCAL);
2492                 } else {
2493                         type_to_eval_stack_type (cfg, ret, ins);
2494                         temp = mono_compile_create_var (cfg, ret, OP_LOCAL);
2495                 }
2496                 
2497                 temp->flags |= MONO_INST_IS_TEMP;
2498
2499                 if (MONO_TYPE_ISSTRUCT (ret)) {
2500                         MonoInst *loada, *dummy_store;
2501
2502                         /* 
2503                          * Emit a dummy store to the local holding the result so the
2504                          * liveness info remains correct.
2505                          */
2506                         NEW_DUMMY_STORE (cfg, dummy_store, temp->inst_c0);
2507                         if (to_end)
2508                                 mono_add_ins_to_end (bblock, dummy_store);
2509                         else
2510                                 MONO_ADD_INS (bblock, dummy_store);
2511
2512                         /* we use this to allocate native sized structs */
2513                         temp->backend.is_pinvoke = sig->pinvoke;
2514
2515                         NEW_TEMPLOADA (cfg, loada, temp->inst_c0);
2516                         if (call->inst.opcode == OP_VCALL)
2517                                 ins->inst_left = loada;
2518                         else
2519                                 ins->inst_right = loada; /* a virtual or indirect call */
2520
2521                         if (to_end)
2522                                 mono_add_ins_to_end (bblock, ins);
2523                         else
2524                                 MONO_ADD_INS (bblock, ins);
2525                 } else {
2526                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2527                         store->cil_code = ip;
2528                         
2529 #ifdef MONO_ARCH_SOFT_FLOAT
2530                         if (store->opcode == CEE_STIND_R4) {
2531                                 /*FIXME implement proper support for to_end*/
2532                                 g_assert (!to_end);
2533                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2534                                 handle_store_float (cfg, bblock, store, ins, ip);
2535                         } else
2536 #endif
2537                         if (to_end)
2538                                 mono_add_ins_to_end (bblock, store);
2539                         else
2540                                 MONO_ADD_INS (bblock, store);
2541                 }
2542                 return temp->inst_c0;
2543         } else {
2544                 if (to_end)
2545                         mono_add_ins_to_end (bblock, ins);
2546                 else
2547                         MONO_ADD_INS (bblock, ins);
2548                 return -1;
2549         }
2550 }
2551
2552 inline static MonoCallInst *
2553 mono_emit_call_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
2554                      MonoInst **args, int calli, int virtual, const guint8 *ip, gboolean to_end)
2555 {
2556         MonoCallInst *call;
2557         MonoInst *arg;
2558
2559         MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (sig->ret, calli, virtual, cfg->generic_sharing_context));
2560
2561 #ifdef MONO_ARCH_SOFT_FLOAT
2562         /* we need to convert the r4 value to an int value */
2563         {
2564                 int i;
2565                 for (i = 0; i < sig->param_count; ++i) {
2566                         if (!sig->params [i]->byref && sig->params [i]->type == MONO_TYPE_R4) {
2567                                 MonoInst *iargs [1];
2568                                 int temp;
2569                                 iargs [0] = args [i + sig->hasthis];
2570
2571                                 temp = mono_emit_jit_icall (cfg, bblock, mono_fload_r4_arg, iargs, ip);
2572                                 NEW_TEMPLOAD (cfg, arg, temp);
2573                                 args [i + sig->hasthis] = arg;
2574                         }
2575                 }
2576         }
2577 #endif
2578
2579         call->inst.cil_code = ip;
2580         call->args = args;
2581         call->signature = sig;
2582         call = mono_arch_call_opcode (cfg, bblock, call, virtual);
2583         type_to_eval_stack_type (cfg, sig->ret, &call->inst);
2584
2585         for (arg = call->out_args; arg;) {
2586                 MonoInst *narg = arg->next;
2587                 arg->next = NULL;
2588                 if (!arg->cil_code)
2589                         arg->cil_code = ip;
2590                 if (to_end)
2591                         mono_add_ins_to_end (bblock, arg);
2592                 else
2593                         MONO_ADD_INS (bblock, arg);
2594                 arg = narg;
2595         }
2596         return call;
2597 }
2598
2599 inline static int
2600 mono_emit_calli (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
2601                  MonoInst **args, MonoInst *addr, const guint8 *ip)
2602 {
2603         MonoCallInst *call = mono_emit_call_args (cfg, bblock, sig, args, TRUE, FALSE, ip, FALSE);
2604
2605         call->inst.inst_i0 = addr;
2606
2607         return mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
2608 }
2609
2610 static MonoCallInst*
2611 mono_emit_method_call_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2612                        MonoInst **args, const guint8 *ip, MonoInst *this, gboolean to_end)
2613 {
2614         gboolean virtual = this != NULL;
2615         MonoCallInst *call;
2616
2617         call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, virtual, ip, to_end);
2618
2619         if (this && sig->hasthis && 
2620             (method->klass->marshalbyref || method->klass == mono_defaults.object_class) && 
2621             !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !MONO_CHECK_THIS (this)) {
2622                 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2623         } else {
2624                 call->method = method;
2625         }
2626         call->inst.flags |= MONO_INST_HAS_METHOD;
2627         call->inst.inst_left = this;
2628
2629         if (call->method->klass->flags & TYPE_ATTRIBUTE_INTERFACE)
2630                 /* Needed by the code generated in inssel.brg */
2631                 mono_get_got_var (cfg);
2632
2633         return call;
2634 }
2635
2636 static MonoCallInst*
2637 mono_emit_method_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2638                        MonoInst **args, const guint8 *ip, MonoInst *this)
2639 {
2640         return mono_emit_method_call_full (cfg, bblock, method, sig, args, ip, this, FALSE);
2641 }
2642
2643 inline static int
2644 mono_emit_method_call_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2645                        MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this)
2646 {
2647         MonoCallInst *call = mono_emit_method_call (cfg, bblock, method, signature, args, ip, this);
2648
2649         return mono_spill_call (cfg, bblock, call, signature, method->string_ctor, ip, FALSE);
2650 }
2651
2652 inline static int
2653 mono_emit_method_call_spilled_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2654                        MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this,
2655                        gboolean ret_object, gboolean to_end)
2656 {
2657         MonoCallInst *call = mono_emit_method_call_full (cfg, bblock, method, signature, args, ip, this, to_end);
2658
2659         return mono_spill_call (cfg, bblock, call, signature, ret_object, ip, to_end);
2660 }
2661
2662 inline static int
2663 mono_emit_native_call (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoMethodSignature *sig,
2664                        MonoInst **args, const guint8 *ip, gboolean ret_object, gboolean to_end)
2665 {
2666         MonoCallInst *call;
2667
2668         g_assert (sig);
2669
2670         call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, FALSE, ip, to_end);
2671         call->fptr = func;
2672
2673         return mono_spill_call (cfg, bblock, call, sig, ret_object, ip, to_end);
2674 }
2675
2676 inline static int
2677 mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip)
2678 {
2679         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2680         
2681         if (!info) {
2682                 g_warning ("unregistered JIT ICall");
2683                 g_assert_not_reached ();
2684         }
2685
2686         return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, args, ip, FALSE, FALSE);
2687 }
2688
2689 static void
2690 mono_emulate_opcode (MonoCompile *cfg, MonoInst *tree, MonoInst **iargs, MonoJitICallInfo *info)
2691 {
2692         MonoInst *ins, *temp = NULL, *store, *load, *begin;
2693         MonoInst *last_arg = NULL;
2694         int nargs;
2695         MonoCallInst *call;
2696
2697         //g_print ("emulating: ");
2698         //mono_print_tree_nl (tree);
2699         MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (info->sig->ret, FALSE, FALSE, cfg->generic_sharing_context));
2700         ins = (MonoInst*)call;
2701         
2702         call->inst.cil_code = tree->cil_code;
2703         call->args = iargs;
2704         call->signature = info->sig;
2705
2706         call = mono_arch_call_opcode (cfg, cfg->cbb, call, FALSE);
2707
2708         if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2709                 temp = mono_compile_create_var (cfg, info->sig->ret, OP_LOCAL);
2710                 temp->flags |= MONO_INST_IS_TEMP;
2711                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2712                 /* FIXME: handle CEE_STIND_R4 */
2713                 store->cil_code = tree->cil_code;
2714         } else {
2715                 store = ins;
2716         }
2717
2718         nargs = info->sig->param_count + info->sig->hasthis;
2719
2720         for (last_arg = call->out_args; last_arg && last_arg->next; last_arg = last_arg->next) ;
2721
2722         if (nargs)
2723                 last_arg->next = store;
2724
2725         if (nargs)
2726                 begin = call->out_args;
2727         else
2728                 begin = store;
2729
2730         if (cfg->prev_ins) {
2731                 /* 
2732                  * This assumes that that in a tree, emulate_opcode is called for a
2733                  * node before it is called for its children. dec_foreach needs to
2734                  * take this into account.
2735                  */
2736                 store->next = cfg->prev_ins->next;
2737                 cfg->prev_ins->next = begin;
2738         } else {
2739                 store->next = cfg->cbb->code;
2740                 cfg->cbb->code = begin;
2741         }
2742
2743         call->fptr = mono_icall_get_wrapper (info);
2744
2745         if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2746                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2747                 *tree = *load;
2748         }
2749 }
2750
2751 /*
2752  * This entry point could be used later for arbitrary method
2753  * redirection.
2754  */
2755 inline static int
2756 mini_redirect_call (int *temp, MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2757                        MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this)
2758 {
2759
2760         if (method->klass == mono_defaults.string_class) {
2761                 /* managed string allocation support */
2762                 if (strcmp (method->name, "InternalAllocateStr") == 0) {
2763                         MonoInst *iargs [2];
2764                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
2765                         MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, FALSE);
2766                         if (!managed_alloc)
2767                                 return FALSE;
2768                         NEW_VTABLECONST (cfg, iargs [0], vtable);
2769                         iargs [1] = args [0];
2770                         *temp = mono_emit_method_call_spilled (cfg, bblock, managed_alloc, mono_method_signature (managed_alloc), iargs, ip, this);
2771                         return TRUE;
2772                 }
2773         }
2774         return FALSE;
2775 }
2776
2777 static MonoMethodSignature *
2778 mono_get_array_new_va_signature (int arity)
2779 {
2780         static GHashTable *sighash = NULL;
2781         MonoMethodSignature *res;
2782         int i;
2783
2784         mono_jit_lock ();
2785         if (!sighash) {
2786                 sighash = g_hash_table_new (NULL, NULL);
2787         }
2788         else if ((res = g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
2789                 mono_jit_unlock ();
2790                 return res;
2791         }
2792
2793         res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
2794
2795         res->pinvoke = 1;
2796 #ifdef MONO_ARCH_VARARG_ICALLS
2797         /* Only set this only some archs since not all backends can handle varargs+pinvoke */
2798         res->call_convention = MONO_CALL_VARARG;
2799 #endif
2800
2801 #ifdef PLATFORM_WIN32
2802         res->call_convention = MONO_CALL_C;
2803 #endif
2804
2805         res->params [0] = &mono_defaults.int_class->byval_arg;  
2806         for (i = 0; i < arity; i++)
2807                 res->params [i + 1] = &mono_defaults.int_class->byval_arg;
2808
2809         res->ret = &mono_defaults.int_class->byval_arg;
2810
2811         g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
2812         mono_jit_unlock ();
2813
2814         return res;
2815 }
2816
2817 #ifdef MONO_ARCH_SOFT_FLOAT
2818 static void
2819 handle_store_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, MonoInst *val, const unsigned char *ip)
2820 {
2821         MonoInst *iargs [2];
2822         iargs [0] = val;
2823         iargs [1] = ptr;
2824
2825         mono_emit_jit_icall (cfg, bblock, mono_fstore_r4, iargs, ip);
2826 }
2827
2828 static int
2829 handle_load_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, const unsigned char *ip)
2830 {
2831         MonoInst *iargs [1];
2832         iargs [0] = ptr;
2833
2834         return mono_emit_jit_icall (cfg, bblock, mono_fload_r4, iargs, ip);
2835 }
2836
2837 #define LDLOC_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2838                 if (header->locals [(idx)]->type == MONO_TYPE_R4 && !header->locals [(idx)]->byref) {   \
2839                         int temp;       \
2840                         NEW_LOCLOADA (cfg, (ins), (idx));       \
2841                         temp = handle_load_float (cfg, bblock, (ins), (ip));    \
2842                         NEW_TEMPLOAD (cfg, (ins), temp);        \
2843                 }       \
2844         } while (0)
2845 #define STLOC_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2846                 if (header->locals [(idx)]->type == MONO_TYPE_R4 && !header->locals [(idx)]->byref) {   \
2847                         int temp;       \
2848                         NEW_LOCLOADA (cfg, (ins), (idx));       \
2849                         handle_store_float (cfg, bblock, (ins), *sp, (ip));     \
2850                         MONO_INST_NEW (cfg, (ins), OP_NOP);     \
2851                 }       \
2852         } while (0)
2853 #define LDARG_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2854                 if (param_types [(idx)]->type == MONO_TYPE_R4 && !param_types [(idx)]->byref) { \
2855                         int temp;       \
2856                         NEW_ARGLOADA (cfg, (ins), (idx));       \
2857                         temp = handle_load_float (cfg, bblock, (ins), (ip));    \
2858                         NEW_TEMPLOAD (cfg, (ins), temp);        \
2859                 }       \
2860         } while (0)
2861 #define STARG_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2862                 if (param_types [(idx)]->type == MONO_TYPE_R4 && !param_types [(idx)]->byref) { \
2863                         int temp;       \
2864                         NEW_ARGLOADA (cfg, (ins), (idx));       \
2865                         handle_store_float (cfg, bblock, (ins), *sp, (ip));     \
2866                         MONO_INST_NEW (cfg, (ins), OP_NOP);     \
2867                 }       \
2868         } while (0)
2869 #else
2870 #define LDLOC_SOFT_FLOAT(cfg,ins,idx,ip)
2871 #define STLOC_SOFT_FLOAT(cfg,ins,idx,ip)
2872 #define LDARG_SOFT_FLOAT(cfg,ins,idx,ip)
2873 #define STARG_SOFT_FLOAT(cfg,ins,idx,ip)
2874 #endif
2875
2876 static MonoMethod*
2877 get_memcpy_method (void)
2878 {
2879         static MonoMethod *memcpy_method = NULL;
2880         if (!memcpy_method) {
2881                 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
2882                 if (!memcpy_method)
2883                         g_error ("Old corlib found. Install a new one");
2884         }
2885         return memcpy_method;
2886 }
2887
2888 static void
2889 handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native, gboolean write_barrier) {
2890         MonoInst *iargs [3];
2891         int n;
2892         guint32 align = 0;
2893         MonoMethod *memcpy_method;
2894
2895         g_assert (klass);
2896         /*
2897          * This check breaks with spilled vars... need to handle it during verification anyway.
2898          * g_assert (klass && klass == src->klass && klass == dest->klass);
2899          */
2900
2901         if (native)
2902                 n = mono_class_native_size (klass, &align);
2903         else
2904                 n = mono_class_value_size (klass, &align);
2905
2906 #if HAVE_WRITE_BARRIERS
2907         /* if native is true there should be no references in the struct */
2908         if (write_barrier && klass->has_references && !native) {
2909                 iargs [0] = dest;
2910                 iargs [1] = src;
2911                 NEW_PCONST (cfg, iargs [2], klass);
2912
2913                 mono_emit_jit_icall (cfg, bblock, mono_value_copy, iargs, ip);
2914                 return;
2915         }
2916 #endif
2917
2918         /* FIXME: add write barrier handling */
2919         if ((cfg->opt & MONO_OPT_INTRINS) && !to_end && n <= sizeof (gpointer) * 5) {
2920                 MonoInst *inst;
2921                 if (dest->opcode == OP_LDADDR) {
2922                         /* Keep liveness info correct */
2923                         NEW_DUMMY_STORE (cfg, inst, dest->inst_i0->inst_c0);
2924                         MONO_ADD_INS (bblock, inst);
2925                 }
2926                 NEW_MEMCPY (cfg, inst, dest, src, n, align);
2927                 MONO_ADD_INS (bblock, inst);
2928                 return;
2929         }
2930         iargs [0] = dest;
2931         iargs [1] = src;
2932         NEW_ICONST (cfg, iargs [2], n);
2933
2934         memcpy_method = get_memcpy_method ();
2935         mono_emit_method_call_spilled_full (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL, FALSE, to_end);
2936 }
2937
2938 static MonoMethod*
2939 get_memset_method (void)
2940 {
2941         static MonoMethod *memset_method = NULL;
2942         if (!memset_method) {
2943                 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
2944                 if (!memset_method)
2945                         g_error ("Old corlib found. Install a new one");
2946         }
2947         return memset_method;
2948 }
2949
2950 static void
2951 handle_initobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, const guchar *ip, MonoClass *klass, MonoInst **stack_start, MonoInst **sp)
2952 {
2953         MonoInst *iargs [3];
2954         MonoInst *ins, *zero_int32;
2955         int n;
2956         guint32 align;
2957         MonoMethod *memset_method;
2958
2959         NEW_ICONST (cfg, zero_int32, 0);
2960
2961         mono_class_init (klass);
2962         n = mono_class_value_size (klass, &align);
2963         MONO_INST_NEW (cfg, ins, 0);
2964         ins->cil_code = ip;
2965         ins->inst_left = dest;
2966         ins->inst_right = zero_int32;
2967         if (n == 1) {
2968                 ins->opcode = CEE_STIND_I1;
2969                 MONO_ADD_INS (bblock, ins);
2970         } else if ((n == 2) && (align >= 2)) {
2971                 ins->opcode = CEE_STIND_I2;
2972                 MONO_ADD_INS (bblock, ins);
2973         } else if ((n == 2) && (align >= 4)) {
2974                 ins->opcode = CEE_STIND_I4;
2975                 MONO_ADD_INS (bblock, ins);
2976         } else if (n <= sizeof (gpointer) * 5) {
2977                 NEW_MEMSET (cfg, ins, dest, 0, n, align);
2978                 MONO_ADD_INS (bblock, ins);
2979         } else {
2980                 memset_method = get_memset_method ();
2981                 handle_loaded_temps (cfg, bblock, stack_start, sp);
2982                 iargs [0] = dest;
2983                 NEW_ICONST (cfg, iargs [1], 0);
2984                 NEW_ICONST (cfg, iargs [2], n);
2985                 mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
2986         }
2987 }
2988
2989 static int
2990 handle_alloc (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, gboolean for_box, const guchar *ip)
2991 {
2992         MonoInst *iargs [2];
2993         void *alloc_ftn;
2994
2995         if (cfg->opt & MONO_OPT_SHARED) {
2996                 NEW_DOMAINCONST (cfg, iargs [0]);
2997                 NEW_CLASSCONST (cfg, iargs [1], klass);
2998
2999                 alloc_ftn = mono_object_new;
3000         } else if (cfg->compile_aot && bblock->out_of_line && klass->type_token && klass->image == mono_defaults.corlib) {
3001                 /* This happens often in argument checking code, eg. throw new FooException... */
3002                 /* Avoid relocations by calling a helper function specialized to mscorlib */
3003                 NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (klass->type_token));
3004                 return mono_emit_jit_icall (cfg, bblock, mono_helper_newobj_mscorlib, iargs, ip);
3005         } else {
3006                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3007                 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, for_box);
3008                 gboolean pass_lw;
3009
3010                 if (managed_alloc) {
3011                         NEW_VTABLECONST (cfg, iargs [0], vtable);
3012                         return mono_emit_method_call_spilled (cfg, bblock, managed_alloc, mono_method_signature (managed_alloc), iargs, ip, NULL);
3013                 }
3014                 alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
3015                 if (pass_lw) {
3016                         guint32 lw = vtable->klass->instance_size;
3017                         lw = ((lw + (sizeof (gpointer) - 1)) & ~(sizeof (gpointer) - 1)) / sizeof (gpointer);
3018                         NEW_ICONST (cfg, iargs [0], lw);
3019                         NEW_VTABLECONST (cfg, iargs [1], vtable);
3020                 }
3021                 else
3022                         NEW_VTABLECONST (cfg, iargs [0], vtable);
3023         }
3024
3025         return mono_emit_jit_icall (cfg, bblock, alloc_ftn, iargs, ip);
3026 }
3027
3028 /**
3029  * Handles unbox of a Nullable<T>, returning a temp variable
3030  * where the result is stored
3031  */
3032 static int
3033 handle_unbox_nullable (MonoCompile* cfg, MonoBasicBlock* bblock, MonoInst* val, const guchar *ip, MonoClass* klass)
3034 {
3035        MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
3036        return mono_emit_method_call_spilled (cfg, bblock, method, mono_method_signature (method), &val, ip, NULL);
3037         
3038 }
3039
3040
3041
3042 static MonoInst *
3043 handle_box (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *val, const guchar *ip, MonoClass *klass)
3044 {
3045         MonoInst *dest, *vtoffset, *add, *vstore;
3046         int temp;
3047
3048        if (mono_class_is_nullable (klass)) {
3049                MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
3050                temp = mono_emit_method_call_spilled (cfg, bblock, method, mono_method_signature (method), &val, ip, NULL);
3051                NEW_TEMPLOAD (cfg, dest, temp);
3052                return dest;
3053        }
3054
3055
3056         temp = handle_alloc (cfg, bblock, klass, TRUE, ip);
3057         NEW_TEMPLOAD (cfg, dest, temp);
3058         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
3059         MONO_INST_NEW (cfg, add, OP_PADD);
3060         add->inst_left = dest;
3061         add->inst_right = vtoffset;
3062         add->cil_code = ip;
3063         add->klass = klass;
3064         MONO_INST_NEW (cfg, vstore, CEE_STIND_I);
3065         vstore->opcode = mini_type_to_stind (cfg, &klass->byval_arg);
3066         vstore->cil_code = ip;
3067         vstore->inst_left = add;
3068         vstore->inst_right = val;
3069
3070 #ifdef MONO_ARCH_SOFT_FLOAT
3071         if (vstore->opcode == CEE_STIND_R4) {
3072                 handle_store_float (cfg, bblock, add, val, ip);
3073         } else
3074 #endif
3075         if (vstore->opcode == CEE_STOBJ) {
3076                 handle_stobj (cfg, bblock, add, val, ip, klass, FALSE, FALSE, TRUE);
3077         } else
3078                 MONO_ADD_INS (bblock, vstore);
3079
3080         NEW_TEMPLOAD (cfg, dest, temp);
3081         return dest;
3082 }
3083
3084 static int
3085 handle_array_new (MonoCompile *cfg, MonoBasicBlock *bblock, int rank, MonoInst **sp, unsigned char *ip)
3086 {
3087         MonoMethodSignature *esig;
3088         char icall_name [256];
3089         char *name;
3090         MonoJitICallInfo *info;
3091
3092         /* Need to register the icall so it gets an icall wrapper */
3093         sprintf (icall_name, "ves_array_new_va_%d", rank);
3094
3095         mono_jit_lock ();
3096         info = mono_find_jit_icall_by_name (icall_name);
3097         if (info == NULL) {
3098                 esig = mono_get_array_new_va_signature (rank);
3099                 name = g_strdup (icall_name);
3100                 info = mono_register_jit_icall (mono_array_new_va, name, esig, FALSE);
3101
3102                 g_hash_table_insert (jit_icall_name_hash, name, name);
3103         }
3104         mono_jit_unlock ();
3105
3106         cfg->flags |= MONO_CFG_HAS_VARARGS;
3107
3108         /* FIXME: This uses info->sig, but it should use the signature of the wrapper */
3109         return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, sp, ip, TRUE, FALSE);
3110 }
3111
3112 static void
3113 mono_emit_load_got_addr (MonoCompile *cfg)
3114 {
3115         MonoInst *load, *store, *dummy_use;
3116         MonoInst *get_got;
3117
3118         if (!cfg->got_var || cfg->got_var_allocated)
3119                 return;
3120
3121         MONO_INST_NEW (cfg, get_got, OP_LOAD_GOTADDR);
3122         NEW_TEMPSTORE (cfg, store, cfg->got_var->inst_c0, get_got);
3123
3124         /* Add it to the start of the first bblock */
3125         if (cfg->bb_entry->code) {
3126                 store->next = cfg->bb_entry->code;
3127                 cfg->bb_entry->code = store;
3128         }
3129         else
3130                 MONO_ADD_INS (cfg->bb_entry, store);
3131
3132         cfg->got_var_allocated = TRUE;
3133
3134         /* 
3135          * Add a dummy use to keep the got_var alive, since real uses might
3136          * only be generated in the decompose or instruction selection phases.
3137          * Add it to end_bblock, so the variable's lifetime covers the whole
3138          * method.
3139          */
3140         NEW_TEMPLOAD (cfg, load, cfg->got_var->inst_c0);
3141         NEW_DUMMY_USE (cfg, dummy_use, load);
3142         MONO_ADD_INS (cfg->bb_exit, dummy_use);
3143 }
3144
3145 #define CODE_IS_STLOC(ip) (((ip) [0] >= CEE_STLOC_0 && (ip) [0] <= CEE_STLOC_3) || ((ip) [0] == CEE_STLOC_S))
3146
3147 static gboolean
3148 mini_class_is_system_array (MonoClass *klass)
3149 {
3150         if (klass->parent == mono_defaults.array_class)
3151                 return TRUE;
3152         else
3153                 return FALSE;
3154 }
3155
3156 static gboolean
3157 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
3158 {
3159         MonoMethodHeader *header = mono_method_get_header (method);
3160         MonoMethodSignature *signature = mono_method_signature (method);
3161         MonoVTable *vtable;
3162         int i;
3163
3164         if (cfg->generic_sharing_context)
3165                 return FALSE;
3166
3167 #ifdef MONO_ARCH_HAVE_LMF_OPS
3168         if (((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3169                  (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) &&
3170             !MONO_TYPE_ISSTRUCT (signature->ret) && !mini_class_is_system_array (method->klass))
3171                 return TRUE;
3172 #endif
3173
3174         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3175             (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3176             (method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
3177             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
3178             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3179             (method->klass->marshalbyref) ||
3180             !header || header->num_clauses ||
3181             /* fixme: why cant we inline valuetype returns? */
3182             MONO_TYPE_ISSTRUCT (signature->ret))
3183                 return FALSE;
3184
3185 #ifdef MONO_ARCH_SOFT_FLOAT
3186         /* this complicates things, fix later */
3187         if (signature->ret->type == MONO_TYPE_R4)
3188                 return FALSE;
3189 #endif
3190         /* its not worth to inline methods with valuetype arguments?? */
3191         for (i = 0; i < signature->param_count; i++) {
3192                 if (MONO_TYPE_ISSTRUCT (signature->params [i])) {
3193                         return FALSE;
3194                 }
3195 #ifdef MONO_ARCH_SOFT_FLOAT
3196                 /* this complicates things, fix later */
3197                 if (!signature->params [i]->byref && signature->params [i]->type == MONO_TYPE_R4)
3198                         return FALSE;
3199 #endif
3200         }
3201
3202         /*
3203          * if we can initialize the class of the method right away, we do,
3204          * otherwise we don't allow inlining if the class needs initialization,
3205          * since it would mean inserting a call to mono_runtime_class_init()
3206          * inside the inlined code
3207          */
3208         if (!(cfg->opt & MONO_OPT_SHARED)) {
3209                 vtable = mono_class_vtable (cfg->domain, method->klass);
3210                 if (method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) {
3211                         if (cfg->run_cctors) {
3212                                 /* This makes so that inline cannot trigger */
3213                                 /* .cctors: too many apps depend on them */
3214                                 /* running with a specific order... */
3215                                 if (! vtable->initialized)
3216                                         return FALSE;
3217                                 mono_runtime_class_init (vtable);
3218                         }
3219                 }
3220                 else if (!vtable->initialized && mono_class_needs_cctor_run (method->klass, NULL))
3221                         return FALSE;
3222         } else {
3223                 /* 
3224                  * If we're compiling for shared code
3225                  * the cctor will need to be run at aot method load time, for example,
3226                  * or at the end of the compilation of the inlining method.
3227                  */
3228                 if (mono_class_needs_cctor_run (method->klass, NULL) && !((method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3229                         return FALSE;
3230         }
3231         //if (!MONO_TYPE_IS_VOID (signature->ret)) return FALSE;
3232
3233         /*
3234          * CAS - do not inline methods with declarative security
3235          * Note: this has to be before any possible return TRUE;
3236          */
3237         if (mono_method_has_declsec (method))
3238                 return FALSE;
3239
3240         /* also consider num_locals? */
3241         if (getenv ("MONO_INLINELIMIT")) {
3242                 if (header->code_size < atoi (getenv ("MONO_INLINELIMIT"))) {
3243                         return TRUE;
3244                 }
3245         } else if (header->code_size < INLINE_LENGTH_LIMIT)
3246                 return TRUE;
3247
3248         return FALSE;
3249 }
3250
3251 static gboolean
3252 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoVTable *vtable)
3253 {
3254         if (vtable->initialized && !cfg->compile_aot)
3255                 return FALSE;
3256
3257         if (vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)
3258                 return FALSE;
3259
3260         if (!mono_class_needs_cctor_run (vtable->klass, method))
3261                 return FALSE;
3262
3263         if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (vtable->klass == method->klass))
3264                 /* The initialization is already done before the method is called */
3265                 return FALSE;
3266
3267         return TRUE;
3268 }
3269
3270 static MonoInst*
3271 mini_get_ldelema_ins (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
3272 {
3273         int temp, rank;
3274         MonoInst *addr;
3275         MonoMethod *addr_method;
3276         int element_size;
3277
3278         rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
3279
3280         if (rank == 1) {
3281                 MONO_INST_NEW (cfg, addr, CEE_LDELEMA);
3282                 addr->inst_left = sp [0];
3283                 addr->inst_right = sp [1];
3284                 addr->cil_code = ip;
3285                 addr->type = STACK_MP;
3286                 addr->klass = cmethod->klass->element_class;
3287                 return addr;
3288         }
3289
3290         if (rank == 2 && (cfg->opt & MONO_OPT_INTRINS)) {
3291 #if defined(MONO_ARCH_EMULATE_MUL_DIV) && !defined(MONO_ARCH_NO_EMULATE_MUL)
3292                 /* OP_LDELEMA2D depends on OP_LMUL */
3293 #else
3294                 MonoInst *indexes;
3295                 NEW_GROUP (cfg, indexes, sp [1], sp [2]);
3296                 MONO_INST_NEW (cfg, addr, OP_LDELEMA2D);
3297                 addr->inst_left = sp [0];
3298                 addr->inst_right = indexes;
3299                 addr->cil_code = ip;
3300                 addr->type = STACK_MP;
3301                 addr->klass = cmethod->klass->element_class;
3302                 return addr;
3303 #endif
3304         }
3305
3306         element_size = mono_class_array_element_size (cmethod->klass->element_class);
3307         addr_method = mono_marshal_get_array_address (rank, element_size);
3308         temp = mono_emit_method_call_spilled (cfg, bblock, addr_method, addr_method->signature, sp, ip, NULL);
3309         NEW_TEMPLOAD (cfg, addr, temp);
3310         return addr;
3311
3312 }
3313
3314 static MonoJitICallInfo **emul_opcode_map = NULL;
3315
3316 MonoJitICallInfo *
3317 mono_find_jit_opcode_emulation (int opcode)
3318 {
3319         g_assert (opcode >= 0 && opcode <= OP_LAST);
3320         if  (emul_opcode_map)
3321                 return emul_opcode_map [opcode];
3322         else
3323                 return NULL;
3324 }
3325
3326 static int
3327 is_unsigned_regsize_type (MonoType *type)
3328 {
3329         switch (type->type) {
3330         case MONO_TYPE_U1:
3331         case MONO_TYPE_U2:
3332         case MONO_TYPE_U4:
3333 #if SIZEOF_VOID_P == 8
3334         /*case MONO_TYPE_U8: this requires different opcodes in inssel.brg */
3335 #endif
3336                 return TRUE;
3337         default:
3338                 return FALSE;
3339         }
3340 }
3341
3342 static MonoInst*
3343 mini_get_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
3344 {
3345         MonoInst *ins = NULL;
3346         
3347         static MonoClass *runtime_helpers_class = NULL;
3348         if (! runtime_helpers_class)
3349                 runtime_helpers_class = mono_class_from_name (mono_defaults.corlib,
3350                         "System.Runtime.CompilerServices", "RuntimeHelpers");
3351
3352         if (cmethod->klass == mono_defaults.string_class) {
3353                 if (strcmp (cmethod->name, "get_Chars") == 0) {
3354                         MONO_INST_NEW (cfg, ins, OP_GETCHR);
3355                         ins->inst_i0 = args [0];
3356                         ins->inst_i1 = args [1];
3357                         return ins;
3358                 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3359                         MONO_INST_NEW (cfg, ins, OP_STRLEN);
3360                         ins->inst_i0 = args [0];
3361                         return ins;
3362                 } else if (strcmp (cmethod->name, "InternalSetChar") == 0) {
3363                         MonoInst *get_addr;
3364                         MONO_INST_NEW (cfg, get_addr, OP_STR_CHAR_ADDR);
3365                         get_addr->inst_i0 = args [0];
3366                         get_addr->inst_i1 = args [1];
3367                         MONO_INST_NEW (cfg, ins, CEE_STIND_I2);
3368                         ins->inst_i0 = get_addr;
3369                         ins->inst_i1 = args [2];
3370                         return ins;
3371                 } else 
3372                         return NULL;
3373         } else if (cmethod->klass == mono_defaults.object_class) {
3374                 if (strcmp (cmethod->name, "GetType") == 0) {
3375                         MONO_INST_NEW (cfg, ins, OP_GETTYPE);
3376                         ins->inst_i0 = args [0];
3377                         return ins;
3378                 /* The OP_GETHASHCODE rule depends on OP_MUL */
3379 #if !defined(MONO_ARCH_EMULATE_MUL_DIV) && !defined(HAVE_MOVING_COLLECTOR)
3380                 } else if (strcmp (cmethod->name, "InternalGetHashCode") == 0) {
3381                         MONO_INST_NEW (cfg, ins, OP_GETHASHCODE);
3382                         ins->inst_i0 = args [0];
3383                         return ins;
3384 #endif
3385                 } else if (strcmp (cmethod->name, ".ctor") == 0) {
3386                         MONO_INST_NEW (cfg, ins, OP_NOP);
3387                         return ins;
3388                 } else
3389                         return NULL;
3390         } else if (cmethod->klass == mono_defaults.array_class) {
3391                 if (cmethod->name [0] != 'g')
3392                         return NULL;
3393
3394                 if (strcmp (cmethod->name, "get_Rank") == 0) {
3395                         MONO_INST_NEW (cfg, ins, OP_ARRAY_RANK);
3396                         ins->inst_i0 = args [0];
3397                         return ins;
3398                 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3399                         MONO_INST_NEW (cfg, ins, CEE_LDLEN);
3400                         ins->inst_i0 = args [0];
3401                         return ins;
3402                 } else
3403                         return NULL;
3404         } else if (cmethod->klass == runtime_helpers_class) {
3405                 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0) {
3406                         NEW_ICONST (cfg, ins, G_STRUCT_OFFSET (MonoString, chars));
3407                         return ins;
3408                 } else
3409                         return NULL;
3410         } else if (cmethod->klass == mono_defaults.thread_class) {
3411                 if (strcmp (cmethod->name, "get_CurrentThread") == 0 && (ins = mono_arch_get_thread_intrinsic (cfg)))
3412                         return ins;
3413                 if (strcmp (cmethod->name, "MemoryBarrier") == 0) {
3414                         MONO_INST_NEW (cfg, ins, OP_MEMORY_BARRIER);
3415                         return ins;
3416                 }
3417         } else if (mini_class_is_system_array (cmethod->klass) &&
3418                         strcmp (cmethod->name, "GetGenericValueImpl") == 0) {
3419                 MonoInst *sp [2];
3420                 MonoInst *ldelem, *store, *load;
3421                 MonoClass *eklass = mono_class_from_mono_type (fsig->params [1]);
3422                 int n;
3423                 n = mini_type_to_stind (cfg, &eklass->byval_arg);
3424                 if (n == CEE_STOBJ)
3425                         return NULL;
3426                 sp [0] = args [0];
3427                 sp [1] = args [1];
3428                 NEW_LDELEMA (cfg, ldelem, sp, eklass);
3429                 ldelem->flags |= MONO_INST_NORANGECHECK;
3430                 MONO_INST_NEW (cfg, store, n);
3431                 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, &eklass->byval_arg));
3432                 type_to_eval_stack_type (cfg, &eklass->byval_arg, load);
3433                 load->inst_left = ldelem;
3434                 store->inst_left = args [2];
3435                 store->inst_right = load;
3436                 return store;
3437         } else if (cmethod->klass == mono_defaults.math_class) {
3438                 if (strcmp (cmethod->name, "Min") == 0) {
3439                         if (is_unsigned_regsize_type (fsig->params [0])) {
3440                                 MONO_INST_NEW (cfg, ins, OP_MIN);
3441                                 ins->inst_i0 = args [0];
3442                                 ins->inst_i1 = args [1];
3443                                 return ins;
3444                         }
3445                 } else if (strcmp (cmethod->name, "Max") == 0) {
3446                         if (is_unsigned_regsize_type (fsig->params [0])) {
3447                                 MONO_INST_NEW (cfg, ins, OP_MAX);
3448                                 ins->inst_i0 = args [0];
3449                                 ins->inst_i1 = args [1];
3450                                 return ins;
3451                         }
3452                 }
3453         } else if (cmethod->klass->image == mono_defaults.corlib &&
3454                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
3455                            (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
3456                 ins = NULL;
3457
3458 #if SIZEOF_VOID_P == 8
3459                 if (strcmp (cmethod->name, "Read") == 0 && (fsig->params [0]->type == MONO_TYPE_I8)) {
3460                         /* 64 bit reads are already atomic */
3461                         MONO_INST_NEW (cfg, ins, CEE_LDIND_I8);
3462                         ins->inst_i0 = args [0];
3463                 }
3464 #endif
3465
3466 #ifdef MONO_ARCH_HAVE_ATOMIC_ADD
3467                 if (strcmp (cmethod->name, "Increment") == 0) {
3468                         MonoInst *ins_iconst;
3469                         guint32 opcode;
3470
3471                         if (fsig->params [0]->type == MONO_TYPE_I4)
3472                                 opcode = OP_ATOMIC_ADD_NEW_I4;
3473                         else if (fsig->params [0]->type == MONO_TYPE_I8)
3474                                 opcode = OP_ATOMIC_ADD_NEW_I8;
3475                         else
3476                                 g_assert_not_reached ();
3477
3478 #if SIZEOF_VOID_P == 4
3479                         if (opcode == OP_ATOMIC_ADD_NEW_I8)
3480                                 return NULL;
3481 #endif
3482
3483                         MONO_INST_NEW (cfg, ins, opcode);
3484                         MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
3485                         ins_iconst->inst_c0 = 1;
3486
3487                         ins->inst_i0 = args [0];
3488                         ins->inst_i1 = ins_iconst;
3489                 } else if (strcmp (cmethod->name, "Decrement") == 0) {
3490                         MonoInst *ins_iconst;
3491                         guint32 opcode;
3492
3493                         if (fsig->params [0]->type == MONO_TYPE_I4)
3494                                 opcode = OP_ATOMIC_ADD_NEW_I4;
3495                         else if (fsig->params [0]->type == MONO_TYPE_I8)
3496                                 opcode = OP_ATOMIC_ADD_NEW_I8;
3497                         else
3498                                 g_assert_not_reached ();
3499
3500 #if SIZEOF_VOID_P == 4
3501                         if (opcode == OP_ATOMIC_ADD_NEW_I8)
3502                                 return NULL;
3503 #endif
3504
3505                         MONO_INST_NEW (cfg, ins, opcode);
3506                         MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
3507                         ins_iconst->inst_c0 = -1;
3508
3509                         ins->inst_i0 = args [0];
3510                         ins->inst_i1 = ins_iconst;
3511                 } else if (strcmp (cmethod->name, "Add") == 0) {
3512                         guint32 opcode;
3513
3514                         if (fsig->params [0]->type == MONO_TYPE_I4)
3515                                 opcode = OP_ATOMIC_ADD_NEW_I4;
3516                         else if (fsig->params [0]->type == MONO_TYPE_I8)
3517                                 opcode = OP_ATOMIC_ADD_NEW_I8;
3518                         else
3519                                 g_assert_not_reached ();
3520
3521 #if SIZEOF_VOID_P == 4
3522                         if (opcode == OP_ATOMIC_ADD_NEW_I8)
3523                                 return NULL;
3524 #endif
3525                         
3526                         MONO_INST_NEW (cfg, ins, opcode);
3527
3528                         ins->inst_i0 = args [0];
3529                         ins->inst_i1 = args [1];
3530                 }
3531 #endif /* MONO_ARCH_HAVE_ATOMIC_ADD */
3532
3533 #ifdef MONO_ARCH_HAVE_ATOMIC_EXCHANGE
3534                 if (strcmp (cmethod->name, "Exchange") == 0) {
3535                         guint32 opcode;
3536
3537                         if (fsig->params [0]->type == MONO_TYPE_I4)
3538                                 opcode = OP_ATOMIC_EXCHANGE_I4;
3539 #if SIZEOF_VOID_P == 8
3540                         else if ((fsig->params [0]->type == MONO_TYPE_I8) ||
3541                                          (fsig->params [0]->type == MONO_TYPE_I) ||
3542                                          (fsig->params [0]->type == MONO_TYPE_OBJECT))
3543                                 opcode = OP_ATOMIC_EXCHANGE_I8;
3544 #else
3545                         else if ((fsig->params [0]->type == MONO_TYPE_I) ||
3546                                          (fsig->params [0]->type == MONO_TYPE_OBJECT))
3547                                 opcode = OP_ATOMIC_EXCHANGE_I4;
3548 #endif
3549                         else
3550                                 return NULL;
3551
3552 #if SIZEOF_VOID_P == 4
3553                         if (opcode == OP_ATOMIC_EXCHANGE_I8)
3554                                 return NULL;
3555 #endif
3556
3557                         MONO_INST_NEW (cfg, ins, opcode);
3558
3559                         ins->inst_i0 = args [0];
3560                         ins->inst_i1 = args [1];
3561                 }
3562 #endif /* MONO_ARCH_HAVE_ATOMIC_EXCHANGE */
3563
3564                 if (ins)
3565                         return ins;
3566         } else if (cmethod->klass->image == mono_defaults.corlib) {
3567                 if (cmethod->name [0] == 'B' && strcmp (cmethod->name, "Break") == 0
3568                                 && strcmp (cmethod->klass->name, "Debugger") == 0) {
3569                         MONO_INST_NEW (cfg, ins, OP_BREAK);
3570                         return ins;
3571                 }
3572                 if (cmethod->name [0] == 'g' && strcmp (cmethod->name, "get_IsRunningOnWindows") == 0
3573                                 && strcmp (cmethod->klass->name, "Environment") == 0) {
3574 #ifdef PLATFORM_WIN32
3575                         NEW_ICONST (cfg, ins, 1);
3576 #else
3577                         NEW_ICONST (cfg, ins, 0);
3578 #endif
3579                         return ins;
3580                 }
3581         }
3582
3583         return mono_arch_get_inst_for_method (cfg, cmethod, fsig, args);
3584 }
3585
3586 static void
3587 mono_save_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, MonoInst **sp, MonoInst **args)
3588 {
3589         MonoInst *store, *temp;
3590         int i;
3591
3592         g_assert (!MONO_TYPE_ISSTRUCT (sig->ret));
3593
3594         if (!sig->hasthis && sig->param_count == 0) 
3595                 return;
3596
3597         if (sig->hasthis) {
3598                 if (sp [0]->opcode == OP_ICONST) {
3599                         *args++ = sp [0];
3600                 } else {
3601                         temp = mono_compile_create_var (cfg, type_from_stack_type (*sp), OP_LOCAL);
3602                         *args++ = temp;
3603                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3604                         /* FIXME: handle CEE_STIND_R4 */
3605                         store->cil_code = sp [0]->cil_code;
3606                         MONO_ADD_INS (bblock, store);
3607                 }
3608                 sp++;
3609         }
3610
3611         for (i = 0; i < sig->param_count; ++i) {
3612                 if (sp [0]->opcode == OP_ICONST) {
3613                         *args++ = sp [0];
3614                 } else {
3615                         temp = mono_compile_create_var (cfg, sig->params [i], OP_LOCAL);
3616                         *args++ = temp;
3617                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3618                         store->cil_code = sp [0]->cil_code;
3619                         /* FIXME: handle CEE_STIND_R4 */
3620                         if (store->opcode == CEE_STOBJ) {
3621                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
3622                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, temp->klass, FALSE, FALSE, FALSE);
3623                         } else {
3624                                 MONO_ADD_INS (bblock, store);
3625                         } 
3626                 }
3627                 sp++;
3628         }
3629 }
3630 #define MONO_INLINE_CALLED_LIMITED_METHODS 0
3631 #define MONO_INLINE_CALLER_LIMITED_METHODS 0
3632
3633 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
3634 static char*
3635 mono_inline_called_method_name_limit = NULL;
3636 static gboolean check_inline_called_method_name_limit (MonoMethod *called_method) {
3637         char *called_method_name = mono_method_full_name (called_method, TRUE);
3638         int strncmp_result;
3639         
3640         if (mono_inline_called_method_name_limit == NULL) {
3641                 char *limit_string = getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
3642                 if (limit_string != NULL) {
3643                         mono_inline_called_method_name_limit = limit_string;
3644                 } else {
3645                         mono_inline_called_method_name_limit = (char *) "";
3646                 }
3647         }
3648         
3649         strncmp_result = strncmp (called_method_name, mono_inline_called_method_name_limit, strlen (mono_inline_called_method_name_limit));
3650         g_free (called_method_name);
3651         
3652         //return (strncmp_result <= 0);
3653         return (strncmp_result == 0);
3654 }
3655 #endif
3656
3657 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
3658 static char*
3659 mono_inline_caller_method_name_limit = NULL;
3660 static gboolean check_inline_caller_method_name_limit (MonoMethod *caller_method) {
3661         char *caller_method_name = mono_method_full_name (caller_method, TRUE);
3662         int strncmp_result;
3663         
3664         if (mono_inline_caller_method_name_limit == NULL) {
3665                 char *limit_string = getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
3666                 if (limit_string != NULL) {
3667                         mono_inline_caller_method_name_limit = limit_string;
3668                 } else {
3669                         mono_inline_caller_method_name_limit = (char *) "";
3670                 }
3671         }
3672         
3673         strncmp_result = strncmp (caller_method_name, mono_inline_caller_method_name_limit, strlen (mono_inline_caller_method_name_limit));
3674         g_free (caller_method_name);
3675         
3676         //return (strncmp_result <= 0);
3677         return (strncmp_result == 0);
3678 }
3679 #endif
3680
3681 static int
3682 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoBasicBlock *bblock, MonoInst **sp,
3683                 guchar *ip, guint real_offset, GList *dont_inline, MonoBasicBlock **last_b, gboolean inline_allways)
3684 {
3685         MonoInst *ins, *rvar = NULL;
3686         MonoMethodHeader *cheader;
3687         MonoBasicBlock *ebblock, *sbblock;
3688         int i, costs, new_locals_offset;
3689         MonoMethod *prev_inlined_method;
3690         MonoBasicBlock **prev_cil_offset_to_bb;
3691         unsigned char* prev_cil_start;
3692         guint32 prev_cil_offset_to_bb_len;
3693
3694         g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
3695
3696 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
3697         if ((! inline_allways) && ! check_inline_called_method_name_limit (cmethod))
3698                 return 0;
3699 #endif
3700 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
3701         if ((! inline_allways) && ! check_inline_caller_method_name_limit (cfg->method))
3702                 return 0;
3703 #endif
3704
3705         if (bblock->out_of_line && !inline_allways)
3706                 return 0;
3707
3708         if (cfg->verbose_level > 2)
3709                 g_print ("INLINE START %p %s -> %s\n", cmethod,  mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
3710
3711         if (!cmethod->inline_info) {
3712                 mono_jit_stats.inlineable_methods++;
3713                 cmethod->inline_info = 1;
3714         }
3715         /* allocate space to store the return value */
3716         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
3717                 rvar =  mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
3718         }
3719
3720         /* allocate local variables */
3721         cheader = mono_method_get_header (cmethod);
3722         new_locals_offset = cfg->num_varinfo;
3723         for (i = 0; i < cheader->num_locals; ++i)
3724                 mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
3725
3726         /* allocate starte and end blocks */
3727         sbblock = NEW_BBLOCK (cfg);
3728         sbblock->block_num = cfg->num_bblocks++;
3729         sbblock->real_offset = real_offset;
3730
3731         ebblock = NEW_BBLOCK (cfg);
3732         ebblock->block_num = cfg->num_bblocks++;
3733         ebblock->real_offset = real_offset;
3734
3735         prev_inlined_method = cfg->inlined_method;
3736         cfg->inlined_method = cmethod;
3737         prev_cil_offset_to_bb = cfg->cil_offset_to_bb;
3738         prev_cil_offset_to_bb_len = cfg->cil_offset_to_bb_len;
3739         prev_cil_start = cfg->cil_start;
3740
3741         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, new_locals_offset, rvar, dont_inline, sp, real_offset, *ip == CEE_CALLVIRT);
3742
3743         cfg->inlined_method = prev_inlined_method;
3744         cfg->cil_offset_to_bb = prev_cil_offset_to_bb;
3745         cfg->cil_offset_to_bb_len = prev_cil_offset_to_bb_len;
3746         cfg->cil_start = prev_cil_start;
3747
3748         if ((costs >= 0 && costs < 60) || inline_allways) {
3749                 if (cfg->verbose_level > 2)
3750                         g_print ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
3751                 
3752                 mono_jit_stats.inlined_methods++;
3753
3754                 /* always add some code to avoid block split failures */
3755                 MONO_INST_NEW (cfg, ins, OP_NOP);
3756                 MONO_ADD_INS (bblock, ins);
3757                 ins->cil_code = ip;
3758
3759                 bblock->next_bb = sbblock;
3760                 link_bblock (cfg, bblock, sbblock);
3761
3762                 if (rvar) {
3763                         NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
3764                         *sp++ = ins;
3765                 }
3766                 *last_b = ebblock;
3767                 return costs + 1;
3768         } else {
3769                 if (cfg->verbose_level > 2)
3770                         g_print ("INLINE ABORTED %s\n", mono_method_full_name (cmethod, TRUE));
3771                 cfg->exception_type = MONO_EXCEPTION_NONE;
3772         }
3773         return 0;
3774 }
3775
3776 /*
3777  * Some of these comments may well be out-of-date.
3778  * Design decisions: we do a single pass over the IL code (and we do bblock 
3779  * splitting/merging in the few cases when it's required: a back jump to an IL
3780  * address that was not already seen as bblock starting point).
3781  * Code is validated as we go (full verification is still better left to metadata/verify.c).
3782  * Complex operations are decomposed in simpler ones right away. We need to let the 
3783  * arch-specific code peek and poke inside this process somehow (except when the 
3784  * optimizations can take advantage of the full semantic info of coarse opcodes).
3785  * All the opcodes of the form opcode.s are 'normalized' to opcode.
3786  * MonoInst->opcode initially is the IL opcode or some simplification of that 
3787  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
3788  * opcode with value bigger than OP_LAST.
3789  * At this point the IR can be handed over to an interpreter, a dumb code generator
3790  * or to the optimizing code generator that will translate it to SSA form.
3791  *
3792  * Profiling directed optimizations.
3793  * We may compile by default with few or no optimizations and instrument the code
3794  * or the user may indicate what methods to optimize the most either in a config file
3795  * or through repeated runs where the compiler applies offline the optimizations to 
3796  * each method and then decides if it was worth it.
3797  *
3798  */
3799
3800 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
3801 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
3802 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
3803 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
3804 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
3805 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
3806 #define CHECK_UNVERIFIABLE(cfg) if (cfg->unverifiable) UNVERIFIED
3807 #define CHECK_TYPELOAD(klass) if (!(klass) || (klass)->exception_type) {cfg->exception_ptr = klass; goto load_error;}
3808
3809 /* offset from br.s -> br like opcodes */
3810 #define BIG_BRANCH_OFFSET 13
3811
3812 static inline gboolean
3813 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
3814 {
3815         MonoBasicBlock *b = cfg->cil_offset_to_bb [ip - cfg->cil_start];
3816         
3817         return b == NULL || b == bb;
3818 }
3819
3820 static int
3821 get_basic_blocks (MonoCompile *cfg, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
3822 {
3823         unsigned char *ip = start;
3824         unsigned char *target;
3825         int i;
3826         guint cli_addr;
3827         MonoBasicBlock *bblock;
3828         const MonoOpcode *opcode;
3829
3830         while (ip < end) {
3831                 cli_addr = ip - start;
3832                 i = mono_opcode_value ((const guint8 **)&ip, end);
3833                 if (i < 0)
3834                         UNVERIFIED;
3835                 opcode = &mono_opcodes [i];
3836                 switch (opcode->argument) {
3837                 case MonoInlineNone:
3838                         ip++; 
3839                         break;
3840                 case MonoInlineString:
3841                 case MonoInlineType:
3842                 case MonoInlineField:
3843                 case MonoInlineMethod:
3844                 case MonoInlineTok:
3845                 case MonoInlineSig:
3846                 case MonoShortInlineR:
3847                 case MonoInlineI:
3848                         ip += 5;
3849                         break;
3850                 case MonoInlineVar:
3851                         ip += 3;
3852                         break;
3853                 case MonoShortInlineVar:
3854                 case MonoShortInlineI:
3855                         ip += 2;
3856                         break;
3857                 case MonoShortInlineBrTarget:
3858                         target = start + cli_addr + 2 + (signed char)ip [1];
3859                         GET_BBLOCK (cfg, bblock, target);
3860                         ip += 2;
3861                         if (ip < end)
3862                                 GET_BBLOCK (cfg, bblock, ip);
3863                         break;
3864                 case MonoInlineBrTarget:
3865                         target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
3866                         GET_BBLOCK (cfg, bblock, target);
3867                         ip += 5;
3868                         if (ip < end)
3869                                 GET_BBLOCK (cfg, bblock, ip);
3870                         break;
3871                 case MonoInlineSwitch: {
3872                         guint32 n = read32 (ip + 1);
3873                         guint32 j;
3874                         ip += 5;
3875                         cli_addr += 5 + 4 * n;
3876                         target = start + cli_addr;
3877                         GET_BBLOCK (cfg, bblock, target);
3878                         
3879                         for (j = 0; j < n; ++j) {
3880                                 target = start + cli_addr + (gint32)read32 (ip);
3881                                 GET_BBLOCK (cfg, bblock, target);
3882                                 ip += 4;
3883                         }
3884                         break;
3885                 }
3886                 case MonoInlineR:
3887                 case MonoInlineI8:
3888                         ip += 9;
3889                         break;
3890                 default:
3891                         g_assert_not_reached ();
3892                 }
3893
3894                 if (i == CEE_THROW) {
3895                         unsigned char *bb_start = ip - 1;
3896                         
3897                         /* Find the start of the bblock containing the throw */
3898                         bblock = NULL;
3899                         while ((bb_start >= start) && !bblock) {
3900                                 bblock = cfg->cil_offset_to_bb [(bb_start) - start];
3901                                 bb_start --;
3902                         }
3903                         if (bblock)
3904                                 bblock->out_of_line = 1;
3905                 }
3906         }
3907         return 0;
3908 unverified:
3909         *pos = ip;
3910         return 1;
3911 }
3912
3913 static MonoInst*
3914 emit_tree (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ins, const guint8* ip_next)
3915 {
3916         MonoInst *store, *temp, *load;
3917         
3918         if (ip_in_bb (cfg, bblock, ip_next) &&
3919                 (CODE_IS_STLOC (ip_next) || *ip_next == CEE_RET))
3920                         return ins;
3921         
3922         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
3923         temp->flags |= MONO_INST_IS_TEMP;
3924         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
3925         /* FIXME: handle CEE_STIND_R4 */
3926         store->cil_code = ins->cil_code;
3927         MONO_ADD_INS (bblock, store);
3928         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
3929         load->cil_code = ins->cil_code;
3930         return load;
3931 }
3932
3933 static inline MonoMethod *
3934 mini_get_method (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
3935 {
3936         MonoMethod *method;
3937
3938         if (m->wrapper_type != MONO_WRAPPER_NONE)
3939                 return mono_method_get_wrapper_data (m, token);
3940
3941         method = mono_get_method_full (m->klass->image, token, klass, context);
3942
3943         return method;
3944 }
3945
3946 static inline MonoClass*
3947 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
3948 {
3949         MonoClass *klass;
3950
3951         if (method->wrapper_type != MONO_WRAPPER_NONE)
3952                 klass = mono_method_get_wrapper_data (method, token);
3953         else
3954                 klass = mono_class_get_full (method->klass->image, token, context);
3955         if (klass)
3956                 mono_class_init (klass);
3957         return klass;
3958 }
3959
3960 /*
3961  * Returns TRUE if the JIT should abort inlining because "callee"
3962  * is influenced by security attributes.
3963  */
3964 static
3965 gboolean check_linkdemand (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee, MonoBasicBlock *bblock, unsigned char *ip)
3966 {
3967         guint32 result;
3968         
3969         if ((cfg->method != caller) && mono_method_has_declsec (callee)) {
3970                 return TRUE;
3971         }
3972         
3973         result = mono_declsec_linkdemand (cfg->domain, caller, callee);
3974         if (result == MONO_JIT_SECURITY_OK)
3975                 return FALSE;
3976
3977         if (result == MONO_JIT_LINKDEMAND_ECMA) {
3978                 /* Generate code to throw a SecurityException before the actual call/link */
3979                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
3980                 MonoInst *args [2];
3981
3982                 NEW_ICONST (cfg, args [0], 4);
3983                 NEW_METHODCONST (cfg, args [1], caller);
3984                 mono_emit_method_call_spilled (cfg, bblock, secman->linkdemandsecurityexception, mono_method_signature (secman->linkdemandsecurityexception), args, ip, NULL);
3985         } else if (cfg->exception_type == MONO_EXCEPTION_NONE) {
3986                  /* don't hide previous results */
3987                 cfg->exception_type = MONO_EXCEPTION_SECURITY_LINKDEMAND;
3988                 cfg->exception_data = result;
3989                 return TRUE;
3990         }
3991         
3992         return FALSE;
3993 }
3994
3995 static MonoMethod*
3996 method_access_exception (void)
3997 {
3998         static MonoMethod *method = NULL;
3999
4000         if (!method) {
4001                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4002                 method = mono_class_get_method_from_name (secman->securitymanager,
4003                                                           "MethodAccessException", 2);
4004         }
4005         g_assert (method);
4006         return method;
4007 }
4008
4009 static void
4010 emit_throw_method_access_exception (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee,
4011                                     MonoBasicBlock *bblock, unsigned char *ip)
4012 {
4013         MonoMethod *thrower = method_access_exception ();
4014         MonoInst *args [2];
4015
4016         NEW_METHODCONST (cfg, args [0], caller);
4017         NEW_METHODCONST (cfg, args [1], callee);
4018         mono_emit_method_call_spilled (cfg, bblock, thrower,
4019                 mono_method_signature (thrower), args, ip, NULL);
4020 }
4021
4022 static MonoMethod*
4023 verification_exception (void)
4024 {
4025         static MonoMethod *method = NULL;
4026
4027         if (!method) {
4028                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4029                 method = mono_class_get_method_from_name (secman->securitymanager,
4030                                                           "VerificationException", 0);
4031         }
4032         g_assert (method);
4033         return method;
4034 }
4035
4036 static void
4037 emit_throw_verification_exception (MonoCompile *cfg, MonoBasicBlock *bblock, unsigned char *ip)
4038 {
4039         MonoMethod *thrower = verification_exception ();
4040
4041         mono_emit_method_call_spilled (cfg, bblock, thrower,
4042                 mono_method_signature (thrower),
4043                 NULL, ip, NULL);
4044 }
4045
4046 static void
4047 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee,
4048                                          MonoBasicBlock *bblock, unsigned char *ip)
4049 {
4050         MonoSecurityCoreCLRLevel caller_level = mono_security_core_clr_method_level (caller, TRUE);
4051         MonoSecurityCoreCLRLevel callee_level = mono_security_core_clr_method_level (callee, TRUE);
4052         gboolean is_safe = TRUE;
4053
4054         if (!(caller_level >= callee_level ||
4055                         caller_level == MONO_SECURITY_CORE_CLR_SAFE_CRITICAL ||
4056                         callee_level == MONO_SECURITY_CORE_CLR_SAFE_CRITICAL)) {
4057                 is_safe = FALSE;
4058         }
4059
4060         if (!is_safe)
4061                 emit_throw_method_access_exception (cfg, caller, callee, bblock, ip);
4062 }
4063
4064 static gboolean
4065 method_is_safe (MonoMethod *method)
4066 {
4067         /*
4068         if (strcmp (method->name, "unsafeMethod") == 0)
4069                 return FALSE;
4070         */
4071         return TRUE;
4072 }
4073
4074 /*
4075  * Check that the IL instructions at ip are the array initialization
4076  * sequence and return the pointer to the data and the size.
4077  */
4078 static const char*
4079 initialize_array_data (MonoMethod *method, gboolean aot, unsigned char *ip, MonoInst *newarr, int *out_size)
4080 {
4081         /*
4082          * newarr[System.Int32]
4083          * dup
4084          * ldtoken field valuetype ...
4085          * call void class [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
4086          */
4087         if (ip [0] == CEE_DUP && ip [1] == CEE_LDTOKEN && ip [5] == 0x4 && ip [6] == CEE_CALL) {
4088                 MonoClass *klass = newarr->inst_newa_class;
4089                 guint32 field_token = read32 (ip + 2);
4090                 guint32 field_index = field_token & 0xffffff;
4091                 guint32 token = read32 (ip + 7);
4092                 guint32 rva;
4093                 const char *data_ptr;
4094                 int size = 0;
4095                 MonoMethod *cmethod;
4096                 MonoClass *dummy_class;
4097                 MonoClassField *field = mono_field_from_token (method->klass->image, field_token, &dummy_class, NULL);
4098                 int dummy_align;
4099
4100                 if (!field)
4101                         return NULL;
4102
4103                 if (newarr->inst_newa_len->opcode != OP_ICONST)
4104                         return NULL;
4105                 cmethod = mini_get_method (method, token, NULL, NULL);
4106                 if (!cmethod)
4107                         return NULL;
4108                 if (strcmp (cmethod->name, "InitializeArray") || strcmp (cmethod->klass->name, "RuntimeHelpers") || cmethod->klass->image != mono_defaults.corlib)
4109                         return NULL;
4110                 switch (mono_type_get_underlying_type (&klass->byval_arg)->type) {
4111                 case MONO_TYPE_BOOLEAN:
4112                 case MONO_TYPE_I1:
4113                 case MONO_TYPE_U1:
4114                         size = 1; break;
4115                 /* we need to swap on big endian, so punt. Should we handle R4 and R8 as well? */
4116 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
4117                 case MONO_TYPE_CHAR:
4118                 case MONO_TYPE_I2:
4119                 case MONO_TYPE_U2:
4120                         size = 2; break;
4121                 case MONO_TYPE_I4:
4122                 case MONO_TYPE_U4:
4123                 case MONO_TYPE_R4:
4124                         size = 4; break;
4125                 case MONO_TYPE_R8:
4126 #ifdef ARM_FPU_FPA
4127                         return NULL; /* stupid ARM FP swapped format */
4128 #endif
4129                 case MONO_TYPE_I8:
4130                 case MONO_TYPE_U8:
4131                         size = 8; break;
4132 #endif
4133                 default:
4134                         return NULL;
4135                 }
4136                 size *= newarr->inst_newa_len->inst_c0;
4137                 if (size > mono_type_size (field->type, &dummy_align))
4138                     return NULL;
4139                 *out_size = size;
4140                 /*g_print ("optimized in %s: size: %d, numelems: %d\n", method->name, size, newarr->inst_newa_len->inst_c0);*/
4141                 field_index = read32 (ip + 2) & 0xffffff;
4142                 mono_metadata_field_info (method->klass->image, field_index - 1, NULL, &rva, NULL);
4143                 data_ptr = mono_image_rva_map (method->klass->image, rva);
4144                 /*g_print ("field: 0x%08x, rva: %d, rva_ptr: %p\n", read32 (ip + 2), rva, data_ptr);*/
4145                 /* for aot code we do the lookup on load */
4146                 if (aot && data_ptr)
4147                         return GUINT_TO_POINTER (rva);
4148                 return data_ptr;
4149         }
4150         return NULL;
4151 }
4152
4153 static void
4154 set_exception_type_from_invalid_il (MonoCompile *cfg, MonoMethod *method, unsigned char *ip)
4155 {
4156         char *method_fname = mono_method_full_name (method, TRUE);
4157         char *method_code = mono_disasm_code_one (NULL, method, ip, NULL);
4158         cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
4159         cfg->exception_message = g_strdup_printf ("Invalid IL code in %s: %s\n", method_fname, method_code);
4160         g_free (method_fname);
4161         g_free (method_code);
4162 }
4163
4164 /*
4165  * Generates this->vtable->runtime_generic_context
4166  */
4167 static MonoInst*
4168 get_runtime_generic_context_from_this (MonoCompile *cfg, MonoInst *this, unsigned char *ip)
4169 {
4170         MonoInst *vtable, *rgc_ptr_addr, *rgc_ptr_offset, *rgc_ptr;
4171
4172         MONO_INST_NEW (cfg, vtable, CEE_LDIND_I);
4173         vtable->cil_code = ip;
4174         vtable->inst_left = this;
4175         vtable->type = STACK_PTR;
4176
4177         NEW_ICONST (cfg, rgc_ptr_offset, G_STRUCT_OFFSET (MonoVTable, runtime_generic_context));
4178
4179         MONO_INST_NEW (cfg, rgc_ptr_addr, OP_PADD);
4180         rgc_ptr_addr->cil_code = ip;
4181         rgc_ptr_addr->inst_left = vtable;
4182         rgc_ptr_addr->inst_right = rgc_ptr_offset;
4183         rgc_ptr_addr->type = STACK_PTR;
4184
4185         MONO_INST_NEW (cfg, rgc_ptr, CEE_LDIND_I);
4186         rgc_ptr->cil_code = ip;
4187         rgc_ptr->inst_left = rgc_ptr_addr;
4188         rgc_ptr->type = STACK_PTR;
4189
4190         return rgc_ptr;
4191 }
4192
4193 static MonoInst*
4194 get_runtime_generic_context_field_from_offset (MonoCompile *cfg, MonoInst *rgc_ptr, int offset, unsigned char *ip)
4195 {
4196         MonoInst *field_offset, *field_addr, *field;
4197
4198         NEW_ICONST (cfg, field_offset, offset);
4199
4200         MONO_INST_NEW (cfg, field_addr, OP_PADD);
4201         field_addr->cil_code = ip;
4202         field_addr->inst_left = rgc_ptr;
4203         field_addr->inst_right = field_offset;
4204         field_addr->type = STACK_PTR;
4205
4206         MONO_INST_NEW (cfg, field, CEE_LDIND_I);
4207         field->cil_code = ip;
4208         field->inst_left = field_addr;
4209         field->type = STACK_PTR;
4210
4211         return field;
4212 }
4213
4214 /*
4215  * Generates ((MonoRuntimeGenericSuperInfo*)rgc)[-depth].XXX where XXX
4216  * is specified by rgctx_type.
4217  */
4218 static MonoInst*
4219 get_runtime_generic_context_super_ptr (MonoCompile *cfg, MonoInst *rgc_ptr, int depth, int rgctx_type, unsigned char *ip)
4220 {
4221         int field_offset_const;
4222
4223         g_assert (depth >= 1);
4224
4225         switch (rgctx_type) {
4226         case MINI_RGCTX_STATIC_DATA :
4227                 field_offset_const = G_STRUCT_OFFSET (MonoRuntimeGenericSuperInfo, static_data);
4228                 break;
4229         case MINI_RGCTX_KLASS :
4230                 field_offset_const = G_STRUCT_OFFSET (MonoRuntimeGenericSuperInfo, klass);
4231                 break;
4232         case MINI_RGCTX_VTABLE:
4233                 field_offset_const = G_STRUCT_OFFSET (MonoRuntimeGenericSuperInfo, vtable);
4234                 break;
4235         default :
4236                 g_assert_not_reached ();
4237         }
4238
4239         return get_runtime_generic_context_field_from_offset (cfg, rgc_ptr,
4240                 -depth * sizeof (MonoRuntimeGenericSuperInfo) + field_offset_const, ip);
4241 }
4242
4243 /*
4244  * Generic rgc->arg_infos [arg_num].XXX where XXX is specified by
4245  * rgctx_type;
4246  */
4247 static MonoInst*
4248 get_runtime_generic_context_arg_ptr (MonoCompile *cfg, MonoInst *rgc_ptr, int arg_num, int rgctx_type, unsigned char *ip)
4249 {
4250         int arg_info_offset, arg_info_field_offset;
4251
4252         g_assert (arg_num >= 0);
4253
4254         arg_info_offset = G_STRUCT_OFFSET (MonoRuntimeGenericContext, arg_infos) +
4255                 arg_num * sizeof (MonoRuntimeGenericArgInfo);
4256
4257         switch (rgctx_type) {
4258         case MINI_RGCTX_STATIC_DATA :
4259                 arg_info_field_offset = G_STRUCT_OFFSET (MonoRuntimeGenericArgInfo, static_data);
4260                 break;
4261         case MINI_RGCTX_KLASS:
4262                 arg_info_field_offset = G_STRUCT_OFFSET (MonoRuntimeGenericArgInfo, klass);
4263                 break;
4264         case MINI_RGCTX_VTABLE :
4265                 arg_info_field_offset = G_STRUCT_OFFSET (MonoRuntimeGenericArgInfo, vtable);
4266                 break;
4267         default:
4268                 g_assert_not_reached ();
4269         }
4270
4271         return get_runtime_generic_context_field_from_offset (cfg, rgc_ptr, arg_info_offset + arg_info_field_offset, ip);
4272 }
4273
4274 static MonoInst*
4275 get_runtime_generic_context_other_ptr (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *bblock,
4276         MonoInst *rgc_ptr, guint32 token, int rgctx_type, unsigned char *ip)
4277 {
4278         MonoInst *args [4];
4279         int temp;
4280         MonoInst *result;
4281
4282         g_assert (method->wrapper_type == MONO_WRAPPER_NONE);
4283
4284         NEW_CLASSCONST (cfg, args [0], method->klass);
4285         args [1] = rgc_ptr;
4286         NEW_ICONST (cfg, args [2], token);
4287         NEW_ICONST (cfg, args [3], rgctx_type);
4288
4289         temp = mono_emit_jit_icall (cfg, bblock, mono_helper_get_rgctx_other_ptr, args, ip);
4290         NEW_TEMPLOAD (cfg, result, temp);
4291
4292         return result;
4293 }
4294
4295 static MonoInst*
4296 get_runtime_generic_context_ptr (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *bblock,
4297         MonoClass *klass, guint32 type_token, MonoGenericContext *generic_context, MonoInst *rgctx,
4298         int rgctx_type, unsigned char *ip)
4299 {
4300         int arg_num = -1;
4301         int relation = mono_class_generic_class_relation (klass, method->klass, generic_context, &arg_num);
4302
4303         switch (relation) {
4304         case MINI_GENERIC_CLASS_RELATION_SELF: {
4305                 int depth = klass->idepth;
4306                 return get_runtime_generic_context_super_ptr (cfg, rgctx, depth, rgctx_type, ip);
4307         }
4308         case MINI_GENERIC_CLASS_RELATION_ARGUMENT:
4309                 return get_runtime_generic_context_arg_ptr (cfg, rgctx, arg_num, rgctx_type, ip);
4310         case MINI_GENERIC_CLASS_RELATION_OTHER:
4311                 return get_runtime_generic_context_other_ptr (cfg, method, bblock, rgctx, type_token, rgctx_type, ip);
4312         default:
4313                 g_assert_not_reached ();
4314         }
4315 }
4316
4317 /*
4318  * mono_method_to_ir: translates IL into basic blocks containing trees
4319  */
4320 static int
4321 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
4322                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
4323                    guint inline_offset, gboolean is_virtual_call)
4324 {
4325         MonoInst *zero_int32, *zero_int64, *zero_ptr, *zero_obj, *zero_r8;
4326         MonoInst *ins, **sp, **stack_start;
4327         MonoBasicBlock *bblock, *tblock = NULL, *init_localsbb = NULL;
4328         MonoMethod *cmethod;
4329         MonoInst **arg_array;
4330         MonoMethodHeader *header;
4331         MonoImage *image;
4332         guint32 token, ins_flag;
4333         MonoClass *klass;
4334         MonoClass *constrained_call = NULL;
4335         unsigned char *ip, *end, *target, *err_pos;
4336         static double r8_0 = 0.0;
4337         MonoMethodSignature *sig;
4338         MonoGenericContext *generic_context = NULL;
4339         MonoGenericContainer *generic_container = NULL;
4340         MonoType **param_types;
4341         GList *bb_recheck = NULL, *tmp;
4342         int i, n, start_new_bblock, ialign;
4343         int num_calls = 0, inline_costs = 0;
4344         int breakpoint_id = 0;
4345         guint32 align;
4346         guint real_offset, num_args;
4347         MonoBoolean security, pinvoke;
4348         MonoSecurityManager* secman = NULL;
4349         MonoDeclSecurityActions actions;
4350         GSList *class_inits = NULL;
4351         gboolean dont_verify, dont_verify_stloc;
4352
4353         /* serialization and xdomain stuff may need access to private fields and methods */
4354         dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
4355         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
4356         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
4357         dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
4358         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP;
4359         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP_INVOKE;
4360
4361         /* turn off visibility checks for smcs */
4362         dont_verify |= mono_security_get_mode () == MONO_SECURITY_MODE_SMCS_HACK;
4363
4364         /* still some type unsafety issues in marshal wrappers... (unknown is PtrToStructure) */
4365         dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
4366         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
4367         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
4368
4369         /* Not turned on yet */
4370         cfg->dont_verify_stack_merge = TRUE;
4371
4372         image = method->klass->image;
4373         header = mono_method_get_header (method);
4374         generic_container = method->generic_container;
4375         sig = mono_method_signature (method);
4376         num_args = sig->hasthis + sig->param_count;
4377         ip = (unsigned char*)header->code;
4378         cfg->cil_start = ip;
4379         end = ip + header->code_size;
4380         mono_jit_stats.cil_code_size += header->code_size;
4381
4382         if (sig->is_inflated)
4383                 generic_context = mono_method_get_context (method);
4384         else if (generic_container)
4385                 generic_context = &generic_container->context;
4386
4387         if (!cfg->generic_sharing_context)
4388                 g_assert (!sig->has_type_parameters);
4389
4390         if (cfg->method == method)
4391                 real_offset = 0;
4392         else
4393                 real_offset = inline_offset;
4394
4395         cfg->cil_offset_to_bb = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * header->code_size);
4396         cfg->cil_offset_to_bb_len = header->code_size;
4397
4398         if (cfg->verbose_level > 2)
4399                 g_print ("method to IR %s\n", mono_method_full_name (method, TRUE));
4400
4401         dont_inline = g_list_prepend (dont_inline, method);
4402         if (cfg->method == method) {
4403
4404                 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
4405                         cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
4406
4407                 /* ENTRY BLOCK */
4408                 cfg->bb_entry = start_bblock = NEW_BBLOCK (cfg);
4409                 start_bblock->cil_code = NULL;
4410                 start_bblock->cil_length = 0;
4411                 start_bblock->block_num = cfg->num_bblocks++;
4412
4413                 /* EXIT BLOCK */
4414                 cfg->bb_exit = end_bblock = NEW_BBLOCK (cfg);
4415                 end_bblock->cil_code = NULL;
4416                 end_bblock->cil_length = 0;
4417                 end_bblock->block_num = cfg->num_bblocks++;
4418                 g_assert (cfg->num_bblocks == 2);
4419
4420                 arg_array = alloca (sizeof (MonoInst *) * num_args);
4421                 for (i = num_args - 1; i >= 0; i--)
4422                         arg_array [i] = cfg->varinfo [i];
4423
4424                 if (header->num_clauses) {
4425                         cfg->spvars = g_hash_table_new (NULL, NULL);
4426                         cfg->exvars = g_hash_table_new (NULL, NULL);
4427                 }
4428                 /* handle exception clauses */
4429                 for (i = 0; i < header->num_clauses; ++i) {
4430                         MonoBasicBlock *try_bb;
4431                         MonoExceptionClause *clause = &header->clauses [i];
4432                         GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
4433                         try_bb->real_offset = clause->try_offset;
4434                         GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
4435                         tblock->real_offset = clause->handler_offset;
4436                         tblock->flags |= BB_EXCEPTION_HANDLER;
4437
4438                         link_bblock (cfg, try_bb, tblock);
4439
4440                         if (*(ip + clause->handler_offset) == CEE_POP)
4441                                 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
4442
4443                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
4444                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
4445                             clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
4446                                 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
4447                                 MONO_ADD_INS (tblock, ins);
4448
4449                                 /* todo: is a fault block unsafe to optimize? */
4450                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
4451                                         tblock->flags |= BB_EXCEPTION_UNSAFE;
4452                         }
4453
4454
4455                         /*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);
4456                           while (p < end) {
4457                           g_print ("%s", mono_disasm_code_one (NULL, method, p, &p));
4458                           }*/
4459                         /* catch and filter blocks get the exception object on the stack */
4460                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
4461                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4462                                 MonoInst *load, *dummy_use;
4463
4464                                 /* mostly like handle_stack_args (), but just sets the input args */
4465                                 /* g_print ("handling clause at IL_%04x\n", clause->handler_offset); */
4466                                 tblock->in_scount = 1;
4467                                 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
4468                                 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
4469                                 tblock->stack_state = mono_mempool_alloc (cfg->mempool, sizeof (MonoStackSlot));
4470                                 tblock->stack_state [0].type = STACK_OBJ;
4471                                 /* FIXME? */
4472                                 tblock->stack_state [0].klass = mono_defaults.object_class;
4473
4474                                 /* 
4475                                  * Add a dummy use for the exvar so its liveness info will be
4476                                  * correct.
4477                                  */
4478                                 NEW_TEMPLOAD (cfg, load, tblock->in_stack [0]->inst_c0);
4479                                 NEW_DUMMY_USE (cfg, dummy_use, load);
4480                                 MONO_ADD_INS (tblock, dummy_use);
4481                                 
4482                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4483                                         GET_BBLOCK (cfg, tblock, ip + clause->data.filter_offset);
4484                                         tblock->real_offset = clause->data.filter_offset;
4485                                         tblock->in_scount = 1;
4486                                         tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
4487                                         tblock->stack_state = mono_mempool_alloc (cfg->mempool, sizeof (MonoStackSlot));
4488                                         tblock->stack_state [0].type = STACK_OBJ;
4489                                         /* FIXME? */
4490                                         tblock->stack_state [0].klass = mono_defaults.object_class;
4491
4492                                         /* The filter block shares the exvar with the handler block */
4493                                         tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
4494                                         MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
4495                                         MONO_ADD_INS (tblock, ins);
4496                                 }
4497                         }
4498                 }
4499         } else {
4500                 arg_array = alloca (sizeof (MonoInst *) * num_args);
4501                 mono_save_args (cfg, start_bblock, sig, inline_args, arg_array);
4502         }
4503
4504         /* FIRST CODE BLOCK */
4505         bblock = NEW_BBLOCK (cfg);
4506         bblock->cil_code = ip;
4507
4508         ADD_BBLOCK (cfg, bblock);
4509
4510         if (cfg->method == method) {
4511                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
4512                 if (breakpoint_id && (mono_debug_format != MONO_DEBUG_FORMAT_DEBUGGER)) {
4513                         MONO_INST_NEW (cfg, ins, OP_BREAK);
4514                         MONO_ADD_INS (bblock, ins);
4515                 }
4516         }
4517
4518         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS)
4519                 secman = mono_security_manager_get_methods ();
4520
4521         security = (secman && mono_method_has_declsec (method));
4522         /* at this point having security doesn't mean we have any code to generate */
4523         if (security && (cfg->method == method)) {
4524                 /* Only Demand, NonCasDemand and DemandChoice requires code generation.
4525                  * And we do not want to enter the next section (with allocation) if we
4526                  * have nothing to generate */
4527                 security = mono_declsec_get_demands (method, &actions);
4528         }
4529
4530         /* we must Demand SecurityPermission.Unmanaged before P/Invoking */
4531         pinvoke = (secman && (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE));
4532         if (pinvoke) {
4533                 MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
4534                 if (wrapped && (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4535                         MonoCustomAttrInfo* custom = mono_custom_attrs_from_method (wrapped);
4536
4537                         /* unless the method or it's class has the [SuppressUnmanagedCodeSecurity] attribute */
4538                         if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
4539                                 pinvoke = FALSE;
4540                         }
4541                         if (custom)
4542                                 mono_custom_attrs_free (custom);
4543
4544                         if (pinvoke) {
4545                                 custom = mono_custom_attrs_from_class (wrapped->klass);
4546                                 if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
4547                                         pinvoke = FALSE;
4548                                 }
4549                                 if (custom)
4550                                         mono_custom_attrs_free (custom);
4551                         }
4552                 } else {
4553                         /* not a P/Invoke after all */
4554                         pinvoke = FALSE;
4555                 }
4556         }
4557         
4558         if ((header->init_locals || (cfg->method == method && (cfg->opt & MONO_OPT_SHARED))) || cfg->compile_aot || security || pinvoke) {
4559                 /* we use a separate basic block for the initialization code */
4560                 cfg->bb_init = init_localsbb = NEW_BBLOCK (cfg);
4561                 init_localsbb->real_offset = real_offset;
4562                 start_bblock->next_bb = init_localsbb;
4563                 init_localsbb->next_bb = bblock;
4564                 link_bblock (cfg, start_bblock, init_localsbb);
4565                 link_bblock (cfg, init_localsbb, bblock);
4566                 init_localsbb->block_num = cfg->num_bblocks++;
4567         } else {
4568                 start_bblock->next_bb = bblock;
4569                 link_bblock (cfg, start_bblock, bblock);
4570         }
4571
4572         /* at this point we know, if security is TRUE, that some code needs to be generated */
4573         if (security && (cfg->method == method)) {
4574                 MonoInst *args [2];
4575
4576                 mono_jit_stats.cas_demand_generation++;
4577
4578                 if (actions.demand.blob) {
4579                         /* Add code for SecurityAction.Demand */
4580                         NEW_DECLSECCONST (cfg, args[0], image, actions.demand);
4581                         NEW_ICONST (cfg, args [1], actions.demand.size);
4582                         /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
4583                         mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
4584                 }
4585                 if (actions.noncasdemand.blob) {
4586                         /* CLR 1.x uses a .noncasdemand (but 2.x doesn't) */
4587                         /* For Mono we re-route non-CAS Demand to Demand (as the managed code must deal with it anyway) */
4588                         NEW_DECLSECCONST (cfg, args[0], image, actions.noncasdemand);
4589                         NEW_ICONST (cfg, args [1], actions.noncasdemand.size);
4590                         /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
4591                         mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
4592                 }
4593                 if (actions.demandchoice.blob) {
4594                         /* New in 2.0, Demand must succeed for one of the permissions (i.e. not all) */
4595                         NEW_DECLSECCONST (cfg, args[0], image, actions.demandchoice);
4596                         NEW_ICONST (cfg, args [1], actions.demandchoice.size);
4597                         /* Calls static void SecurityManager.InternalDemandChoice (byte* permissions, int size); */
4598                         mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandchoice, mono_method_signature (secman->demandchoice), args, ip, NULL);
4599                 }
4600         }
4601
4602         /* we must Demand SecurityPermission.Unmanaged before p/invoking */
4603         if (pinvoke) {
4604                 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandunmanaged, mono_method_signature (secman->demandunmanaged), NULL, ip, NULL);
4605         }
4606
4607         if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
4608                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
4609                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
4610                         if (wrapped && (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4611                                 if (!(method->klass && method->klass->image &&
4612                                                 mono_security_core_clr_is_platform_image (method->klass->image))) {
4613                                         emit_throw_method_access_exception (cfg, method, wrapped, bblock, ip);
4614                                 }
4615                         }
4616                 }
4617                 if (!method_is_safe (method))
4618                         emit_throw_verification_exception (cfg, bblock, ip);
4619         }
4620
4621         if (get_basic_blocks (cfg, header, real_offset, ip, end, &err_pos)) {
4622                 ip = err_pos;
4623                 UNVERIFIED;
4624         }
4625
4626         if (cfg->method == method)
4627                 mono_debug_init_method (cfg, bblock, breakpoint_id);
4628
4629         param_types = mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
4630         if (sig->hasthis)
4631                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
4632         for (n = 0; n < sig->param_count; ++n)
4633                 param_types [n + sig->hasthis] = sig->params [n];
4634         for (n = 0; n < header->num_locals; ++n) {
4635                 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
4636                         UNVERIFIED;
4637         }
4638         class_inits = NULL;
4639
4640         /* do this somewhere outside - not here */
4641         NEW_ICONST (cfg, zero_int32, 0);
4642         NEW_ICONST (cfg, zero_int64, 0);
4643         zero_int64->type = STACK_I8;
4644         NEW_PCONST (cfg, zero_ptr, 0);
4645         NEW_PCONST (cfg, zero_obj, 0);
4646         zero_obj->type = STACK_OBJ;
4647
4648         MONO_INST_NEW (cfg, zero_r8, OP_R8CONST);
4649         zero_r8->type = STACK_R8;
4650         zero_r8->inst_p0 = &r8_0;
4651
4652         /* add a check for this != NULL to inlined methods */
4653         if (is_virtual_call) {
4654                 MONO_INST_NEW (cfg, ins, OP_CHECK_THIS);
4655                 NEW_ARGLOAD (cfg, ins->inst_left, 0);
4656                 ins->cil_code = ip;
4657                 MONO_ADD_INS (bblock, ins);
4658         }
4659
4660         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
4661         stack_start = sp = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
4662
4663         ins_flag = 0;
4664         start_new_bblock = 0;
4665         while (ip < end) {
4666
4667                 if (cfg->method == method)
4668                         real_offset = ip - header->code;
4669                 else
4670                         real_offset = inline_offset;
4671
4672                 if (start_new_bblock) {
4673                         bblock->cil_length = ip - bblock->cil_code;
4674                         if (start_new_bblock == 2) {
4675                                 g_assert (ip == tblock->cil_code);
4676                         } else {
4677                                 GET_BBLOCK (cfg, tblock, ip);
4678                         }
4679                         bblock->next_bb = tblock;
4680                         bblock = tblock;
4681                         start_new_bblock = 0;
4682                         for (i = 0; i < bblock->in_scount; ++i) {
4683                                 if (cfg->verbose_level > 3)
4684                                         g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);                                           
4685                                 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
4686                                 *sp++ = ins;
4687                         }
4688                         g_slist_free (class_inits);
4689                         class_inits = NULL;
4690                 } else {
4691                         if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != bblock)) {
4692                                 link_bblock (cfg, bblock, tblock);
4693                                 if (sp != stack_start) {
4694                                         handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
4695                                         sp = stack_start;
4696                                         CHECK_UNVERIFIABLE (cfg);
4697                                 }
4698                                 bblock->next_bb = tblock;
4699                                 bblock = tblock;
4700                                 for (i = 0; i < bblock->in_scount; ++i) {
4701                                         if (cfg->verbose_level > 3)
4702                                                 g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);                                           
4703                                         NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
4704                                         *sp++ = ins;
4705                                 }
4706                                 g_slist_free (class_inits);
4707                                 class_inits = NULL;
4708                         }
4709                 }
4710
4711                 bblock->real_offset = real_offset;
4712
4713                 if ((cfg->method == method) && cfg->coverage_info) {
4714                         MonoInst *store, *one;
4715                         guint32 cil_offset = ip - header->code;
4716                         cfg->coverage_info->data [cil_offset].cil_code = ip;
4717
4718                         /* TODO: Use an increment here */
4719                         NEW_ICONST (cfg, one, 1);
4720                         one->cil_code = ip;
4721
4722                         NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
4723                         ins->cil_code = ip;
4724
4725                         MONO_INST_NEW (cfg, store, CEE_STIND_I);
4726                         store->cil_code = ip;
4727                         store->inst_left = ins;
4728                         store->inst_right = one;
4729
4730                         MONO_ADD_INS (bblock, store);
4731                 }
4732
4733                 if (cfg->verbose_level > 3)
4734                         g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
4735
4736                 switch (*ip) {
4737                 case CEE_NOP:
4738                         MONO_INST_NEW (cfg, ins, OP_NOP);
4739                         ins->cil_code = ip++;
4740                         MONO_ADD_INS (bblock, ins);
4741                         break;
4742                 case CEE_BREAK:
4743                         MONO_INST_NEW (cfg, ins, OP_BREAK);
4744                         ins->cil_code = ip++;
4745                         MONO_ADD_INS (bblock, ins);
4746                         break;
4747                 case CEE_LDARG_0:
4748                 case CEE_LDARG_1:
4749                 case CEE_LDARG_2:
4750                 case CEE_LDARG_3:
4751                         CHECK_STACK_OVF (1);
4752                         n = (*ip)-CEE_LDARG_0;
4753                         CHECK_ARG (n);
4754                         NEW_ARGLOAD (cfg, ins, n);
4755                         LDARG_SOFT_FLOAT (cfg, ins, n, ip);
4756                         ins->cil_code = ip++;
4757                         *sp++ = ins;
4758                         break;
4759                 case CEE_LDLOC_0:
4760                 case CEE_LDLOC_1:
4761                 case CEE_LDLOC_2:
4762                 case CEE_LDLOC_3:
4763                         CHECK_STACK_OVF (1);
4764                         n = (*ip)-CEE_LDLOC_0;
4765                         CHECK_LOCAL (n);
4766                         NEW_LOCLOAD (cfg, ins, n);
4767                         LDLOC_SOFT_FLOAT (cfg, ins, n, ip);
4768                         ins->cil_code = ip++;
4769                         *sp++ = ins;
4770                         break;
4771                 case CEE_STLOC_0:
4772                 case CEE_STLOC_1:
4773                 case CEE_STLOC_2:
4774                 case CEE_STLOC_3:
4775                         CHECK_STACK (1);
4776                         n = (*ip)-CEE_STLOC_0;
4777                         CHECK_LOCAL (n);
4778                         --sp;
4779                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4780                         NEW_LOCSTORE (cfg, ins, n, *sp);
4781                         ins->cil_code = ip;
4782                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
4783                                 UNVERIFIED;
4784                         STLOC_SOFT_FLOAT (cfg, ins, n, ip);
4785                         if (ins->opcode == CEE_STOBJ) {
4786                                 NEW_LOCLOADA (cfg, ins, n);
4787                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
4788                         } else
4789                                 MONO_ADD_INS (bblock, ins);
4790                         ++ip;
4791                         inline_costs += 1;
4792                         break;
4793                 case CEE_LDARG_S:
4794                         CHECK_OPSIZE (2);
4795                         CHECK_STACK_OVF (1);
4796                         CHECK_ARG (ip [1]);
4797                         NEW_ARGLOAD (cfg, ins, ip [1]);
4798                         LDARG_SOFT_FLOAT (cfg, ins, ip [1], ip);
4799                         ins->cil_code = ip;
4800                         *sp++ = ins;
4801                         ip += 2;
4802                         break;
4803                 case CEE_LDARGA_S:
4804                         CHECK_OPSIZE (2);
4805                         CHECK_STACK_OVF (1);
4806                         CHECK_ARG (ip [1]);
4807                         NEW_ARGLOADA (cfg, ins, ip [1]);
4808                         ins->cil_code = ip;
4809                         *sp++ = ins;
4810                         ip += 2;
4811                         break;
4812                 case CEE_STARG_S:
4813                         CHECK_OPSIZE (2);
4814                         CHECK_STACK (1);
4815                         --sp;
4816                         CHECK_ARG (ip [1]);
4817                         NEW_ARGSTORE (cfg, ins, ip [1], *sp);
4818                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4819                         ins->cil_code = ip;
4820                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
4821                                 UNVERIFIED;
4822                         STARG_SOFT_FLOAT (cfg, ins, ip [1], ip);
4823                         if (ins->opcode == CEE_STOBJ) {
4824                                 NEW_ARGLOADA (cfg, ins, ip [1]);
4825                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
4826                         } else
4827                                 MONO_ADD_INS (bblock, ins);
4828                         ip += 2;
4829                         break;
4830                 case CEE_LDLOC_S:
4831                         CHECK_OPSIZE (2);
4832                         CHECK_STACK_OVF (1);
4833                         CHECK_LOCAL (ip [1]);
4834                         NEW_LOCLOAD (cfg, ins, ip [1]);
4835                         LDLOC_SOFT_FLOAT (cfg, ins, ip [1], ip);
4836                         ins->cil_code = ip;
4837                         *sp++ = ins;
4838                         ip += 2;
4839                         break;
4840                 case CEE_LDLOCA_S:
4841                         CHECK_OPSIZE (2);
4842                         CHECK_STACK_OVF (1);
4843                         CHECK_LOCAL (ip [1]);
4844                         NEW_LOCLOADA (cfg, ins, ip [1]);
4845                         ins->cil_code = ip;
4846                         *sp++ = ins;
4847                         ip += 2;
4848                         break;
4849                 case CEE_STLOC_S:
4850                         CHECK_OPSIZE (2);
4851                         CHECK_STACK (1);
4852                         --sp;
4853                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4854                         CHECK_LOCAL (ip [1]);
4855                         NEW_LOCSTORE (cfg, ins, ip [1], *sp);
4856                         ins->cil_code = ip;
4857                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
4858                                 UNVERIFIED;
4859                         STLOC_SOFT_FLOAT (cfg, ins, ip [1], ip);
4860                         if (ins->opcode == CEE_STOBJ) {
4861                                 NEW_LOCLOADA (cfg, ins, ip [1]);
4862                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
4863                         } else
4864                                 MONO_ADD_INS (bblock, ins);
4865                         ip += 2;
4866                         inline_costs += 1;
4867                         break;
4868                 case CEE_LDNULL:
4869                         CHECK_STACK_OVF (1);
4870                         NEW_PCONST (cfg, ins, NULL);
4871                         ins->cil_code = ip;
4872                         ins->type = STACK_OBJ;
4873                         ++ip;
4874                         *sp++ = ins;
4875                         break;
4876                 case CEE_LDC_I4_M1:
4877                         CHECK_STACK_OVF (1);
4878                         NEW_ICONST (cfg, ins, -1);
4879                         ins->cil_code = ip;
4880                         ++ip;
4881                         *sp++ = ins;
4882                         break;
4883                 case CEE_LDC_I4_0:
4884                 case CEE_LDC_I4_1:
4885                 case CEE_LDC_I4_2:
4886                 case CEE_LDC_I4_3:
4887                 case CEE_LDC_I4_4:
4888                 case CEE_LDC_I4_5:
4889                 case CEE_LDC_I4_6:
4890                 case CEE_LDC_I4_7:
4891                 case CEE_LDC_I4_8:
4892                         CHECK_STACK_OVF (1);
4893                         NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
4894                         ins->cil_code = ip;
4895                         ++ip;
4896                         *sp++ = ins;
4897                         break;
4898                 case CEE_LDC_I4_S:
4899                         CHECK_OPSIZE (2);
4900                         CHECK_STACK_OVF (1);
4901                         ++ip;
4902                         NEW_ICONST (cfg, ins, *((signed char*)ip));
4903                         ins->cil_code = ip;
4904                         ++ip;
4905                         *sp++ = ins;
4906                         break;
4907                 case CEE_LDC_I4:
4908                         CHECK_OPSIZE (5);
4909                         CHECK_STACK_OVF (1);
4910                         NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
4911                         ins->cil_code = ip;
4912                         ip += 5;
4913                         *sp++ = ins;
4914                         break;
4915                 case CEE_LDC_I8:
4916                         CHECK_OPSIZE (9);
4917                         CHECK_STACK_OVF (1);
4918                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
4919                         ins->cil_code = ip;
4920                         ins->type = STACK_I8;
4921                         ++ip;
4922                         ins->inst_l = (gint64)read64 (ip);
4923                         ip += 8;
4924                         *sp++ = ins;
4925                         break;
4926                 case CEE_LDC_R4: {
4927                         float *f;
4928                         /* we should really allocate this only late in the compilation process */
4929                         mono_domain_lock (cfg->domain);
4930                         f = mono_mempool_alloc (cfg->domain->mp, sizeof (float));
4931                         mono_domain_unlock (cfg->domain);
4932                         CHECK_OPSIZE (5);
4933                         CHECK_STACK_OVF (1);
4934                         MONO_INST_NEW (cfg, ins, OP_R4CONST);
4935                         ins->type = STACK_R8;
4936                         ++ip;
4937                         readr4 (ip, f);
4938                         ins->inst_p0 = f;
4939
4940                         ip += 4;
4941                         *sp++ = ins;                    
4942                         break;
4943                 }
4944                 case CEE_LDC_R8: {
4945                         double *d;
4946                         mono_domain_lock (cfg->domain);
4947                         d = mono_mempool_alloc (cfg->domain->mp, sizeof (double));
4948                         mono_domain_unlock (cfg->domain);
4949                         CHECK_OPSIZE (9);
4950                         CHECK_STACK_OVF (1);
4951                         MONO_INST_NEW (cfg, ins, OP_R8CONST);
4952                         ins->type = STACK_R8;
4953                         ++ip;
4954                         readr8 (ip, d);
4955                         ins->inst_p0 = d;
4956
4957                         ip += 8;
4958                         *sp++ = ins;                    
4959                         break;
4960                 }
4961                 case CEE_DUP: {
4962                         MonoInst *temp, *store;
4963                         CHECK_STACK (1);
4964                         CHECK_STACK_OVF (1);
4965                         sp--;
4966                         ins = *sp;
4967                 
4968                         /* 
4969                          * small optimization: if the loaded value was from a local already,
4970                          * just load it twice.
4971                          */
4972                         if (ins->ssa_op == MONO_SSA_LOAD && 
4973                             (ins->inst_i0->opcode == OP_LOCAL || ins->inst_i0->opcode == OP_ARG)) {
4974                                 sp++;
4975                                 MONO_INST_NEW (cfg, temp, 0);
4976                                 *temp = *ins;
4977                                 temp->cil_code = ip;
4978                                 *sp++ = temp;
4979                         } else {
4980                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
4981                                 temp->flags |= MONO_INST_IS_TEMP;
4982                                 temp->cil_code = ip;
4983                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
4984                                 store->cil_code = ip;
4985                                 /* FIXME: handle CEE_STIND_R4 */
4986                                 if (store->opcode == CEE_STOBJ) {
4987                                         NEW_TEMPLOADA (cfg, store, temp->inst_c0);
4988                                         handle_stobj (cfg, bblock, store, sp [0], sp [0]->cil_code, store->klass, TRUE, FALSE, FALSE);
4989                                 } else {
4990                                         MONO_ADD_INS (bblock, store);
4991                                 }
4992                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
4993                                 *sp++ = ins;
4994                                 ins->cil_code = ip;
4995                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
4996                                 *sp++ = ins;
4997                                 ins->cil_code = ip;
4998                         }
4999                         ++ip;
5000                         inline_costs += 2;
5001                         break;
5002                 }
5003                 case CEE_POP:
5004                         CHECK_STACK (1);
5005                         MONO_INST_NEW (cfg, ins, CEE_POP);
5006                         MONO_ADD_INS (bblock, ins);
5007                         ins->cil_code = ip++;
5008                         --sp;
5009                         ins->inst_i0 = *sp;
5010                         break;
5011                 case CEE_JMP:
5012                         CHECK_OPSIZE (5);
5013                         if (stack_start != sp)
5014                                 UNVERIFIED;
5015                         MONO_INST_NEW (cfg, ins, OP_JMP);
5016                         token = read32 (ip + 1);
5017                         /* FIXME: check the signature matches */
5018                         cmethod = mini_get_method (method, token, NULL, generic_context);
5019
5020                         if (!cmethod)
5021                                 goto load_error;
5022
5023                         if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
5024                                 GENERIC_SHARING_FAILURE (CEE_JMP);
5025
5026                         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
5027                                 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
5028                                         INLINE_FAILURE;
5029                                 CHECK_CFG_EXCEPTION;
5030                         }
5031
5032                         ins->inst_p0 = cmethod;
5033                         MONO_ADD_INS (bblock, ins);
5034                         ip += 5;
5035                         start_new_bblock = 1;
5036                         break;
5037                 case CEE_CALLI:
5038                 case CEE_CALL:
5039                 case CEE_CALLVIRT: {
5040                         MonoInst *addr = NULL;
5041                         MonoMethodSignature *fsig = NULL;
5042                         int temp, array_rank = 0;
5043                         int virtual = *ip == CEE_CALLVIRT;
5044
5045                         CHECK_OPSIZE (5);
5046                         token = read32 (ip + 1);
5047
5048                         if (*ip == CEE_CALLI) {
5049                                 cmethod = NULL;
5050                                 CHECK_STACK (1);
5051                                 --sp;
5052                                 addr = *sp;
5053                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
5054                                         fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
5055                                 else
5056                                         fsig = mono_metadata_parse_signature (image, token);
5057
5058                                 n = fsig->param_count + fsig->hasthis;
5059                         } else {
5060                                 MonoMethod *cil_method;
5061                                 
5062                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
5063                                         cmethod =  (MonoMethod *)mono_method_get_wrapper_data (method, token);
5064                                         cil_method = cmethod;
5065                                 } else if (constrained_call) {
5066                                         cmethod = mono_get_method_constrained (image, token, constrained_call, generic_context, &cil_method);
5067                                         cil_method = cmethod;
5068                                 } else {
5069                                         cmethod = mini_get_method (method, token, NULL, generic_context);
5070                                         cil_method = cmethod;
5071                                 }
5072
5073                                 if (!cmethod)
5074                                         goto load_error;
5075                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cil_method))
5076                                         METHOD_ACCESS_FAILURE;
5077
5078                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
5079                                         ensure_method_is_allowed_to_call_method (cfg, method, cil_method, bblock, ip);
5080
5081                                 if (!virtual && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
5082                                         /* MS.NET seems to silently convert this to a callvirt */
5083                                         virtual = 1;
5084
5085                                 if (!cmethod->klass->inited){
5086                                         if (!mono_class_init (cmethod->klass))
5087                                                 goto load_error;
5088                                 }
5089
5090                                 if (mono_method_signature (cmethod)->pinvoke) {
5091                                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod);
5092                                         fsig = mono_method_signature (wrapper);
5093                                 } else if (constrained_call) {
5094                                         fsig = mono_method_signature (cmethod);
5095                                 } else {
5096                                         fsig = mono_method_get_signature_full (cmethod, image, token, generic_context);
5097                                 }
5098
5099                                 mono_save_token_info (cfg, image, token, cmethod);
5100
5101                                 n = fsig->param_count + fsig->hasthis;
5102
5103                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
5104                                         if (check_linkdemand (cfg, method, cmethod, bblock, ip))
5105                                                 INLINE_FAILURE;
5106                                         CHECK_CFG_EXCEPTION;
5107                                 }
5108
5109                                 if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
5110                                     mini_class_is_system_array (cmethod->klass)) {
5111                                         array_rank = cmethod->klass->rank;
5112                                 }
5113
5114                                 if (cmethod->string_ctor)
5115                                         g_assert_not_reached ();
5116
5117                         }
5118
5119                         if (!cfg->generic_sharing_context && cmethod && cmethod->klass->generic_container)
5120                                 UNVERIFIED;
5121
5122                         if (cfg->generic_sharing_context && cmethod && mono_method_check_context_used (cmethod))
5123                                 GENERIC_SHARING_FAILURE (*ip);
5124
5125                         CHECK_STACK (n);
5126
5127                         //g_assert (!virtual || fsig->hasthis);
5128
5129                         sp -= n;
5130
5131                         if (constrained_call) {
5132                                 /*
5133                                  * We have the `constrained.' prefix opcode.
5134                                  */
5135                                 if (constrained_call->valuetype && !cmethod->klass->valuetype) {
5136                                         MonoInst *load;
5137                                         /*
5138                                          * The type parameter is instantiated as a valuetype,
5139                                          * but that type doesn't override the method we're
5140                                          * calling, so we need to box `this'.
5141                                          * sp [0] is a pointer to the data: we need the value
5142                                          * in handle_box (), so load it here.
5143                                          */
5144                                         MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, &constrained_call->byval_arg));
5145                                         type_to_eval_stack_type (cfg, &constrained_call->byval_arg, load);
5146                                         load->cil_code = ip;
5147                                         load->inst_left = sp [0];
5148                                         sp [0] = handle_box (cfg, bblock, load, ip, constrained_call);
5149                                 } else if (!constrained_call->valuetype) {
5150                                         MonoInst *ins;
5151
5152                                         /*
5153                                          * The type parameter is instantiated as a reference
5154                                          * type.  We have a managed pointer on the stack, so
5155                                          * we need to dereference it here.
5156                                          */
5157
5158                                         MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
5159                                         ins->cil_code = ip;
5160                                         ins->inst_i0 = sp [0];
5161                                         ins->type = STACK_OBJ;
5162                                         ins->klass = mono_class_from_mono_type (&constrained_call->byval_arg);
5163                                         sp [0] = ins;
5164                                 } else if (cmethod->klass->valuetype)
5165                                         virtual = 0;
5166                                 constrained_call = NULL;
5167                         }
5168
5169                         if (*ip != CEE_CALLI && check_call_signature (cfg, fsig, sp))
5170                                 UNVERIFIED;
5171
5172                         if (cmethod && virtual && 
5173                             (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) && 
5174                             !((cmethod->flags & METHOD_ATTRIBUTE_FINAL) && 
5175                               cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
5176                             mono_method_signature (cmethod)->generic_param_count) {
5177                                 MonoInst *this_temp, *this_arg_temp, *store;
5178                                 MonoInst *iargs [4];
5179
5180                                 g_assert (mono_method_signature (cmethod)->is_inflated);
5181                                 /* Prevent inlining of methods that contain indirect calls */
5182                                 INLINE_FAILURE;
5183
5184                                 this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
5185                                 this_temp->cil_code = ip;
5186                                 NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
5187
5188                                 store->cil_code = ip;
5189                                 MONO_ADD_INS (bblock, store);
5190
5191                                 /* FIXME: This should be a managed pointer */
5192                                 this_arg_temp = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
5193                                 this_arg_temp->cil_code = ip;
5194
5195                                 /* Because of the PCONST below */
5196                                 cfg->disable_aot = TRUE;
5197                                 NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
5198                                 NEW_METHODCONST (cfg, iargs [1], cmethod);
5199                                 NEW_PCONST (cfg, iargs [2], mono_method_get_context (cmethod));
5200                                 NEW_TEMPLOADA (cfg, iargs [3], this_arg_temp->inst_c0);
5201                                 temp = mono_emit_jit_icall (cfg, bblock, mono_helper_compile_generic_method, iargs, ip);
5202
5203                                 NEW_TEMPLOAD (cfg, addr, temp);
5204                                 NEW_TEMPLOAD (cfg, sp [0], this_arg_temp->inst_c0);
5205
5206                                 if ((temp = mono_emit_calli (cfg, bblock, fsig, sp, addr, ip)) != -1) {
5207                                         NEW_TEMPLOAD (cfg, *sp, temp);
5208                                         sp++;
5209                                 }
5210
5211                                 ip += 5;
5212                                 ins_flag = 0;
5213                                 break;
5214                         }
5215
5216                         if ((ins_flag & MONO_INST_TAILCALL) && cmethod && (*ip == CEE_CALL) &&
5217                                  (mono_metadata_signature_equal (mono_method_signature (method), mono_method_signature (cmethod)))) {
5218                                 int i;
5219
5220                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
5221                                 INLINE_FAILURE;
5222                                 /* FIXME: This assumes the two methods has the same number and type of arguments */
5223                                 /*
5224                                  * We implement tail calls by storing the actual arguments into the 
5225                                  * argument variables, then emitting a OP_JMP. Since the actual arguments
5226                                  * can refer to the arg variables, we have to spill them.
5227                                  */
5228                                 handle_loaded_temps (cfg, bblock, sp, sp + n);
5229                                 for (i = 0; i < n; ++i) {
5230                                         /* Prevent argument from being register allocated */
5231                                         arg_array [i]->flags |= MONO_INST_VOLATILE;
5232
5233                                         /* Check if argument is the same */
5234                                         /* 
5235                                          * FIXME: This loses liveness info, so it can only be done if the
5236                                          * argument is not register allocated.
5237                                          */
5238                                         NEW_ARGLOAD (cfg, ins, i);
5239                                         if ((ins->opcode == sp [i]->opcode) && (ins->inst_i0 == sp [i]->inst_i0))
5240                                                 continue;
5241
5242                                         NEW_ARGSTORE (cfg, ins, i, sp [i]);
5243                                         ins->cil_code = ip;
5244                                         /* FIXME: handle CEE_STIND_R4 */
5245                                         if (ins->opcode == CEE_STOBJ) {
5246                                                 NEW_ARGLOADA (cfg, ins, i);
5247                                                 handle_stobj (cfg, bblock, ins, sp [i], sp [i]->cil_code, ins->klass, FALSE, FALSE, FALSE);
5248                                         }
5249                                         else
5250                                                 MONO_ADD_INS (bblock, ins);
5251                                 }
5252                                 MONO_INST_NEW (cfg, ins, OP_JMP);
5253                                 ins->cil_code = ip;
5254                                 ins->inst_p0 = cmethod;
5255                                 ins->inst_p1 = arg_array [0];
5256                                 MONO_ADD_INS (bblock, ins);
5257                                 link_bblock (cfg, bblock, end_bblock);                  
5258                                 start_new_bblock = 1;
5259                                 /* skip CEE_RET as well */
5260                                 ip += 6;
5261                                 ins_flag = 0;
5262                                 break;
5263                         }
5264                         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_get_inst_for_method (cfg, cmethod, fsig, sp))) {
5265                                 ins->cil_code = ip;
5266
5267                                 if (MONO_TYPE_IS_VOID (fsig->ret)) {
5268                                         MONO_ADD_INS (bblock, ins);
5269                                 } else {
5270                                         type_to_eval_stack_type (cfg, fsig->ret, ins);
5271                                         *sp = ins;
5272                                         sp++;
5273                                 }
5274
5275                                 ip += 5;
5276                                 ins_flag = 0;
5277                                 break;
5278                         }
5279
5280                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5281
5282                         if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
5283                             (!virtual || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || (cmethod->flags & METHOD_ATTRIBUTE_FINAL)) && 
5284                             mono_method_check_inlining (cfg, cmethod) &&
5285                                  !g_list_find (dont_inline, cmethod)) {
5286                                 int costs;
5287                                 MonoBasicBlock *ebblock;
5288                                 gboolean allways = FALSE;
5289
5290                                 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
5291                                         (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5292                                         /* Prevent inlining of methods that call wrappers */
5293                                         INLINE_FAILURE;
5294                                         cmethod = mono_marshal_get_native_wrapper (cmethod);
5295                                         allways = TRUE;
5296                                 }
5297
5298                                 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, allways))) {
5299                                         ip += 5;
5300                                         real_offset += 5;
5301
5302                                         GET_BBLOCK (cfg, bblock, ip);
5303                                         ebblock->next_bb = bblock;
5304                                         link_bblock (cfg, ebblock, bblock);
5305
5306                                         if (!MONO_TYPE_IS_VOID (fsig->ret))
5307                                                 sp++;
5308
5309                                         /* indicates start of a new block, and triggers a load of all 
5310                                            stack arguments at bb boundarie */
5311                                         bblock = ebblock;
5312
5313                                         inline_costs += costs;
5314                                         ins_flag = 0;
5315                                         break;
5316                                 }
5317                         }
5318                         
5319                         inline_costs += 10 * num_calls++;
5320
5321                         /* tail recursion elimination */
5322                         if ((cfg->opt & MONO_OPT_TAILC) && *ip == CEE_CALL && cmethod == method && ip [5] == CEE_RET) {
5323                                 gboolean has_vtargs = FALSE;
5324                                 int i;
5325                                 
5326                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
5327                                 INLINE_FAILURE;
5328                                 /* keep it simple */
5329                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
5330                                         if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i])) 
5331                                                 has_vtargs = TRUE;
5332                                 }
5333
5334                                 if (!has_vtargs) {
5335                                         for (i = 0; i < n; ++i) {
5336                                                 /* FIXME: handle CEE_STIND_R4 */
5337                                                 NEW_ARGSTORE (cfg, ins, i, sp [i]);
5338                                                 ins->cil_code = ip;
5339                                                 MONO_ADD_INS (bblock, ins);
5340                                         }
5341                                         MONO_INST_NEW (cfg, ins, OP_BR);
5342                                         ins->cil_code = ip;
5343                                         MONO_ADD_INS (bblock, ins);
5344                                         tblock = start_bblock->out_bb [0];
5345                                         link_bblock (cfg, bblock, tblock);
5346                                         ins->inst_target_bb = tblock;
5347                                         start_new_bblock = 1;
5348
5349                                         /* skip the CEE_RET, too */
5350                                         if (ip_in_bb (cfg, bblock, ip + 5))
5351                                                 ip += 6;
5352                                         else
5353                                                 ip += 5;
5354                                         ins_flag = 0;
5355                                         break;
5356                                 }
5357                         }
5358
5359                         if (*ip == CEE_CALLI) {
5360                                 /* Prevent inlining of methods with indirect calls */
5361                                 INLINE_FAILURE;
5362                                 if ((temp = mono_emit_calli (cfg, bblock, fsig, sp, addr, ip)) != -1) {
5363                                         NEW_TEMPLOAD (cfg, *sp, temp);
5364                                         sp++;
5365                                 }                                       
5366                         } else if (array_rank) {
5367                                 MonoInst *addr;
5368
5369                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
5370                                         if (sp [fsig->param_count]->type == STACK_OBJ) {
5371                                                 MonoInst *iargs [2];
5372                                                 MonoInst *array, *to_store, *store;
5373
5374                                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5375                                                 
5376                                                 array = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
5377                                                 NEW_TEMPSTORE (cfg, store, array->inst_c0, sp [0]);
5378                                                 store->cil_code = ip;
5379                                                 MONO_ADD_INS (bblock, store);
5380                                                 NEW_TEMPLOAD (cfg, iargs [0], array->inst_c0);
5381
5382                                                 to_store = mono_compile_create_var (cfg, type_from_stack_type (sp [fsig->param_count]), OP_LOCAL);
5383                                                 NEW_TEMPSTORE (cfg, store, to_store->inst_c0, sp [fsig->param_count]);
5384                                                 /* FIXME: handle CEE_STIND_R4 */
5385                                                 store->cil_code = ip;
5386                                                 MONO_ADD_INS (bblock, store);
5387                                                 NEW_TEMPLOAD (cfg, iargs [1], to_store->inst_c0);
5388
5389                                                 /*
5390                                                  * We first save the args for the call so that the args are copied to the stack
5391                                                  * and a new instruction tree for them is created. If we don't do this,
5392                                                  * the same MonoInst is added to two different trees and this is not 
5393                                                  * allowed by burg.
5394                                                  */
5395                                                 mono_emit_jit_icall (cfg, bblock, mono_helper_stelem_ref_check, iargs, ip);
5396
5397                                                 NEW_TEMPLOAD (cfg, sp [0], array->inst_c0);
5398                                                 NEW_TEMPLOAD (cfg, sp [fsig->param_count], to_store->inst_c0);
5399                                         }
5400
5401                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, TRUE);
5402                                         NEW_INDSTORE (cfg, ins, addr, sp [fsig->param_count], fsig->params [fsig->param_count - 1]);
5403                                         ins->cil_code = ip;
5404                                         /* FIXME: handle CEE_STIND_R4 */
5405                                         if (ins->opcode == CEE_STOBJ) {
5406                                                 handle_stobj (cfg, bblock, addr, sp [fsig->param_count], ip, mono_class_from_mono_type (fsig->params [fsig->param_count-1]), FALSE, FALSE, TRUE);
5407                                         } else {
5408                                                 MONO_ADD_INS (bblock, ins);
5409                                         }
5410
5411                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
5412                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
5413                                         NEW_INDLOAD (cfg, ins, addr, fsig->ret);
5414                                         ins->cil_code = ip;
5415
5416                                         *sp++ = ins;
5417                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
5418                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
5419                                         *sp++ = addr;
5420                                 } else {
5421                                         g_assert_not_reached ();
5422                                 }
5423
5424                         } else {
5425                                 /* Prevent inlining of methods which call other methods */
5426                                 INLINE_FAILURE;
5427                                 if (mini_redirect_call (&temp, cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL)) {
5428                                         if (temp != -1) {
5429                                                 NEW_TEMPLOAD (cfg, *sp, temp);
5430                                                 sp++;
5431                                         }
5432                                 } else if (ip_in_bb (cfg, bblock, ip + 5) 
5433                                     && (!MONO_TYPE_ISSTRUCT (fsig->ret))
5434                                     && (!MONO_TYPE_IS_VOID (fsig->ret) || cmethod->string_ctor)
5435                                     && (CODE_IS_STLOC (ip + 5) || ip [5] == CEE_POP || ip [5] == CEE_RET)) {
5436                                         /* no need to spill */
5437                                         ins = (MonoInst*)mono_emit_method_call (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL);
5438                                         *sp++ = ins;
5439                                 } else {
5440                                         if ((temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL)) != -1) {
5441                                                 MonoInst *load;
5442                                                 NEW_TEMPLOAD (cfg, load, temp);
5443
5444 #ifdef MONO_ARCH_SOFT_FLOAT
5445                                                 if (load->opcode == CEE_LDIND_R4) {
5446                                                         NEW_TEMPLOADA (cfg, load, temp);
5447                                                         temp = handle_load_float (cfg, bblock, load, ip);
5448                                                         NEW_TEMPLOAD (cfg, load, temp);
5449                                                 }
5450 #endif
5451                                                 *sp++ = load;
5452                                         }
5453                                 }
5454                         }
5455
5456                         ip += 5;
5457                         ins_flag = 0;
5458                         break;
5459                 }
5460                 case CEE_RET:
5461                         if (cfg->method != method) {
5462                                 /* return from inlined methode */
5463                                 if (return_var) {
5464                                         MonoInst *store;
5465                                         CHECK_STACK (1);
5466                                         --sp;
5467                                         //g_assert (returnvar != -1);
5468                                         NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
5469                                         store->cil_code = sp [0]->cil_code;
5470                                         /* FIXME: handle CEE_STIND_R4 */
5471                                         if (store->opcode == CEE_STOBJ) {
5472                                                 g_assert_not_reached ();
5473                                                 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
5474                                                 /* FIXME: it is possible some optimization will pass the a heap pointer for the struct address, so we'll need the write barrier */
5475                                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, return_var->klass, FALSE, FALSE, FALSE);
5476                                         } else
5477                                                 MONO_ADD_INS (bblock, store);
5478                                 } 
5479                         } else {
5480                                 if (cfg->ret) {
5481                                         g_assert (!return_var);
5482                                         CHECK_STACK (1);
5483                                         --sp;
5484                                         MONO_INST_NEW (cfg, ins, OP_NOP);
5485                                         ins->opcode = mini_type_to_stind (cfg, mono_method_signature (method)->ret);
5486                                         if (ins->opcode == CEE_STOBJ) {
5487                                                 NEW_RETLOADA (cfg, ins);
5488                                                 /* FIXME: it is possible some optimization will pass the a heap pointer for the struct address, so we'll need the write barrier */
5489                                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5490                                         } else {
5491                                                 ins->opcode = OP_SETRET;
5492                                                 ins->cil_code = ip;
5493                                                 ins->inst_i0 = *sp;;
5494                                                 ins->inst_i1 = NULL;
5495                                                 MONO_ADD_INS (bblock, ins);
5496                                         }
5497                                 }
5498                         }
5499                         if (sp != stack_start)
5500                                 UNVERIFIED;
5501                         MONO_INST_NEW (cfg, ins, OP_BR);
5502                         ins->cil_code = ip++;
5503                         ins->inst_target_bb = end_bblock;
5504                         MONO_ADD_INS (bblock, ins);
5505                         link_bblock (cfg, bblock, end_bblock);
5506                         start_new_bblock = 1;
5507                         break;
5508                 case CEE_BR_S:
5509                         CHECK_OPSIZE (2);
5510                         MONO_INST_NEW (cfg, ins, OP_BR);
5511                         ins->cil_code = ip++;
5512                         MONO_ADD_INS (bblock, ins);
5513                         target = ip + 1 + (signed char)(*ip);
5514                         ++ip;
5515                         GET_BBLOCK (cfg, tblock, target);
5516                         link_bblock (cfg, bblock, tblock);
5517                         CHECK_BBLOCK (target, ip, tblock);
5518                         ins->inst_target_bb = tblock;
5519                         if (sp != stack_start) {
5520                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5521                                 sp = stack_start;
5522                                 CHECK_UNVERIFIABLE (cfg);
5523                         }
5524                         start_new_bblock = 1;
5525                         inline_costs += BRANCH_COST;
5526                         break;
5527                 case CEE_BRFALSE_S:
5528                 case CEE_BRTRUE_S:
5529                         CHECK_OPSIZE (2);
5530                         CHECK_STACK (1);
5531                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
5532                                 UNVERIFIED;
5533                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
5534                         ins->cil_code = ip++;
5535                         target = ip + 1 + *(signed char*)ip;
5536                         ip++;
5537                         ADD_UNCOND (ins->opcode == CEE_BRTRUE);
5538                         if (sp != stack_start) {
5539                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5540                                 sp = stack_start;
5541                                 CHECK_UNVERIFIABLE (cfg);
5542                         }
5543                         inline_costs += BRANCH_COST;
5544                         break;
5545                 case CEE_BEQ_S:
5546                 case CEE_BGE_S:
5547                 case CEE_BGT_S:
5548                 case CEE_BLE_S:
5549                 case CEE_BLT_S:
5550                 case CEE_BNE_UN_S:
5551                 case CEE_BGE_UN_S:
5552                 case CEE_BGT_UN_S:
5553                 case CEE_BLE_UN_S:
5554                 case CEE_BLT_UN_S:
5555                         CHECK_OPSIZE (2);
5556                         CHECK_STACK (2);
5557                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
5558                         ins->cil_code = ip++;
5559                         target = ip + 1 + *(signed char*)ip;
5560                         ip++;
5561 #ifdef MONO_ARCH_SOFT_FLOAT
5562                         if (sp [-1]->type == STACK_R8 || sp [-2]->type == STACK_R8) {
5563                                 ins->opcode = condbr_to_fp_br (ins->opcode);
5564                                 sp -= 2;
5565                                 ins->inst_left = sp [0];
5566                                 ins->inst_right = sp [1];
5567                                 ins->type = STACK_I4;
5568                                 *sp++ = emit_tree (cfg, bblock, ins, ins->cil_code);
5569                                 MONO_INST_NEW (cfg, ins, CEE_BRTRUE);
5570                                 ADD_UNCOND (TRUE);
5571                         } else {
5572                                 ADD_BINCOND (NULL);
5573                         }
5574 #else
5575                         ADD_BINCOND (NULL);
5576 #endif
5577                         if (sp != stack_start) {
5578                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5579                                 sp = stack_start;
5580                                 CHECK_UNVERIFIABLE (cfg);
5581                         }
5582                         inline_costs += BRANCH_COST;
5583                         break;
5584                 case CEE_BR:
5585                         CHECK_OPSIZE (5);
5586                         MONO_INST_NEW (cfg, ins, OP_BR);
5587                         ins->cil_code = ip++;
5588                         MONO_ADD_INS (bblock, ins);
5589                         target = ip + 4 + (gint32)read32(ip);
5590                         ip += 4;
5591                         GET_BBLOCK (cfg, tblock, target);
5592                         link_bblock (cfg, bblock, tblock);
5593                         CHECK_BBLOCK (target, ip, tblock);
5594                         ins->inst_target_bb = tblock;
5595                         if (sp != stack_start) {
5596                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5597                                 sp = stack_start;
5598                                 CHECK_UNVERIFIABLE (cfg);
5599                         }
5600                         start_new_bblock = 1;
5601                         inline_costs += BRANCH_COST;
5602                         break;
5603                 case CEE_BRFALSE:
5604                 case CEE_BRTRUE:
5605                         CHECK_OPSIZE (5);
5606                         CHECK_STACK (1);
5607                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
5608                                 UNVERIFIED;
5609                         MONO_INST_NEW (cfg, ins, *ip);
5610                         ins->cil_code = ip++;
5611                         target = ip + 4 + (gint32)read32(ip);
5612                         ip += 4;
5613                         ADD_UNCOND(ins->opcode == CEE_BRTRUE);
5614                         if (sp != stack_start) {
5615                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5616                                 sp = stack_start;
5617                                 CHECK_UNVERIFIABLE (cfg);
5618                         }
5619                         inline_costs += BRANCH_COST;
5620                         break;
5621                 case CEE_BEQ:
5622                 case CEE_BGE:
5623                 case CEE_BGT:
5624                 case CEE_BLE:
5625                 case CEE_BLT:
5626                 case CEE_BNE_UN:
5627                 case CEE_BGE_UN:
5628                 case CEE_BGT_UN:
5629                 case CEE_BLE_UN:
5630                 case CEE_BLT_UN:
5631                         CHECK_OPSIZE (5);
5632                         CHECK_STACK (2);
5633                         MONO_INST_NEW (cfg, ins, *ip);
5634                         ins->cil_code = ip++;
5635                         target = ip + 4 + (gint32)read32(ip);
5636                         ip += 4;
5637 #ifdef MONO_ARCH_SOFT_FLOAT
5638                         if (sp [-1]->type == STACK_R8 || sp [-2]->type == STACK_R8) {
5639                                 ins->opcode = condbr_to_fp_br (ins->opcode);
5640                                 sp -= 2;
5641                                 ins->inst_left = sp [0];
5642                                 ins->inst_right = sp [1];
5643                                 ins->type = STACK_I4;
5644                                 *sp++ = emit_tree (cfg, bblock, ins, ins->cil_code);
5645                                 MONO_INST_NEW (cfg, ins, CEE_BRTRUE);
5646                                 ADD_UNCOND (TRUE);
5647                         } else {
5648                                 ADD_BINCOND (NULL);
5649                         }
5650 #else
5651                         ADD_BINCOND (NULL);
5652 #endif
5653                         if (sp != stack_start) {
5654                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5655                                 sp = stack_start;
5656                                 CHECK_UNVERIFIABLE (cfg);
5657                         }
5658                         inline_costs += BRANCH_COST;
5659                         break;
5660                 case CEE_SWITCH:
5661                         CHECK_OPSIZE (5);
5662                         CHECK_STACK (1);
5663                         n = read32 (ip + 1);
5664                         MONO_INST_NEW (cfg, ins, *ip);
5665                         --sp;
5666                         ins->inst_left = *sp;
5667                         if ((ins->inst_left->type != STACK_I4) && (ins->inst_left->type != STACK_PTR)) 
5668                                 UNVERIFIED;
5669                         ins->cil_code = ip;
5670                         ip += 5;
5671                         CHECK_OPSIZE (n * sizeof (guint32));
5672                         target = ip + n * sizeof (guint32);
5673                         MONO_ADD_INS (bblock, ins);
5674                         GET_BBLOCK (cfg, tblock, target);
5675                         link_bblock (cfg, bblock, tblock);
5676                         ins->klass = GUINT_TO_POINTER (n);
5677                         ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (n + 1));
5678                         ins->inst_many_bb [n] = tblock;
5679
5680                         for (i = 0; i < n; ++i) {
5681                                 GET_BBLOCK (cfg, tblock, target + (gint32)read32(ip));
5682                                 link_bblock (cfg, bblock, tblock);
5683                                 ins->inst_many_bb [i] = tblock;
5684                                 ip += 4;
5685                         }
5686                         if (sp != stack_start) {
5687                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5688                                 sp = stack_start;
5689                                 CHECK_UNVERIFIABLE (cfg);
5690                         }
5691                         /* Needed by the code generated in inssel.brg */
5692                         mono_get_got_var (cfg);
5693                         inline_costs += (BRANCH_COST * 2);
5694                         break;
5695                 case CEE_LDIND_I1:
5696                 case CEE_LDIND_U1:
5697                 case CEE_LDIND_I2:
5698                 case CEE_LDIND_U2:
5699                 case CEE_LDIND_I4:
5700                 case CEE_LDIND_U4:
5701                 case CEE_LDIND_I8:
5702                 case CEE_LDIND_I:
5703                 case CEE_LDIND_R4:
5704                 case CEE_LDIND_R8:
5705                 case CEE_LDIND_REF:
5706                         CHECK_STACK (1);
5707                         MONO_INST_NEW (cfg, ins, *ip);
5708                         ins->cil_code = ip;
5709                         --sp;
5710                         ins->inst_i0 = *sp;
5711                         *sp++ = ins;
5712                         ins->type = ldind_type [*ip - CEE_LDIND_I1];
5713                         ins->flags |= ins_flag;
5714                         ins_flag = 0;
5715                         if (ins->type == STACK_OBJ)
5716                                 ins->klass = mono_defaults.object_class;
5717 #ifdef MONO_ARCH_SOFT_FLOAT
5718                         if (*ip == CEE_LDIND_R4) {
5719                                 int temp;
5720                                 --sp;
5721                                 temp = handle_load_float (cfg, bblock, ins->inst_i0, ip);
5722                                 NEW_TEMPLOAD (cfg, *sp, temp);
5723                                 sp++;
5724                         }
5725 #endif
5726                         ++ip;
5727                         break;
5728                 case CEE_STIND_REF:
5729                 case CEE_STIND_I1:
5730                 case CEE_STIND_I2:
5731                 case CEE_STIND_I4:
5732                 case CEE_STIND_I8:
5733                 case CEE_STIND_R4:
5734                 case CEE_STIND_R8:
5735                         CHECK_STACK (2);
5736 #ifdef MONO_ARCH_SOFT_FLOAT
5737                         if (*ip == CEE_STIND_R4) {
5738                                 sp -= 2;
5739                                 handle_store_float (cfg, bblock, sp [0], sp [1], ip);
5740                                 ip++;
5741                                 break;
5742                         }
5743 #endif
5744 #if HAVE_WRITE_BARRIERS
5745                         if (*ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER) {
5746                                 /* insert call to write barrier */
5747                                 MonoMethod *write_barrier = mono_marshal_get_write_barrier ();
5748                                 sp -= 2;
5749                                 mono_emit_method_call_spilled (cfg, bblock, write_barrier, mono_method_signature (write_barrier), sp, ip, NULL);
5750                                 ip++;
5751                                 break;
5752                         }
5753 #endif
5754                         MONO_INST_NEW (cfg, ins, *ip);
5755                         ins->cil_code = ip++;
5756                         sp -= 2;
5757                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5758                         MONO_ADD_INS (bblock, ins);
5759                         ins->inst_i0 = sp [0];
5760                         ins->inst_i1 = sp [1];
5761                         ins->flags |= ins_flag;
5762                         ins_flag = 0;
5763                         inline_costs += 1;
5764                         break;
5765                 case CEE_MUL:
5766                         CHECK_STACK (2);
5767                         ADD_BINOP (*ip);
5768
5769 #ifdef MONO_ARCH_NO_EMULATE_MUL_IMM
5770                         /* FIXME: This breaks with ssapre (mono -O=ssapre loader.exe) */
5771                         if ((ins->inst_right->opcode == OP_ICONST) && !(cfg->opt & MONO_OPT_SSAPRE)) {
5772                                 switch (ins->opcode) {
5773                                 case CEE_MUL:
5774                                         ins->opcode = OP_IMUL_IMM;
5775                                         ins->inst_imm = ins->inst_right->inst_c0;
5776                                         break;
5777                                 case OP_LMUL:
5778                                         ins->opcode = OP_LMUL_IMM;
5779                                         ins->inst_imm = ins->inst_right->inst_c0;
5780                                         break;
5781                                 default:
5782                                         g_assert_not_reached ();
5783                                 }
5784                         }
5785 #endif
5786
5787                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
5788                                 --sp;
5789                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
5790                         }
5791                         ip++;
5792                         break;
5793                 case CEE_ADD:
5794                 case CEE_SUB:
5795                 case CEE_DIV:
5796                 case CEE_DIV_UN:
5797                 case CEE_REM:
5798                 case CEE_REM_UN:
5799                 case CEE_AND:
5800                 case CEE_OR:
5801                 case CEE_XOR:
5802                 case CEE_SHL:
5803                 case CEE_SHR:
5804                 case CEE_SHR_UN:
5805                         CHECK_STACK (2);
5806                         ADD_BINOP (*ip);
5807                         /* special case that gives a nice speedup and happens to workaorund a ppc jit but (for the release)
5808                          * later apply the speedup to the left shift as well
5809                          * See BUG# 57957.
5810                          */
5811                         if ((ins->opcode == OP_LSHR_UN) && (ins->type == STACK_I8) 
5812                                         && (ins->inst_right->opcode == OP_ICONST) && (ins->inst_right->inst_c0 == 32)) {
5813                                 ins->opcode = OP_LONG_SHRUN_32;
5814                                 /*g_print ("applied long shr speedup to %s\n", cfg->method->name);*/
5815                                 ip++;
5816                                 break;
5817                         }
5818                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
5819                                 --sp;
5820                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
5821                         }
5822                         ip++;
5823                         break;
5824                 case CEE_NEG:
5825                 case CEE_NOT:
5826                 case CEE_CONV_I1:
5827                 case CEE_CONV_I2:
5828                 case CEE_CONV_I4:
5829                 case CEE_CONV_R4:
5830                 case CEE_CONV_R8:
5831                 case CEE_CONV_U4:
5832                 case CEE_CONV_I8:
5833                 case CEE_CONV_U8:
5834                 case CEE_CONV_OVF_I8:
5835                 case CEE_CONV_OVF_U8:
5836                 case CEE_CONV_R_UN:
5837                         CHECK_STACK (1);
5838                         ADD_UNOP (*ip);
5839                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
5840                                 --sp;
5841                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
5842                         }
5843                         ip++;                   
5844                         break;
5845                 case CEE_CONV_OVF_I4:
5846                 case CEE_CONV_OVF_I1:
5847                 case CEE_CONV_OVF_I2:
5848                 case CEE_CONV_OVF_I:
5849                 case CEE_CONV_OVF_U:
5850                         CHECK_STACK (1);
5851
5852                         if (sp [-1]->type == STACK_R8) {
5853                                 ADD_UNOP (CEE_CONV_OVF_I8);
5854                                 ADD_UNOP (*ip);
5855                         } else {
5856                                 ADD_UNOP (*ip);
5857                         }
5858
5859                         ip++;
5860                         break;
5861                 case CEE_CONV_OVF_U1:
5862                 case CEE_CONV_OVF_U2:
5863                 case CEE_CONV_OVF_U4:
5864                         CHECK_STACK (1);
5865
5866                         if (sp [-1]->type == STACK_R8) {
5867                                 ADD_UNOP (CEE_CONV_OVF_U8);
5868                                 ADD_UNOP (*ip);
5869                         } else {
5870                                 ADD_UNOP (*ip);
5871                         }
5872
5873                         ip++;
5874                         break;
5875                 case CEE_CONV_OVF_I1_UN:
5876                 case CEE_CONV_OVF_I2_UN:
5877                 case CEE_CONV_OVF_I4_UN:
5878                 case CEE_CONV_OVF_I8_UN:
5879                 case CEE_CONV_OVF_U1_UN:
5880                 case CEE_CONV_OVF_U2_UN:
5881                 case CEE_CONV_OVF_U4_UN:
5882                 case CEE_CONV_OVF_U8_UN:
5883                 case CEE_CONV_OVF_I_UN:
5884                 case CEE_CONV_OVF_U_UN:
5885                         CHECK_STACK (1);
5886                         ADD_UNOP (*ip);
5887                         ip++;
5888                         break;
5889                 case CEE_CPOBJ:
5890                         CHECK_OPSIZE (5);
5891                         CHECK_STACK (2);
5892                         token = read32 (ip + 1);
5893                         klass = mini_get_class (method, token, generic_context);
5894                         CHECK_TYPELOAD (klass);
5895                         sp -= 2;
5896                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
5897                                 MonoInst *store, *load;
5898                                 MONO_INST_NEW (cfg, load, CEE_LDIND_REF);
5899                                 load->cil_code = ip;
5900                                 load->inst_i0 = sp [1];
5901                                 load->type = STACK_OBJ;
5902                                 load->klass = klass;
5903                                 load->flags |= ins_flag;
5904                                 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
5905                                 store->cil_code = ip;
5906                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5907                                 MONO_ADD_INS (bblock, store);
5908                                 store->inst_i0 = sp [0];
5909                                 store->inst_i1 = load;
5910                                 store->flags |= ins_flag;
5911                         } else {
5912                                 guint32 align;
5913
5914                                 n = mono_class_value_size (klass, &align);
5915                                 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
5916                                         MonoInst *copy;
5917                                         NEW_MEMCPY (cfg, copy, sp [0], sp [1], n, align);
5918                                         MONO_ADD_INS (bblock, copy);
5919                                 } else {
5920                                         MonoMethod *memcpy_method = get_memcpy_method ();
5921                                         MonoInst *iargs [3];
5922                                         iargs [0] = sp [0];
5923                                         iargs [1] = sp [1];
5924                                         NEW_ICONST (cfg, iargs [2], n);
5925                                         iargs [2]->cil_code = ip;
5926
5927                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
5928                                 }
5929                         }
5930                         ins_flag = 0;
5931                         ip += 5;
5932                         break;
5933                 case CEE_LDOBJ: {
5934                         MonoInst *iargs [3];
5935                         int loc_index = -1;
5936                         int stloc_len = 0;
5937                         guint32 align;
5938
5939                         CHECK_OPSIZE (5);
5940                         CHECK_STACK (1);
5941                         --sp;
5942                         token = read32 (ip + 1);
5943                         klass = mini_get_class (method, token, generic_context);
5944                         CHECK_TYPELOAD (klass);
5945                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
5946                                 MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
5947                                 ins->cil_code = ip;
5948                                 ins->inst_i0 = sp [0];
5949                                 ins->type = STACK_OBJ;
5950                                 ins->klass = klass;
5951                                 ins->flags |= ins_flag;
5952                                 ins_flag = 0;
5953                                 *sp++ = ins;
5954                                 ip += 5;
5955                                 break;
5956                         }
5957
5958                         /* Optimize the common ldobj+stloc combination */
5959                         switch (ip [5]) {
5960                         case CEE_STLOC_S:
5961                                 loc_index = ip [6];
5962                                 stloc_len = 2;
5963                                 break;
5964                         case CEE_STLOC_0:
5965                         case CEE_STLOC_1:
5966                         case CEE_STLOC_2:
5967                         case CEE_STLOC_3:
5968                                 loc_index = ip [5] - CEE_STLOC_0;
5969                                 stloc_len = 1;
5970                                 break;
5971                         default:
5972                                 break;
5973                         }
5974
5975                         if ((loc_index != -1) && ip_in_bb (cfg, bblock, ip + 5)) {
5976                                 CHECK_LOCAL (loc_index);
5977                                 NEW_LOCSTORE (cfg, ins, loc_index, *sp);
5978
5979                                 /* FIXME: handle CEE_STIND_R4 */
5980                                 if (ins->opcode == CEE_STOBJ) {
5981                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5982                                         ins->cil_code = ip;
5983                                         g_assert (ins->opcode == CEE_STOBJ);
5984                                         NEW_LOCLOADA (cfg, ins, loc_index);
5985                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5986                                         ip += 5;
5987                                         ip += stloc_len;
5988                                         break;
5989                                 }
5990                         }
5991
5992                         n = mono_class_value_size (klass, &align);
5993                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
5994                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
5995                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
5996                                 MonoInst *copy;
5997                                 NEW_MEMCPY (cfg, copy, iargs [0], *sp, n, align);
5998                                 MONO_ADD_INS (bblock, copy);
5999                         } else {
6000                                 MonoMethod *memcpy_method = get_memcpy_method ();
6001                                 iargs [1] = *sp;
6002                                 NEW_ICONST (cfg, iargs [2], n);
6003                                 iargs [2]->cil_code = ip;
6004
6005                                 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6006                         }
6007                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
6008                         ++sp;
6009                         ip += 5;
6010                         ins_flag = 0;
6011                         inline_costs += 1;
6012                         break;
6013                 }
6014                 case CEE_LDSTR:
6015                         CHECK_STACK_OVF (1);
6016                         CHECK_OPSIZE (5);
6017                         n = read32 (ip + 1);
6018
6019                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
6020                                 /* FIXME: moving GC */
6021                                 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
6022                                 ins->cil_code = ip;
6023                                 ins->type = STACK_OBJ;
6024                                 ins->klass = mono_defaults.string_class;
6025                                 *sp = ins;
6026                         }
6027                         else if (method->wrapper_type != MONO_WRAPPER_NONE) {
6028                                 int temp;
6029                                 MonoInst *iargs [1];
6030
6031                                 NEW_PCONST (cfg, iargs [0], mono_method_get_wrapper_data (method, n));                          
6032                                 temp = mono_emit_jit_icall (cfg, bblock, mono_string_new_wrapper, iargs, ip);
6033                                 NEW_TEMPLOAD (cfg, *sp, temp);
6034
6035                         } else {
6036
6037                                 if (cfg->opt & MONO_OPT_SHARED) {
6038                                         int temp;
6039                                         MonoInst *iargs [3];
6040                                         MonoInst* domain_var;
6041                                         
6042                                         if (cfg->compile_aot) {
6043                                                 /* FIXME: bug when inlining methods from different assemblies (n is a token valid just in one). */
6044                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
6045                                         }
6046                                         /* avoid depending on undefined C behavior in sequence points */
6047                                         domain_var = mono_get_domainvar (cfg);
6048                                         NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
6049                                         NEW_IMAGECONST (cfg, iargs [1], image);
6050                                         NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
6051                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldstr, iargs, ip);
6052                                         NEW_TEMPLOAD (cfg, *sp, temp);
6053                                         mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
6054                                 } else {
6055                                         if (bblock->out_of_line) {
6056                                                 MonoInst *iargs [2];
6057                                                 int temp;
6058
6059                                                 if (cfg->compile_aot && cfg->method->klass->image == mono_defaults.corlib) {
6060                                                         /* 
6061                                                          * Avoid relocations by using a version of helper_ldstr
6062                                                          * specialized to mscorlib.
6063                                                          */
6064                                                         NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
6065                                                         temp = mono_emit_jit_icall (cfg, bblock, mono_helper_ldstr_mscorlib, iargs, ip);
6066                                                 } else {
6067                                                         /* Avoid creating the string object */
6068                                                         NEW_IMAGECONST (cfg, iargs [0], image);
6069                                                         NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
6070                                                         temp = mono_emit_jit_icall (cfg, bblock, mono_helper_ldstr, iargs, ip);
6071                                                 }
6072                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6073                                         } 
6074                                         else
6075                                         if (cfg->compile_aot) {
6076                                                 NEW_LDSTRCONST (cfg, ins, image, n);
6077                                                 *sp = ins;
6078                                         } 
6079                                         else {
6080                                                 NEW_PCONST (cfg, ins, NULL);
6081                                                 ins->cil_code = ip;
6082                                                 ins->type = STACK_OBJ;
6083                                                 ins->inst_p0 = mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
6084                                                 ins->klass = mono_defaults.string_class;
6085                                                 *sp = ins;
6086                                         }
6087                                 }
6088                         }
6089
6090                         sp++;
6091                         ip += 5;
6092                         break;
6093                 case CEE_NEWOBJ: {
6094                         MonoInst *iargs [2];
6095                         MonoMethodSignature *fsig;
6096                         int temp;
6097
6098                         CHECK_OPSIZE (5);
6099                         token = read32 (ip + 1);
6100                         cmethod = mini_get_method (method, token, NULL, generic_context);
6101                         if (!cmethod)
6102                                 goto load_error;
6103                         fsig = mono_method_get_signature (cmethod, image, token);
6104
6105                         mono_save_token_info (cfg, image, token, cmethod);
6106
6107                         if (!mono_class_init (cmethod->klass))
6108                                 goto load_error;
6109
6110                         if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
6111                                 GENERIC_SHARING_FAILURE (CEE_NEWOBJ);
6112
6113                         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
6114                                 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
6115                                         INLINE_FAILURE;
6116                                 CHECK_CFG_EXCEPTION;
6117                         } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
6118                                 ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
6119                         }
6120
6121                         n = fsig->param_count;
6122                         CHECK_STACK (n);
6123
6124                         /* move the args to allow room for 'this' in the first position */
6125                         while (n--) {
6126                                 --sp;
6127                                 sp [1] = sp [0];
6128                         }
6129
6130                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6131
6132                         if (mini_class_is_system_array (cmethod->klass)) {
6133                                 NEW_METHODCONST (cfg, *sp, cmethod);
6134                                 temp = handle_array_new (cfg, bblock, fsig->param_count, sp, ip);
6135                         } else if (cmethod->string_ctor) {
6136                                 /* we simply pass a null pointer */
6137                                 NEW_PCONST (cfg, *sp, NULL); 
6138                                 /* now call the string ctor */
6139                                 temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, NULL);
6140                         } else {
6141                                 MonoInst* callvirt_this_arg = NULL;
6142                                 
6143                                 if (cmethod->klass->valuetype) {
6144                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
6145                                         temp = iargs [0]->inst_c0;
6146
6147                                         NEW_TEMPLOADA (cfg, *sp, temp);
6148
6149                                         handle_initobj (cfg, bblock, *sp, NULL, cmethod->klass, stack_start, sp);
6150
6151                                         NEW_TEMPLOADA (cfg, *sp, temp);
6152
6153                                         /* 
6154                                          * The code generated by mini_emit_virtual_call () expects
6155                                          * iargs [0] to be a boxed instance, but luckily the vcall
6156                                          * will be transformed into a normal call there.
6157                                          */
6158                                 } else {
6159                                         temp = handle_alloc (cfg, bblock, cmethod->klass, FALSE, ip);
6160                                         NEW_TEMPLOAD (cfg, *sp, temp);
6161                                 }
6162
6163                                 /* Avoid virtual calls to ctors if possible */
6164                                 if (cmethod->klass->marshalbyref)
6165                                         callvirt_this_arg = sp [0];
6166                                 
6167                                 if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
6168                                     mono_method_check_inlining (cfg, cmethod) &&
6169                                     !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE) &&
6170                                     !g_list_find (dont_inline, cmethod)) {
6171                                         int costs;
6172                                         MonoBasicBlock *ebblock;
6173                                         if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, FALSE))) {
6174
6175                                                 ip += 5;
6176                                                 real_offset += 5;
6177                                                 
6178                                                 GET_BBLOCK (cfg, bblock, ip);
6179                                                 ebblock->next_bb = bblock;
6180                                                 link_bblock (cfg, ebblock, bblock);
6181
6182                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6183                                                 sp++;
6184
6185                                                 /* indicates start of a new block, and triggers a load 
6186                                                    of all stack arguments at bb boundarie */
6187                                                 bblock = ebblock;
6188
6189                                                 inline_costs += costs;
6190                                                 break;
6191                                                 
6192                                         } else {
6193                                                 /* Prevent inlining of methods which call other methods */
6194                                                 INLINE_FAILURE;
6195                                                 mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
6196                                         }
6197                                 } else {
6198                                         /* Prevent inlining of methods which call other methods */
6199                                         INLINE_FAILURE;
6200                                         /* now call the actual ctor */
6201                                         mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
6202                                 }
6203                         }
6204
6205                         NEW_TEMPLOAD (cfg, *sp, temp);
6206                         sp++;
6207                         
6208                         ip += 5;
6209                         inline_costs += 5;
6210                         break;
6211                 }
6212                 case CEE_ISINST:
6213                         CHECK_STACK (1);
6214                         --sp;
6215                         CHECK_OPSIZE (5);
6216                         token = read32 (ip + 1);
6217                         klass = mini_get_class (method, token, generic_context);
6218                         CHECK_TYPELOAD (klass);
6219                         if (sp [0]->type != STACK_OBJ)
6220                                 UNVERIFIED;
6221
6222                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
6223                                 GENERIC_SHARING_FAILURE (CEE_ISINST);
6224
6225                         /* Needed by the code generated in inssel.brg */
6226                         mono_get_got_var (cfg);
6227
6228                         if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
6229                         
6230                                 MonoMethod *mono_isinst;
6231                                 MonoInst *iargs [1];
6232                                 MonoBasicBlock *ebblock;
6233                                 int costs;
6234                                 int temp;
6235                                 
6236                                 mono_isinst = mono_marshal_get_isinst (klass); 
6237                                 iargs [0] = sp [0];
6238                                 
6239                                 costs = inline_method (cfg, mono_isinst, mono_method_signature (mono_isinst), bblock, 
6240                                                        iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6241                         
6242                                 g_assert (costs > 0);
6243                                 
6244                                 ip += 5;
6245                                 real_offset += 5;
6246                         
6247                                 GET_BBLOCK (cfg, bblock, ip);
6248                                 ebblock->next_bb = bblock;
6249                                 link_bblock (cfg, ebblock, bblock);
6250
6251                                 temp = iargs [0]->inst_i0->inst_c0;
6252                                 NEW_TEMPLOAD (cfg, *sp, temp);
6253                                 
6254                                 sp++;
6255                                 bblock = ebblock;
6256                                 inline_costs += costs;
6257                         } else {
6258                                 MONO_INST_NEW (cfg, ins, *ip);
6259                                 ins->type = STACK_OBJ;
6260                                 ins->inst_left = *sp;
6261                                 ins->inst_newa_class = klass;
6262                                 ins->klass = klass;
6263                                 ins->cil_code = ip;
6264                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
6265                                 ip += 5;
6266                         }
6267                         break;
6268                 case CEE_UNBOX_ANY: {
6269                         MonoInst *add, *vtoffset;
6270                         MonoInst *iargs [3];
6271                         guint32 align;
6272
6273                         CHECK_STACK (1);
6274                         --sp;
6275                         CHECK_OPSIZE (5);
6276                         token = read32 (ip + 1);
6277                         klass = mini_get_class (method, token, generic_context);
6278                         CHECK_TYPELOAD (klass);
6279
6280                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
6281                                 GENERIC_SHARING_FAILURE (CEE_UNBOX_ANY);
6282
6283                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
6284                                 /* CASTCLASS */
6285                                 if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
6286                                         MonoMethod *mono_castclass;
6287                                         MonoInst *iargs [1];
6288                                         MonoBasicBlock *ebblock;
6289                                         int costs;
6290                                         int temp;
6291                                         
6292                                         mono_castclass = mono_marshal_get_castclass (klass); 
6293                                         iargs [0] = sp [0];
6294                                         
6295                                         costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), bblock, 
6296                                                         iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6297                                 
6298                                         g_assert (costs > 0);
6299                                         
6300                                         ip += 5;
6301                                         real_offset += 5;
6302                                 
6303                                         GET_BBLOCK (cfg, bblock, ip);
6304                                         ebblock->next_bb = bblock;
6305                                         link_bblock (cfg, ebblock, bblock);
6306         
6307                                         temp = iargs [0]->inst_i0->inst_c0;
6308                                         NEW_TEMPLOAD (cfg, *sp, temp);
6309                                         
6310                                         sp++;
6311                                         bblock = ebblock;
6312                                         inline_costs += costs;                          
6313                                 } else {
6314                                         MONO_INST_NEW (cfg, ins, CEE_CASTCLASS);
6315                                         ins->type = STACK_OBJ;
6316                                         ins->inst_left = *sp;
6317                                         ins->klass = klass;
6318                                         ins->inst_newa_class = klass;
6319                                         ins->cil_code = ip;
6320                                         *sp++ = ins;
6321                                         ip += 5;
6322                                 }
6323                                 break;
6324                         }
6325
6326                         if (mono_class_is_nullable (klass)) {
6327                                 int v = handle_unbox_nullable (cfg, bblock, *sp, ip, klass);
6328                                 NEW_TEMPLOAD (cfg, *sp, v);
6329                                 sp ++;
6330                                 ip += 5;
6331                                 break;
6332                         }
6333
6334                         MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
6335                         ins->type = STACK_OBJ;
6336                         ins->inst_left = *sp;
6337                         ins->klass = klass;
6338                         ins->inst_newa_class = klass;
6339                         ins->cil_code = ip;
6340
6341                         MONO_INST_NEW (cfg, add, OP_PADD);
6342                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
6343                         add->inst_left = ins;
6344                         add->inst_right = vtoffset;
6345                         add->type = STACK_MP;
6346                         add->klass = mono_defaults.object_class;
6347                         *sp = add;
6348                         ip += 5;
6349                         /* LDOBJ impl */
6350                         n = mono_class_value_size (klass, &align);
6351                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
6352                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
6353                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
6354                                 MonoInst *copy;
6355                                 NEW_MEMCPY (cfg, copy, iargs [0], *sp, n, align);
6356                                 MONO_ADD_INS (bblock, copy);
6357                         } else {
6358                                 MonoMethod *memcpy_method = get_memcpy_method ();
6359                                 iargs [1] = *sp;
6360                                 NEW_ICONST (cfg, iargs [2], n);
6361                                 iargs [2]->cil_code = ip;
6362
6363                                 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6364                         }
6365                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
6366                         ++sp;
6367                         inline_costs += 2;
6368                         break;
6369                 }
6370                 case CEE_UNBOX: {
6371                         MonoInst *add, *vtoffset;
6372
6373                         CHECK_STACK (1);
6374                         --sp;
6375                         CHECK_OPSIZE (5);
6376                         token = read32 (ip + 1);
6377                         klass = mini_get_class (method, token, generic_context);
6378                         CHECK_TYPELOAD (klass);
6379
6380                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
6381                                 GENERIC_SHARING_FAILURE (CEE_UNBOX);
6382
6383                         if (mono_class_is_nullable (klass)) {
6384                                 int v = handle_unbox_nullable (cfg, bblock, *sp, ip, klass);
6385                                 NEW_TEMPLOAD (cfg, *sp, v);
6386                                 sp ++;
6387                                 ip += 5;
6388                                 break;
6389                         }
6390
6391                         /* Needed by the code generated in inssel.brg */
6392                         mono_get_got_var (cfg);
6393
6394                         MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
6395                         ins->type = STACK_OBJ;
6396                         ins->inst_left = *sp;
6397                         ins->klass = klass;
6398                         ins->inst_newa_class = klass;
6399                         ins->cil_code = ip;
6400
6401                         MONO_INST_NEW (cfg, add, OP_PADD);
6402                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
6403                         add->inst_left = ins;
6404                         add->inst_right = vtoffset;
6405                         add->type = STACK_MP;
6406                         add->klass = klass;
6407                         *sp++ = add;
6408                         ip += 5;
6409                         inline_costs += 2;
6410                         break;
6411                 }
6412                 case CEE_CASTCLASS:
6413                         CHECK_STACK (1);
6414                         --sp;
6415                         CHECK_OPSIZE (5);
6416                         token = read32 (ip + 1);
6417                         klass = mini_get_class (method, token, generic_context);
6418                         CHECK_TYPELOAD (klass);
6419                         if (sp [0]->type != STACK_OBJ)
6420                                 UNVERIFIED;
6421
6422                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
6423                                 GENERIC_SHARING_FAILURE (CEE_CASTCLASS);
6424
6425                         /* Needed by the code generated in inssel.brg */
6426                         mono_get_got_var (cfg);
6427                 
6428                         if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
6429                                 
6430                                 MonoMethod *mono_castclass;
6431                                 MonoInst *iargs [1];
6432                                 MonoBasicBlock *ebblock;
6433                                 int costs;
6434                                 int temp;
6435                                 
6436                                 mono_castclass = mono_marshal_get_castclass (klass); 
6437                                 iargs [0] = sp [0];
6438                                 
6439                                 costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), bblock, 
6440                                                 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6441                         
6442                                 g_assert (costs > 0);
6443                                 
6444                                 ip += 5;
6445                                 real_offset += 5;
6446                         
6447                                 GET_BBLOCK (cfg, bblock, ip);
6448                                 ebblock->next_bb = bblock;
6449                                 link_bblock (cfg, ebblock, bblock);
6450
6451                                 temp = iargs [0]->inst_i0->inst_c0;
6452                                 NEW_TEMPLOAD (cfg, *sp, temp);
6453                                 
6454                                 sp++;
6455                                 bblock = ebblock;
6456                                 inline_costs += costs;
6457                         } else {
6458                                 MONO_INST_NEW (cfg, ins, *ip);
6459                                 ins->type = STACK_OBJ;
6460                                 ins->inst_left = *sp;
6461                                 ins->klass = klass;
6462                                 ins->inst_newa_class = klass;
6463                                 ins->cil_code = ip;
6464                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
6465                                 ip += 5;
6466                         }
6467                         break;
6468                 case CEE_THROW:
6469                         CHECK_STACK (1);
6470                         MONO_INST_NEW (cfg, ins, OP_THROW);
6471                         --sp;
6472                         ins->inst_left = *sp;
6473                         ins->cil_code = ip++;
6474                         bblock->out_of_line = TRUE;
6475                         MONO_ADD_INS (bblock, ins);
6476                         MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
6477                         ins->cil_code = ip - 1;
6478                         MONO_ADD_INS (bblock, ins);
6479                         sp = stack_start;
6480                         
6481                         link_bblock (cfg, bblock, end_bblock);
6482                         start_new_bblock = 1;
6483                         break;
6484                 case CEE_LDFLD:
6485                 case CEE_LDFLDA:
6486                 case CEE_STFLD: {
6487                         MonoInst *offset_ins;
6488                         MonoClassField *field;
6489                         MonoBasicBlock *ebblock;
6490                         int costs;
6491                         guint foffset;
6492
6493                         if (*ip == CEE_STFLD) {
6494                                 CHECK_STACK (2);
6495                                 sp -= 2;
6496                         } else {
6497                                 CHECK_STACK (1);
6498                                 --sp;
6499                         }
6500                         if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
6501                                 UNVERIFIED;
6502                         if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
6503                                 UNVERIFIED;
6504                         CHECK_OPSIZE (5);
6505                         token = read32 (ip + 1);
6506                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6507                                 field = mono_method_get_wrapper_data (method, token);
6508                                 klass = field->parent;
6509                         } else {
6510                                 field = mono_field_from_token (image, token, &klass, generic_context);
6511                         }
6512                         if (!field)
6513                                 goto load_error;
6514                         mono_class_init (klass);
6515                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
6516                                 FIELD_ACCESS_FAILURE;
6517
6518                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
6519                         /* FIXME: mark instructions for use in SSA */
6520                         if (*ip == CEE_STFLD) {
6521                                 if (target_type_is_incompatible (cfg, field->type, sp [1]))
6522                                         UNVERIFIED;
6523                                 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
6524                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
6525                                         MonoInst *iargs [5];
6526
6527                                         iargs [0] = sp [0];
6528                                         NEW_CLASSCONST (cfg, iargs [1], klass);
6529                                         NEW_FIELDCONST (cfg, iargs [2], field);
6530                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
6531                                                     field->offset);
6532                                         iargs [4] = sp [1];
6533
6534                                         if (cfg->opt & MONO_OPT_INLINE) {
6535                                                 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), bblock, 
6536                                                                 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6537                                                 g_assert (costs > 0);
6538                                                       
6539                                                 ip += 5;
6540                                                 real_offset += 5;
6541
6542                                                 GET_BBLOCK (cfg, bblock, ip);
6543                                                 ebblock->next_bb = bblock;
6544                                                 link_bblock (cfg, ebblock, bblock);
6545
6546                                                 /* indicates start of a new block, and triggers a load 
6547                                                    of all stack arguments at bb boundarie */
6548                                                 bblock = ebblock;
6549
6550                                                 inline_costs += costs;
6551                                                 break;
6552                                         } else {
6553                                                 mono_emit_method_call_spilled (cfg, bblock, stfld_wrapper, mono_method_signature (stfld_wrapper), iargs, ip, NULL);
6554                                         }
6555 #if HAVE_WRITE_BARRIERS
6556                                 } else if (mini_type_to_stind (cfg, field->type) == CEE_STIND_REF) {
6557                                         /* insert call to write barrier */
6558                                         MonoMethod *write_barrier = mono_marshal_get_write_barrier ();
6559                                         MonoInst *iargs [2];
6560                                         NEW_ICONST (cfg, offset_ins, foffset);
6561                                         MONO_INST_NEW (cfg, ins, OP_PADD);
6562                                         ins->cil_code = ip;
6563                                         ins->inst_left = *sp;
6564                                         ins->inst_right = offset_ins;
6565                                         ins->type = STACK_MP;
6566                                         ins->klass = mono_defaults.object_class;
6567                                         iargs [0] = ins;
6568                                         iargs [1] = sp [1];
6569                                         mono_emit_method_call_spilled (cfg, bblock, write_barrier, mono_method_signature (write_barrier), iargs, ip, NULL);
6570 #endif
6571 #ifdef MONO_ARCH_SOFT_FLOAT
6572                                 } else if (mini_type_to_stind (cfg, field->type) == CEE_STIND_R4) {
6573                                         NEW_ICONST (cfg, offset_ins, foffset);
6574                                         MONO_INST_NEW (cfg, ins, OP_PADD);
6575                                         ins->cil_code = ip;
6576                                         ins->inst_left = *sp;
6577                                         ins->inst_right = offset_ins;
6578                                         ins->type = STACK_MP;
6579                                         ins->klass = mono_defaults.object_class;
6580                                         handle_store_float (cfg, bblock, ins, sp [1], ip);
6581 #endif
6582                                 } else {
6583                                         MonoInst *store;
6584                                         NEW_ICONST (cfg, offset_ins, foffset);
6585                                         MONO_INST_NEW (cfg, ins, OP_PADD);
6586                                         ins->cil_code = ip;
6587                                         ins->inst_left = *sp;
6588                                         ins->inst_right = offset_ins;
6589                                         ins->type = STACK_MP;
6590
6591                                         MONO_INST_NEW (cfg, store, mini_type_to_stind (cfg, field->type));
6592                                         store->cil_code = ip;
6593                                         store->inst_left = ins;
6594                                         store->inst_right = sp [1];
6595                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6596                                         store->flags |= ins_flag;
6597                                         ins_flag = 0;
6598                                         if (store->opcode == CEE_STOBJ) {
6599                                                 handle_stobj (cfg, bblock, ins, sp [1], ip, 
6600                                                               mono_class_from_mono_type (field->type), FALSE, FALSE, TRUE);
6601                                         } else
6602                                                 MONO_ADD_INS (bblock, store);
6603                                 }
6604                         } else {
6605                                 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
6606                                         MonoMethod *wrapper = (*ip == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type); 
6607                                         MonoInst *iargs [4];
6608                                         int temp;
6609                                         
6610                                         iargs [0] = sp [0];
6611                                         NEW_CLASSCONST (cfg, iargs [1], klass);
6612                                         NEW_FIELDCONST (cfg, iargs [2], field);
6613                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
6614                                         if ((cfg->opt & MONO_OPT_INLINE) && !MONO_TYPE_ISSTRUCT (mono_method_signature (wrapper)->ret)) {
6615                                                 costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), bblock, 
6616                                                                 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6617                                                 g_assert (costs > 0);
6618                                                       
6619                                                 ip += 5;
6620                                                 real_offset += 5;
6621
6622                                                 GET_BBLOCK (cfg, bblock, ip);
6623                                                 ebblock->next_bb = bblock;
6624                                                 link_bblock (cfg, ebblock, bblock);
6625
6626                                                 temp = iargs [0]->inst_i0->inst_c0;
6627
6628                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6629                                                 sp++;
6630
6631                                                 /* indicates start of a new block, and triggers a load of
6632                                                    all stack arguments at bb boundarie */
6633                                                 bblock = ebblock;
6634                                                 
6635                                                 inline_costs += costs;
6636                                                 break;
6637                                         } else {
6638                                                 temp = mono_emit_method_call_spilled (cfg, bblock, wrapper, mono_method_signature (wrapper), iargs, ip, NULL);
6639                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6640                                                 sp++;
6641                                         }
6642                                 } else {
6643                                         NEW_ICONST (cfg, offset_ins, foffset);
6644                                         MONO_INST_NEW (cfg, ins, OP_PADD);
6645                                         ins->cil_code = ip;
6646                                         ins->inst_left = *sp;
6647                                         ins->inst_right = offset_ins;
6648                                         ins->type = STACK_MP;
6649
6650                                         if (*ip == CEE_LDFLDA) {
6651                                                 ins->klass = mono_class_from_mono_type (field->type);
6652                                                 *sp++ = ins;
6653                                         } else {
6654                                                 MonoInst *load;
6655                                                 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, field->type));
6656                                                 type_to_eval_stack_type (cfg, field->type, load);
6657                                                 load->cil_code = ip;
6658                                                 load->inst_left = ins;
6659                                                 load->flags |= ins_flag;
6660                                                 ins_flag = 0;
6661 #ifdef MONO_ARCH_SOFT_FLOAT
6662                                                 if (mini_type_to_ldind (cfg, field->type) == CEE_LDIND_R4) {
6663                                                         int temp;
6664                                                         temp = handle_load_float (cfg, bblock, ins, ip);
6665                                                         NEW_TEMPLOAD (cfg, *sp, temp);
6666                                                         sp++;
6667                                                 } else
6668 #endif
6669                                                 *sp++ = load;
6670                                         }
6671                                 }
6672                         }
6673                         ip += 5;
6674                         break;
6675                 }
6676                 case CEE_LDSFLD:
6677                 case CEE_LDSFLDA:
6678                 case CEE_STSFLD: {
6679                         MonoClassField *field;
6680                         gpointer addr = NULL;
6681
6682                         CHECK_OPSIZE (5);
6683                         token = read32 (ip + 1);
6684                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
6685                                 field = mono_method_get_wrapper_data (method, token);
6686                                 klass = field->parent;
6687                         }
6688                         else
6689                                 field = mono_field_from_token (image, token, &klass, generic_context);
6690                         if (!field)
6691                                 goto load_error;
6692                         mono_class_init (klass);
6693                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
6694                                 FIELD_ACCESS_FAILURE;
6695
6696                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
6697                                 GENERIC_SHARING_FAILURE (*ip);
6698
6699                         g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL));
6700
6701                         if ((*ip) == CEE_STSFLD)
6702                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
6703
6704                         /* The special_static_fields field is init'd in mono_class_vtable, so it needs
6705                          * to be called here.
6706                          */
6707                         if (!(cfg->opt & MONO_OPT_SHARED))
6708                                 mono_class_vtable (cfg->domain, klass);
6709                         mono_domain_lock (cfg->domain);
6710                         if (cfg->domain->special_static_fields)
6711                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
6712                         mono_domain_unlock (cfg->domain);
6713
6714                         if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
6715                                 int temp;
6716                                 MonoInst *iargs [2];
6717                                 MonoInst *domain_var;
6718                                 
6719                                 g_assert (field->parent);
6720                                 /* avoid depending on undefined C behavior in sequence points */
6721                                 domain_var = mono_get_domainvar (cfg);
6722                                 NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
6723                                 NEW_FIELDCONST (cfg, iargs [1], field);
6724                                 temp = mono_emit_jit_icall (cfg, bblock, mono_class_static_field_address, iargs, ip);
6725                                 NEW_TEMPLOAD (cfg, ins, temp);
6726                         } else {
6727                                 MonoVTable *vtable;
6728                                 vtable = mono_class_vtable (cfg->domain, klass);
6729                                 if (!addr) {
6730                                         if (mini_field_access_needs_cctor_run (cfg, method, vtable) && !(g_slist_find (class_inits, vtable))) {
6731                                                 guint8 *tramp = mono_create_class_init_trampoline (vtable);
6732                                                 mono_emit_native_call (cfg, bblock, tramp, 
6733                                                                                            helper_sig_class_init_trampoline,
6734                                                                                            NULL, ip, FALSE, FALSE);
6735                                                 if (cfg->verbose_level > 2)
6736                                                         g_print ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, field->name);
6737                                                 class_inits = g_slist_prepend (class_inits, vtable);
6738                                         } else {
6739                                                 if (cfg->run_cctors) {
6740                                                         /* This makes so that inline cannot trigger */
6741                                                         /* .cctors: too many apps depend on them */
6742                                                         /* running with a specific order... */
6743                                                         if (! vtable->initialized)
6744                                                                 INLINE_FAILURE;
6745                                                         mono_runtime_class_init (vtable);
6746                                                 }
6747                                         }
6748                                         addr = (char*)vtable->data + field->offset;
6749
6750                                         if (cfg->compile_aot)
6751                                                 NEW_SFLDACONST (cfg, ins, field);
6752                                         else
6753                                                 NEW_PCONST (cfg, ins, addr);
6754                                         ins->cil_code = ip;
6755                                 } else {
6756                                         /* 
6757                                          * insert call to mono_threads_get_static_data (GPOINTER_TO_UINT (addr)) 
6758                                          * This could be later optimized to do just a couple of
6759                                          * memory dereferences with constant offsets.
6760                                          */
6761                                         int temp;
6762                                         MonoInst *iargs [1];
6763                                         NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
6764                                         temp = mono_emit_jit_icall (cfg, bblock, mono_get_special_static_data, iargs, ip);
6765                                         NEW_TEMPLOAD (cfg, ins, temp);
6766                                 }
6767                         }
6768
6769                         /* FIXME: mark instructions for use in SSA */
6770                         if (*ip == CEE_LDSFLDA) {
6771                                 ins->klass = mono_class_from_mono_type (field->type);
6772                                 *sp++ = ins;
6773                         } else if (*ip == CEE_STSFLD) {
6774                                 MonoInst *store;
6775                                 CHECK_STACK (1);
6776                                 sp--;
6777                                 MONO_INST_NEW (cfg, store, mini_type_to_stind (cfg, field->type));
6778                                 store->cil_code = ip;
6779                                 store->inst_left = ins;
6780                                 store->inst_right = sp [0];
6781                                 store->flags |= ins_flag;
6782                                 ins_flag = 0;
6783
6784 #ifdef MONO_ARCH_SOFT_FLOAT
6785                                 if (store->opcode == CEE_STIND_R4)
6786                                         handle_store_float (cfg, bblock, ins, sp [0], ip);
6787                                 else
6788 #endif
6789                                 if (store->opcode == CEE_STOBJ) {
6790                                         handle_stobj (cfg, bblock, ins, sp [0], ip, mono_class_from_mono_type (field->type), FALSE, FALSE, FALSE);
6791                                 } else
6792                                         MONO_ADD_INS (bblock, store);
6793                         } else {
6794                                 gboolean is_const = FALSE;
6795                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
6796                                 if (!((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) && 
6797                                     vtable->initialized && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY)) {
6798                                         gpointer addr = (char*)vtable->data + field->offset;
6799                                         int ro_type = field->type->type;
6800                                         if (ro_type == MONO_TYPE_VALUETYPE && field->type->data.klass->enumtype) {
6801                                                 ro_type = field->type->data.klass->enum_basetype->type;
6802                                         }
6803                                         /* g_print ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, field->name);*/
6804                                         is_const = TRUE;
6805                                         switch (ro_type) {
6806                                         case MONO_TYPE_BOOLEAN:
6807                                         case MONO_TYPE_U1:
6808                                                 NEW_ICONST (cfg, *sp, *((guint8 *)addr));
6809                                                 sp++;
6810                                                 break;
6811                                         case MONO_TYPE_I1:
6812                                                 NEW_ICONST (cfg, *sp, *((gint8 *)addr));
6813                                                 sp++;
6814                                                 break;                                          
6815                                         case MONO_TYPE_CHAR:
6816                                         case MONO_TYPE_U2:
6817                                                 NEW_ICONST (cfg, *sp, *((guint16 *)addr));
6818                                                 sp++;
6819                                                 break;
6820                                         case MONO_TYPE_I2:
6821                                                 NEW_ICONST (cfg, *sp, *((gint16 *)addr));
6822                                                 sp++;
6823                                                 break;
6824                                                 break;
6825                                         case MONO_TYPE_I4:
6826                                                 NEW_ICONST (cfg, *sp, *((gint32 *)addr));
6827                                                 sp++;
6828                                                 break;                                          
6829                                         case MONO_TYPE_U4:
6830                                                 NEW_ICONST (cfg, *sp, *((guint32 *)addr));
6831                                                 sp++;
6832                                                 break;
6833 #ifndef HAVE_MOVING_COLLECTOR
6834                                         case MONO_TYPE_I:
6835                                         case MONO_TYPE_U:
6836                                         case MONO_TYPE_STRING:
6837                                         case MONO_TYPE_OBJECT:
6838                                         case MONO_TYPE_CLASS:
6839                                         case MONO_TYPE_SZARRAY:
6840                                         case MONO_TYPE_PTR:
6841                                         case MONO_TYPE_FNPTR:
6842                                         case MONO_TYPE_ARRAY:
6843                                                 NEW_PCONST (cfg, *sp, *((gpointer *)addr));
6844                                                 type_to_eval_stack_type (cfg, field->type, *sp);
6845                                                 sp++;
6846                                                 break;
6847 #endif
6848                                         case MONO_TYPE_I8:
6849                                         case MONO_TYPE_U8:
6850                                                 MONO_INST_NEW (cfg, *sp, OP_I8CONST);
6851                                                 sp [0]->type = STACK_I8;
6852                                                 sp [0]->inst_l = *((gint64 *)addr);
6853                                                 sp++;
6854                                                 break;
6855                                         case MONO_TYPE_R4:
6856                                         case MONO_TYPE_R8:
6857                                         case MONO_TYPE_VALUETYPE:
6858                                         default:
6859                                                 is_const = FALSE;
6860                                                 break;
6861                                         }
6862                                 }
6863
6864                                 if (!is_const) {
6865                                         MonoInst *load;
6866                                         CHECK_STACK_OVF (1);
6867                                         MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, field->type));
6868                                         type_to_eval_stack_type (cfg, field->type, load);
6869                                         load->cil_code = ip;
6870                                         load->inst_left = ins;
6871                                         *sp++ = load;
6872                                         load->flags |= ins_flag;
6873                                         ins_flag = 0;
6874                                         /* fixme: dont see the problem why this does not work */
6875                                         //cfg->disable_aot = TRUE;
6876                                 }
6877                         }
6878                         ip += 5;
6879                         break;
6880                 }
6881                 case CEE_STOBJ:
6882                         CHECK_STACK (2);
6883                         sp -= 2;
6884                         CHECK_OPSIZE (5);
6885                         token = read32 (ip + 1);
6886                         klass = mini_get_class (method, token, generic_context);
6887                         CHECK_TYPELOAD (klass);
6888                         n = mini_type_to_stind (cfg, &klass->byval_arg);
6889                         /* FIXME: handle CEE_STIND_R4 */
6890                         if (n == CEE_STOBJ) {
6891                                 handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE, TRUE);
6892                         } else {
6893                                 /* FIXME: should check item at sp [1] is compatible with the type of the store. */
6894                                 MonoInst *store;
6895                                 MONO_INST_NEW (cfg, store, n);
6896                                 store->cil_code = ip;
6897                                 store->inst_left = sp [0];
6898                                 store->inst_right = sp [1];
6899                                 store->flags |= ins_flag;
6900                                 MONO_ADD_INS (bblock, store);
6901                         }
6902                         ins_flag = 0;
6903                         ip += 5;
6904                         inline_costs += 1;
6905                         break;
6906                 case CEE_BOX: {
6907                         MonoInst *val;
6908
6909                         CHECK_STACK (1);
6910                         --sp;
6911                         val = *sp;
6912                         CHECK_OPSIZE (5);
6913                         token = read32 (ip + 1);
6914                         klass = mini_get_class (method, token, generic_context);
6915                         CHECK_TYPELOAD (klass);
6916
6917                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
6918                                 GENERIC_SHARING_FAILURE (CEE_BOX);
6919
6920                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
6921                                 *sp++ = val;
6922                                 ip += 5;
6923                                 break;
6924                         }
6925                         if (klass == mono_defaults.void_class)
6926                                 UNVERIFIED;
6927                         if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
6928                                 UNVERIFIED;
6929                         /* frequent check in generic code: box (struct), brtrue */
6930                         if (!mono_class_is_nullable (klass) &&
6931                             ip + 5 < end && ip_in_bb (cfg, bblock, ip + 5) && (ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S)) {
6932                                 /*g_print ("box-brtrue opt at 0x%04x in %s\n", real_offset, method->name);*/
6933                                 MONO_INST_NEW (cfg, ins, CEE_POP);
6934                                 MONO_ADD_INS (bblock, ins);
6935                                 ins->cil_code = ip;
6936                                 ins->inst_i0 = *sp;
6937                                 ip += 5;
6938                                 MONO_INST_NEW (cfg, ins, OP_BR);
6939                                 ins->cil_code = ip;
6940                                 MONO_ADD_INS (bblock, ins);
6941                                 if (*ip == CEE_BRTRUE_S) {
6942                                         CHECK_OPSIZE (2);
6943                                         ip++;
6944                                         target = ip + 1 + (signed char)(*ip);
6945                                         ip++;
6946                                 } else {
6947                                         CHECK_OPSIZE (5);
6948                                         ip++;
6949                                         target = ip + 4 + (gint)(read32 (ip));
6950                                         ip += 4;
6951                                 }
6952                                 GET_BBLOCK (cfg, tblock, target);
6953                                 link_bblock (cfg, bblock, tblock);
6954                                 CHECK_BBLOCK (target, ip, tblock);
6955                                 ins->inst_target_bb = tblock;
6956                                 GET_BBLOCK (cfg, tblock, ip);
6957                                 link_bblock (cfg, bblock, tblock);
6958                                 if (sp != stack_start) {
6959                                         handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6960                                         sp = stack_start;
6961                                         CHECK_UNVERIFIABLE (cfg);
6962                                 }
6963                                 start_new_bblock = 1;
6964                                 break;
6965                         }
6966                         *sp++ = handle_box (cfg, bblock, val, ip, klass);
6967                         ip += 5;
6968                         inline_costs += 1;
6969                         break;
6970                 }
6971                 case CEE_NEWARR: {
6972                         gboolean shared_access = FALSE;
6973
6974                         CHECK_STACK (1);
6975                         --sp;
6976
6977                         CHECK_OPSIZE (5);
6978                         token = read32 (ip + 1);
6979
6980                         /* allocate the domainvar - becaus this is used in decompose_foreach */
6981                         if (cfg->opt & MONO_OPT_SHARED) {
6982                                 mono_get_domainvar (cfg);
6983                                 /* LAME-IR: Mark it as used since otherwise it will be optimized away */
6984                                 cfg->domainvar->flags |= MONO_INST_VOLATILE;
6985                         }
6986
6987                         /* Ditto */
6988                         mono_get_got_var (cfg);
6989
6990                         klass = mini_get_class (method, token, generic_context);
6991                         CHECK_TYPELOAD (klass);
6992
6993                         if (cfg->generic_sharing_context) {
6994                                 int context_used = mono_class_check_context_used (klass);
6995
6996                                 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD || klass->valuetype)
6997                                         GENERIC_SHARING_FAILURE (CEE_NEWARR);
6998
6999                                 if (context_used) {
7000                                         if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
7001                                                 shared_access = TRUE;
7002                                         else
7003                                                 GENERIC_SHARING_FAILURE (CEE_NEWARR);
7004                                 }
7005                         }
7006
7007                         if (shared_access) {
7008                                 MonoInst *this, *rgctx;
7009                                 MonoInst *args [3];
7010                                 int temp;
7011
7012                                 /* domain */
7013                                 NEW_DOMAINCONST (cfg, args [0]);
7014
7015                                 /* klass */
7016                                 NEW_ARGLOAD (cfg, this, 0);
7017                                 rgctx = get_runtime_generic_context_from_this (cfg, this, ip);
7018                                 args [1] = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
7019                                         token, generic_context, rgctx, MINI_RGCTX_KLASS, ip);
7020
7021                                 /* array len */
7022                                 args [2] = *sp;
7023
7024                                 temp = mono_emit_jit_icall (cfg, bblock, mono_array_new, args, ip);
7025                                 NEW_TEMPLOAD (cfg, ins, temp);
7026                         } else {
7027                                 MONO_INST_NEW (cfg, ins, *ip);
7028                                 ins->cil_code = ip;
7029                                 ins->inst_newa_class = klass;
7030                                 ins->inst_newa_len = *sp;
7031                                 ins->type = STACK_OBJ;
7032                                 ins->klass = mono_array_class_get (klass, 1);
7033                         }
7034
7035                         ip += 5;
7036                         *sp++ = ins;
7037                         /* 
7038                          * we store the object so calls to create the array are not interleaved
7039                          * with the arguments of other calls.
7040                          */
7041                         if (1) {
7042                                 MonoInst *store, *temp, *load;
7043                                 const char *data_ptr;
7044                                 int data_size = 0;
7045                                 --sp;
7046                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
7047                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
7048                                 store->cil_code = ins->cil_code;
7049                                 MONO_ADD_INS (bblock, store);
7050                                 /* 
7051                                  * we inline/optimize the initialization sequence if possible.
7052                                  * we should also allocate the array as not cleared, since we spend as much time clearing to 0 as initializing
7053                                  * for small sizes open code the memcpy
7054                                  * ensure the rva field is big enough
7055                                  */
7056                                 if ((cfg->opt & MONO_OPT_INTRINS) && ip_in_bb (cfg, bblock, ip + 6) && (data_ptr = initialize_array_data (method, cfg->compile_aot, ip, ins, &data_size))) {
7057                                         MonoMethod *memcpy_method = get_memcpy_method ();
7058                                         MonoInst *data_offset, *add;
7059                                         MonoInst *iargs [3];
7060                                         NEW_ICONST (cfg, iargs [2], data_size);
7061                                         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
7062                                         load->cil_code = ins->cil_code;
7063                                         NEW_ICONST (cfg, data_offset, G_STRUCT_OFFSET (MonoArray, vector));
7064                                         MONO_INST_NEW (cfg, add, OP_PADD);
7065                                         add->inst_left = load;
7066                                         add->inst_right = data_offset;
7067                                         add->cil_code = ip;
7068                                         iargs [0] = add;
7069                                         if (cfg->compile_aot) {
7070                                                 NEW_AOTCONST_TOKEN (cfg, iargs [1], MONO_PATCH_INFO_RVA, method->klass->image, GPOINTER_TO_UINT(data_ptr), STACK_PTR, NULL);
7071                                         } else {
7072                                                 NEW_PCONST (cfg, iargs [1], (char*)data_ptr);
7073                                         }
7074                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
7075                                         ip += 11;
7076                                 }
7077                                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
7078                                 load->cil_code = ins->cil_code;
7079                                 *sp++ = load;
7080                         }
7081                         inline_costs += 1;
7082                         break;
7083                 }
7084                 case CEE_LDLEN:
7085                         CHECK_STACK (1);
7086                         --sp;
7087                         if (sp [0]->type != STACK_OBJ)
7088                                 UNVERIFIED;
7089                         MONO_INST_NEW (cfg, ins, *ip);
7090                         ins->cil_code = ip++;
7091                         ins->inst_left = *sp;
7092                         ins->type = STACK_PTR;
7093                         *sp++ = ins;
7094                         break;
7095                 case CEE_LDELEMA:
7096                         CHECK_STACK (2);
7097                         sp -= 2;
7098                         CHECK_OPSIZE (5);
7099                         if (sp [0]->type != STACK_OBJ)
7100                                 UNVERIFIED;
7101
7102                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
7103                         CHECK_TYPELOAD (klass);
7104                         /* we need to make sure that this array is exactly the type it needs
7105                          * to be for correctness. the wrappers are lax with their usage
7106                          * so we need to ignore them here
7107                          */
7108                         if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE) {
7109                                 MonoInst* check;
7110
7111                                 /* Needed by the code generated in inssel.brg */
7112                                 mono_get_got_var (cfg);
7113
7114                                 MONO_INST_NEW (cfg, check, OP_CHECK_ARRAY_TYPE);
7115                                 check->cil_code = ip;
7116                                 check->klass = klass;
7117                                 check->inst_left = sp [0];
7118                                 check->type = STACK_OBJ;
7119                                 check->klass = klass;
7120                                 sp [0] = check;
7121                         }
7122                         
7123                         mono_class_init (klass);
7124                         NEW_LDELEMA (cfg, ins, sp, klass);
7125                         ins->cil_code = ip;
7126                         *sp++ = ins;
7127                         ip += 5;
7128                         break;
7129                 case CEE_LDELEM_ANY: {
7130                         MonoInst *load;
7131                         CHECK_STACK (2);
7132                         sp -= 2;
7133                         if (sp [0]->type != STACK_OBJ)
7134                                 UNVERIFIED;
7135                         CHECK_OPSIZE (5);
7136                         token = read32 (ip + 1);
7137                         klass = mini_get_class (method, token, generic_context);
7138                         CHECK_TYPELOAD (klass);
7139                         mono_class_init (klass);
7140                         NEW_LDELEMA (cfg, load, sp, klass);
7141                         load->cil_code = ip;
7142                         MONO_INST_NEW (cfg, ins, mini_type_to_ldind (cfg, &klass->byval_arg));
7143                         ins->cil_code = ip;
7144                         ins->inst_left = load;
7145                         *sp++ = ins;
7146                         type_to_eval_stack_type (cfg, &klass->byval_arg, ins);
7147                         ip += 5;
7148                         break;
7149                 }
7150                 case CEE_LDELEM_I1:
7151                 case CEE_LDELEM_U1:
7152                 case CEE_LDELEM_I2:
7153                 case CEE_LDELEM_U2:
7154                 case CEE_LDELEM_I4:
7155                 case CEE_LDELEM_U4:
7156                 case CEE_LDELEM_I8:
7157                 case CEE_LDELEM_I:
7158                 case CEE_LDELEM_R4:
7159                 case CEE_LDELEM_R8:
7160                 case CEE_LDELEM_REF: {
7161                         MonoInst *load;
7162                         /*
7163                          * translate to:
7164                          * ldind.x (ldelema (array, index))
7165                          * ldelema does the bounds check
7166                          */
7167                         CHECK_STACK (2);
7168                         sp -= 2;
7169                         if (sp [0]->type != STACK_OBJ)
7170                                 UNVERIFIED;
7171                         klass = array_access_to_klass (*ip, sp [0]);
7172                         NEW_LDELEMA (cfg, load, sp, klass);
7173                         load->cil_code = ip;
7174 #ifdef MONO_ARCH_SOFT_FLOAT
7175                         if (*ip == CEE_LDELEM_R4) {
7176                                 int temp;
7177                                 temp = handle_load_float (cfg, bblock, load, ip);
7178                                 NEW_TEMPLOAD (cfg, *sp, temp);
7179                                 sp++;
7180                                 ++ip;
7181                                 break;
7182                         }
7183 #endif
7184                         MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
7185                         ins->cil_code = ip;
7186                         ins->inst_left = load;
7187                         *sp++ = ins;
7188                         ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
7189                         ins->klass = klass;
7190                         ++ip;
7191                         break;
7192                 }
7193                 case CEE_STELEM_I:
7194                 case CEE_STELEM_I1:
7195                 case CEE_STELEM_I2:
7196                 case CEE_STELEM_I4:
7197                 case CEE_STELEM_I8:
7198                 case CEE_STELEM_R4:
7199                 case CEE_STELEM_R8: {
7200                         MonoInst *load;
7201                         /*
7202                          * translate to:
7203                          * stind.x (ldelema (array, index), val)
7204                          * ldelema does the bounds check
7205                          */
7206                         CHECK_STACK (3);
7207                         sp -= 3;
7208                         if (sp [0]->type != STACK_OBJ)
7209                                 UNVERIFIED;
7210                         klass = array_access_to_klass (*ip, sp [0]);
7211                         NEW_LDELEMA (cfg, load, sp, klass);
7212                         load->cil_code = ip;
7213 #ifdef MONO_ARCH_SOFT_FLOAT
7214                         if (*ip == CEE_STELEM_R4) {
7215                                 handle_store_float (cfg, bblock, load, sp [2], ip);
7216                                 ip++;
7217                                 break;
7218                         }
7219 #endif
7220                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
7221                         ins->cil_code = ip;
7222                         ins->inst_left = load;
7223                         ins->inst_right = sp [2];
7224                         ++ip;
7225                         handle_loaded_temps (cfg, bblock, stack_start, sp);
7226                         MONO_ADD_INS (bblock, ins);
7227                         inline_costs += 1;
7228                         break;
7229                 }
7230                 case CEE_STELEM_ANY: {
7231                         MonoInst *load;
7232                         /*
7233                          * translate to:
7234                          * stind.x (ldelema (array, index), val)
7235                          * ldelema does the bounds check
7236                          */
7237                         CHECK_STACK (3);
7238                         sp -= 3;
7239                         if (sp [0]->type != STACK_OBJ)
7240                                 UNVERIFIED;
7241                         CHECK_OPSIZE (5);
7242                         token = read32 (ip + 1);
7243                         klass = mini_get_class (method, token, generic_context);
7244                         CHECK_TYPELOAD (klass);
7245                         mono_class_init (klass);
7246                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
7247                                 /* storing a NULL doesn't need any of the complex checks in stelemref */
7248                                 if (sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL) {
7249                                         MonoInst *load;
7250                                         NEW_LDELEMA (cfg, load, sp, mono_defaults.object_class);
7251                                         load->cil_code = ip;
7252                                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
7253                                         ins->cil_code = ip;
7254                                         ins->inst_left = load;
7255                                         ins->inst_right = sp [2];
7256                                         MONO_ADD_INS (bblock, ins);
7257                                 } else {
7258                                         MonoMethod* helper = mono_marshal_get_stelemref ();
7259                                         MonoInst *iargs [3];
7260                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
7261
7262                                         iargs [2] = sp [2];
7263                                         iargs [1] = sp [1];
7264                                         iargs [0] = sp [0];
7265
7266                                         mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
7267                                 }
7268                         } else {
7269                                 NEW_LDELEMA (cfg, load, sp, klass);
7270                                 load->cil_code = ip;
7271
7272                                 n = mini_type_to_stind (cfg, &klass->byval_arg);
7273                                 /* FIXME: CEE_STIND_R4 */
7274                                 if (n == CEE_STOBJ)
7275                                         handle_stobj (cfg, bblock, load, sp [2], ip, klass, FALSE, FALSE, TRUE);
7276                                 else {
7277                                         MONO_INST_NEW (cfg, ins, n);
7278                                         ins->cil_code = ip;
7279                                         ins->inst_left = load;
7280                                         ins->inst_right = sp [2];
7281                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
7282                                         MONO_ADD_INS (bblock, ins);
7283                                 }
7284                         }
7285                         ip += 5;
7286                         inline_costs += 1;
7287                         break;
7288                 }
7289                 case CEE_STELEM_REF: {
7290                         MonoInst *iargs [3];
7291                         MonoMethod* helper = mono_marshal_get_stelemref ();
7292
7293                         CHECK_STACK (3);
7294                         sp -= 3;
7295                         if (sp [0]->type != STACK_OBJ)
7296                                 UNVERIFIED;
7297                         if (sp [2]->type != STACK_OBJ)
7298                                 UNVERIFIED;
7299
7300                         handle_loaded_temps (cfg, bblock, stack_start, sp);
7301
7302                         /* storing a NULL doesn't need any of the complex checks in stelemref */
7303                         if (sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL) {
7304                                 MonoInst *load;
7305                                 NEW_LDELEMA (cfg, load, sp, mono_defaults.object_class);
7306                                 load->cil_code = ip;
7307                                 MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
7308                                 ins->cil_code = ip;
7309                                 ins->inst_left = load;
7310                                 ins->inst_right = sp [2];
7311                                 MONO_ADD_INS (bblock, ins);
7312                         } else {
7313                                 iargs [2] = sp [2];
7314                                 iargs [1] = sp [1];
7315                                 iargs [0] = sp [0];
7316                         
7317                                 mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
7318                                 inline_costs += 1;
7319                         }
7320
7321                         ++ip;
7322                         break;
7323                 }
7324                 case CEE_CKFINITE: {
7325                         MonoInst *store, *temp;
7326                         CHECK_STACK (1);
7327
7328                         /* this instr. can throw exceptions as side effect,
7329                          * so we cant eliminate dead code which contains CKFINITE opdodes.
7330                          * Spilling to memory makes sure that we always perform
7331                          * this check */
7332
7333                         
7334                         MONO_INST_NEW (cfg, ins, OP_CKFINITE);
7335                         ins->cil_code = ip;
7336                         ins->inst_left = sp [-1];
7337                         temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
7338
7339                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
7340                         store->cil_code = ip;
7341                         MONO_ADD_INS (bblock, store);
7342
7343                         NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
7344                        
7345                         ++ip;
7346                         break;
7347                 }
7348                 case CEE_REFANYVAL:
7349                         CHECK_STACK (1);
7350                         MONO_INST_NEW (cfg, ins, *ip);
7351                         --sp;
7352                         CHECK_OPSIZE (5);
7353                         klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
7354                         CHECK_TYPELOAD (klass);
7355                         mono_class_init (klass);
7356                         ins->type = STACK_MP;
7357                         ins->inst_left = *sp;
7358                         ins->klass = klass;
7359                         ins->inst_newa_class = klass;
7360                         ins->cil_code = ip;
7361                         ip += 5;
7362                         *sp++ = ins;
7363                         break;
7364                 case CEE_MKREFANY: {
7365                         MonoInst *loc, *klassconst;
7366
7367                         CHECK_STACK (1);
7368                         MONO_INST_NEW (cfg, ins, *ip);
7369                         --sp;
7370                         CHECK_OPSIZE (5);
7371                         klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
7372                         CHECK_TYPELOAD (klass);
7373                         mono_class_init (klass);
7374                         ins->cil_code = ip;
7375
7376                         if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
7377                                 GENERIC_SHARING_FAILURE (CEE_MKREFANY);
7378
7379                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
7380                         NEW_TEMPLOADA (cfg, ins->inst_right, loc->inst_c0);
7381
7382                         NEW_PCONST (cfg, klassconst, klass);
7383                         NEW_GROUP (cfg, ins->inst_left, *sp, klassconst);
7384                         
7385                         MONO_ADD_INS (bblock, ins);
7386
7387                         NEW_TEMPLOAD (cfg, *sp, loc->inst_c0);
7388                         ++sp;
7389                         ip += 5;
7390                         break;
7391                 }
7392                 case CEE_LDTOKEN: {
7393                         gpointer handle;
7394                         MonoClass *handle_class;
7395
7396                         CHECK_STACK_OVF (1);
7397
7398                         CHECK_OPSIZE (5);
7399                         n = read32 (ip + 1);
7400
7401                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7402                                 handle = mono_method_get_wrapper_data (method, n);
7403                                 handle_class = mono_method_get_wrapper_data (method, n + 1);
7404                                 if (handle_class == mono_defaults.typehandle_class)
7405                                         handle = &((MonoClass*)handle)->byval_arg;
7406                         }
7407                         else {
7408                                 handle = mono_ldtoken (image, n, &handle_class, generic_context);
7409                                 if (cfg->generic_sharing_context &&
7410                                                 mono_class_check_context_used (handle_class))
7411                                         GENERIC_SHARING_FAILURE (CEE_LDTOKEN);
7412                         }
7413                         if (!handle)
7414                                 goto load_error;
7415                         mono_class_init (handle_class);
7416
7417                         if (cfg->opt & MONO_OPT_SHARED) {
7418                                 int temp;
7419                                 MonoInst *res, *store, *addr, *vtvar, *iargs [3];
7420
7421                                 GENERIC_SHARING_FAILURE (CEE_LDTOKEN);
7422
7423                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
7424
7425                                 NEW_IMAGECONST (cfg, iargs [0], image);
7426                                 NEW_ICONST (cfg, iargs [1], n);
7427                                 NEW_PCONST (cfg, iargs [2], generic_context);
7428                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
7429                                 NEW_TEMPLOAD (cfg, res, temp);
7430                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
7431                                 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
7432                                 MONO_ADD_INS (bblock, store);
7433                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
7434                         } else {
7435                                 if ((ip [5] == CEE_CALL) && (cmethod = mini_get_method (method, read32 (ip + 6), NULL, generic_context)) &&
7436                                                 (cmethod->klass == mono_defaults.monotype_class->parent) &&
7437                                                 (strcmp (cmethod->name, "GetTypeFromHandle") == 0) && ip_in_bb (cfg, bblock, ip + 5)) {
7438                                         MonoClass *tclass = mono_class_from_mono_type (handle);
7439                                         mono_class_init (tclass);
7440                                         if (cfg->compile_aot)
7441                                                 NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n);
7442                                         else
7443                                                 NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
7444                                         ins->type = STACK_OBJ;
7445                                         ins->klass = cmethod->klass;
7446                                         ip += 5;
7447                                 } else {
7448                                         MonoInst *store, *addr, *vtvar;
7449
7450                                         if (cfg->compile_aot)
7451                                                 NEW_LDTOKENCONST (cfg, ins, image, n);
7452                                         else
7453                                                 NEW_PCONST (cfg, ins, handle);
7454                                         vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
7455                                         NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
7456                                         NEW_INDSTORE (cfg, store, addr, ins, &mono_defaults.int_class->byval_arg);
7457                                         MONO_ADD_INS (bblock, store);
7458                                         NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
7459                                 }
7460                         }
7461
7462                         *sp++ = ins;
7463                         ip += 5;
7464                         break;
7465                 }
7466                 case CEE_CONV_U2:
7467                 case CEE_CONV_U1:
7468                 case CEE_CONV_I:
7469                         CHECK_STACK (1);
7470                         ADD_UNOP (*ip);
7471                         ip++;
7472                         break;
7473                 case CEE_ADD_OVF:
7474                 case CEE_ADD_OVF_UN:
7475                 case CEE_MUL_OVF:
7476                 case CEE_MUL_OVF_UN:
7477                 case CEE_SUB_OVF:
7478                 case CEE_SUB_OVF_UN:
7479                         CHECK_STACK (2);
7480                         ADD_BINOP (*ip);
7481                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
7482                                 --sp;
7483                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
7484                         }
7485                         ip++;
7486                         break;
7487                 case CEE_ENDFINALLY:
7488                         MONO_INST_NEW (cfg, ins, OP_ENDFINALLY);
7489                         MONO_ADD_INS (bblock, ins);
7490                         ins->cil_code = ip++;
7491                         start_new_bblock = 1;
7492
7493                         /*
7494                          * Control will leave the method so empty the stack, otherwise
7495                          * the next basic block will start with a nonempty stack.
7496                          */
7497                         while (sp != stack_start) {
7498                                 MONO_INST_NEW (cfg, ins, CEE_POP);
7499                                 ins->cil_code = ip;
7500                                 sp--;
7501                                 ins->inst_i0 = *sp;
7502                                 MONO_ADD_INS (bblock, ins);
7503                         }
7504                         break;
7505                 case CEE_LEAVE:
7506                 case CEE_LEAVE_S: {
7507                         GList *handlers;
7508
7509                         if (*ip == CEE_LEAVE) {
7510                                 CHECK_OPSIZE (5);
7511                                 target = ip + 5 + (gint32)read32(ip + 1);
7512                         } else {
7513                                 CHECK_OPSIZE (2);
7514                                 target = ip + 2 + (signed char)(ip [1]);
7515                         }
7516
7517                         /* empty the stack */
7518                         while (sp != stack_start) {
7519                                 MONO_INST_NEW (cfg, ins, CEE_POP);
7520                                 ins->cil_code = ip;
7521                                 sp--;
7522                                 ins->inst_i0 = *sp;
7523                                 MONO_ADD_INS (bblock, ins);
7524                         }
7525
7526                         /* 
7527                          * If this leave statement is in a catch block, check for a
7528                          * pending exception, and rethrow it if necessary.
7529                          */
7530                         for (i = 0; i < header->num_clauses; ++i) {
7531                                 MonoExceptionClause *clause = &header->clauses [i];
7532
7533                                 /* 
7534                                  * Use <= in the final comparison to handle clauses with multiple
7535                                  * leave statements, like in bug #78024.
7536                                  * The ordering of the exception clauses guarantees that we find the
7537                                  * innermost clause.
7538                                  */
7539                                 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)) {
7540                                         int temp;
7541                                         MonoInst *load;
7542
7543                                         NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
7544                                         load->cil_code = ip;
7545
7546                                         temp = mono_emit_jit_icall (cfg, bblock, mono_thread_get_pending_exception, NULL, ip);
7547                                         NEW_TEMPLOAD (cfg, *sp, temp);
7548                                 
7549                                         MONO_INST_NEW (cfg, ins, OP_THROW_OR_NULL);
7550                                         ins->inst_left = *sp;
7551                                         ins->inst_right = load;
7552                                         ins->cil_code = ip;
7553                                         MONO_ADD_INS (bblock, ins);
7554                                 }
7555                         }
7556
7557                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
7558                                 GList *tmp;
7559                                 for (tmp = handlers; tmp; tmp = tmp->next) {
7560                                         tblock = tmp->data;
7561                                         link_bblock (cfg, bblock, tblock);
7562                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
7563                                         ins->cil_code = ip;
7564                                         ins->inst_target_bb = tblock;
7565                                         MONO_ADD_INS (bblock, ins);
7566                                 }
7567                                 g_list_free (handlers);
7568                         } 
7569
7570                         MONO_INST_NEW (cfg, ins, OP_BR);
7571                         ins->cil_code = ip;
7572                         MONO_ADD_INS (bblock, ins);
7573                         GET_BBLOCK (cfg, tblock, target);
7574                         link_bblock (cfg, bblock, tblock);
7575                         CHECK_BBLOCK (target, ip, tblock);
7576                         ins->inst_target_bb = tblock;
7577                         start_new_bblock = 1;
7578
7579                         if (*ip == CEE_LEAVE)
7580                                 ip += 5;
7581                         else
7582                                 ip += 2;
7583
7584                         break;
7585                 }
7586                 case CEE_STIND_I:
7587                         CHECK_STACK (2);
7588                         MONO_INST_NEW (cfg, ins, *ip);
7589                         sp -= 2;
7590                         handle_loaded_temps (cfg, bblock, stack_start, sp);
7591                         MONO_ADD_INS (bblock, ins);
7592                         ins->cil_code = ip++;
7593                         ins->inst_i0 = sp [0];
7594                         ins->inst_i1 = sp [1];
7595                         inline_costs += 1;
7596                         break;
7597                 case CEE_CONV_U:
7598                         CHECK_STACK (1);
7599                         ADD_UNOP (*ip);
7600                         ip++;
7601                         break;
7602                 /* trampoline mono specific opcodes */
7603                 case MONO_CUSTOM_PREFIX: {
7604
7605                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
7606
7607                         CHECK_OPSIZE (2);
7608                         switch (ip [1]) {
7609
7610                         case CEE_MONO_ICALL: {
7611                                 int temp;
7612                                 gpointer func;
7613                                 MonoJitICallInfo *info;
7614
7615                                 token = read32 (ip + 2);
7616                                 func = mono_method_get_wrapper_data (method, token);
7617                                 info = mono_find_jit_icall_by_addr (func);
7618                                 if (info == NULL){
7619                                         g_error ("An attempt has been made to perform an icall to address %p, "
7620                                                  "but the address has not been registered as an icall\n", info);
7621                                         g_assert_not_reached ();
7622                                 }
7623
7624                                 CHECK_STACK (info->sig->param_count);
7625                                 sp -= info->sig->param_count;
7626
7627                                 temp = mono_emit_jit_icall (cfg, bblock, info->func, sp, ip);
7628                                 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
7629                                         NEW_TEMPLOAD (cfg, *sp, temp);
7630                                         sp++;
7631                                 }
7632
7633                                 ip += 6;
7634                                 inline_costs += 10 * num_calls++;
7635
7636                                 break;
7637                         }
7638                         case CEE_MONO_LDPTR:
7639                                 CHECK_STACK_OVF (1);
7640                                 CHECK_OPSIZE (6);
7641                                 token = read32 (ip + 2);
7642                                 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
7643                                 ins->cil_code = ip;
7644                                 *sp++ = ins;
7645                                 ip += 6;
7646                                 inline_costs += 10 * num_calls++;
7647                                 /* Can't embed random pointers into AOT code */
7648                                 cfg->disable_aot = 1;
7649                                 break;
7650                         case CEE_MONO_VTADDR:
7651                                 CHECK_STACK (1);
7652                                 --sp;
7653                                 MONO_INST_NEW (cfg, ins, OP_VTADDR);
7654                                 ins->cil_code = ip;
7655                                 ins->type = STACK_MP;
7656                                 ins->inst_left = *sp;
7657                                 *sp++ = ins;
7658                                 ip += 2;
7659                                 break;
7660                         case CEE_MONO_NEWOBJ: {
7661                                 MonoInst *iargs [2];
7662                                 int temp;
7663                                 CHECK_STACK_OVF (1);
7664                                 CHECK_OPSIZE (6);
7665                                 token = read32 (ip + 2);
7666                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
7667                                 mono_class_init (klass);
7668                                 NEW_DOMAINCONST (cfg, iargs [0]);
7669                                 NEW_CLASSCONST (cfg, iargs [1], klass);
7670                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
7671                                 NEW_TEMPLOAD (cfg, *sp, temp);
7672                                 sp++;
7673                                 ip += 6;
7674                                 inline_costs += 10 * num_calls++;
7675                                 break;
7676                         }
7677                         case CEE_MONO_OBJADDR:
7678                                 CHECK_STACK (1);
7679                                 --sp;
7680                                 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
7681                                 ins->cil_code = ip;
7682                                 ins->type = STACK_MP;
7683                                 ins->inst_left = *sp;
7684                                 *sp++ = ins;
7685                                 ip += 2;
7686                                 break;
7687                         case CEE_MONO_LDNATIVEOBJ:
7688                                 CHECK_STACK (1);
7689                                 CHECK_OPSIZE (6);
7690                                 token = read32 (ip + 2);
7691                                 klass = mono_method_get_wrapper_data (method, token);
7692                                 g_assert (klass->valuetype);
7693                                 mono_class_init (klass);
7694                                 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
7695                                 sp [-1] = ins;
7696                                 ip += 6;
7697                                 break;
7698                         case CEE_MONO_RETOBJ:
7699                                 g_assert (cfg->ret);
7700                                 g_assert (mono_method_signature (method)->pinvoke); 
7701                                 CHECK_STACK (1);
7702                                 --sp;
7703                                 
7704                                 CHECK_OPSIZE (6);
7705                                 token = read32 (ip + 2);    
7706                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
7707
7708                                 NEW_RETLOADA (cfg, ins);
7709                                 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE, FALSE);
7710                                 
7711                                 if (sp != stack_start)
7712                                         UNVERIFIED;
7713                                 
7714                                 MONO_INST_NEW (cfg, ins, OP_BR);
7715                                 ins->cil_code = ip;
7716                                 ins->inst_target_bb = end_bblock;
7717                                 MONO_ADD_INS (bblock, ins);
7718                                 link_bblock (cfg, bblock, end_bblock);
7719                                 start_new_bblock = 1;
7720                                 ip += 6;
7721                                 break;
7722                         case CEE_MONO_CISINST:
7723                         case CEE_MONO_CCASTCLASS: {
7724                                 int token;
7725                                 CHECK_STACK (1);
7726                                 --sp;
7727                                 CHECK_OPSIZE (6);
7728                                 token = read32 (ip + 2);
7729                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
7730                                 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_CISINST) ? OP_CISINST : OP_CCASTCLASS);
7731                                 ins->type = STACK_I4;
7732                                 ins->inst_left = *sp;
7733                                 ins->inst_newa_class = klass;
7734                                 ins->cil_code = ip;
7735                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 6);
7736                                 ip += 6;
7737                                 break;
7738                         }
7739                         case CEE_MONO_SAVE_LMF:
7740                         case CEE_MONO_RESTORE_LMF:
7741 #ifdef MONO_ARCH_HAVE_LMF_OPS
7742                                 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_SAVE_LMF) ? OP_SAVE_LMF : OP_RESTORE_LMF);
7743                                 MONO_ADD_INS (bblock, ins);
7744                                 cfg->need_lmf_area = TRUE;
7745 #endif
7746                                 ip += 2;
7747                                 break;
7748                         case CEE_MONO_CLASSCONST:
7749                                 CHECK_STACK_OVF (1);
7750                                 CHECK_OPSIZE (6);
7751                                 token = read32 (ip + 2);
7752                                 NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
7753                                 ins->cil_code = ip;
7754                                 *sp++ = ins;
7755                                 ip += 6;
7756                                 inline_costs += 10 * num_calls++;
7757                                 break;
7758                         case CEE_MONO_NOT_TAKEN:
7759                                 bblock->out_of_line = TRUE;
7760                                 ip += 2;
7761                                 break;
7762                         case CEE_MONO_TLS:
7763                                 CHECK_STACK_OVF (1);
7764                                 CHECK_OPSIZE (6);
7765                                 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
7766                                 ins->inst_offset = (gint32)read32 (ip + 2);
7767                                 ins->cil_code = ip;
7768                                 ins->type = STACK_PTR;
7769                                 *sp++ = ins;
7770                                 ip += 6;
7771                                 break;
7772                         default:
7773                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
7774                                 break;
7775                         }
7776                         break;
7777                 }
7778                 case CEE_PREFIX1: {
7779                         CHECK_OPSIZE (2);
7780                         switch (ip [1]) {
7781                         case CEE_ARGLIST: {
7782                                 /* somewhat similar to LDTOKEN */
7783                                 MonoInst *addr, *vtvar;
7784                                 CHECK_STACK_OVF (1);
7785                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
7786
7787                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
7788                                 addr->cil_code = ip;
7789                                 MONO_INST_NEW (cfg, ins, OP_ARGLIST);
7790                                 ins->cil_code = ip;
7791                                 ins->inst_left = addr;
7792                                 MONO_ADD_INS (bblock, ins);
7793                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
7794                                 ins->cil_code = ip;
7795                                 *sp++ = ins;
7796                                 ip += 2;
7797                                 break;
7798                         }
7799                         case CEE_CEQ:
7800                         case CEE_CGT:
7801                         case CEE_CGT_UN:
7802                         case CEE_CLT:
7803                         case CEE_CLT_UN: {
7804                                 MonoInst *cmp;
7805                                 CHECK_STACK (2);
7806                                 /*
7807                                  * The following transforms:
7808                                  *    CEE_CEQ    into OP_CEQ
7809                                  *    CEE_CGT    into OP_CGT
7810                                  *    CEE_CGT_UN into OP_CGT_UN
7811                                  *    CEE_CLT    into OP_CLT
7812                                  *    CEE_CLT_UN into OP_CLT_UN
7813                                  */
7814                                 MONO_INST_NEW (cfg, cmp, 256 + ip [1]);
7815                                 
7816                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
7817                                 sp -= 2;
7818                                 cmp->inst_i0 = sp [0];
7819                                 cmp->inst_i1 = sp [1];
7820                                 cmp->cil_code = ip;
7821                                 type_from_op (cmp);
7822                                 CHECK_TYPE (cmp);
7823                                 ins->cil_code = ip;
7824                                 ins->type = STACK_I4;
7825                                 ins->inst_i0 = cmp;
7826 #if MONO_ARCH_SOFT_FLOAT
7827                                 if (sp [0]->type == STACK_R8) {
7828                                         cmp->type = STACK_I4;
7829                                         *sp++ = emit_tree (cfg, bblock, cmp, ip + 2);
7830                                         ip += 2;
7831                                         break;
7832                                 }
7833 #endif
7834                                 if ((sp [0]->type == STACK_I8) || ((sizeof (gpointer) == 8) && ((sp [0]->type == STACK_PTR) || (sp [0]->type == STACK_OBJ) || (sp [0]->type == STACK_MP))))
7835                                         cmp->opcode = OP_LCOMPARE;
7836                                 else
7837                                         cmp->opcode = OP_COMPARE;
7838                                 *sp++ = ins;
7839                                 /* spill it to reduce the expression complexity
7840                                  * and workaround bug 54209 
7841                                  */
7842                                 if (cmp->inst_left->type == STACK_I8) {
7843                                         --sp;
7844                                         *sp++ = emit_tree (cfg, bblock, ins, ip + 2);
7845                                 }
7846                                 ip += 2;
7847                                 break;
7848                         }
7849                         case CEE_LDFTN: {
7850                                 MonoInst *argconst;
7851                                 MonoMethod *cil_method;
7852                                 int temp;
7853
7854                                 CHECK_STACK_OVF (1);
7855                                 CHECK_OPSIZE (6);
7856                                 n = read32 (ip + 2);
7857                                 cmethod = mini_get_method (method, n, NULL, generic_context);
7858                                 if (!cmethod)
7859                                         goto load_error;
7860                                 mono_class_init (cmethod->klass);
7861
7862                                 if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
7863                                         GENERIC_SHARING_FAILURE (CEE_LDFTN);
7864
7865                                 cil_method = cmethod;
7866                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cmethod))
7867                                         METHOD_ACCESS_FAILURE;
7868                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
7869                                         if (check_linkdemand (cfg, method, cmethod, bblock, ip))
7870                                                 INLINE_FAILURE;
7871                                         CHECK_CFG_EXCEPTION;
7872                                 } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
7873                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
7874                                 }
7875
7876                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
7877
7878                                 NEW_METHODCONST (cfg, argconst, cmethod);
7879                                 if (method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
7880                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
7881                                 else
7882                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn_nosync, &argconst, ip);
7883                                 NEW_TEMPLOAD (cfg, *sp, temp);
7884                                 sp ++;
7885                                 
7886                                 ip += 6;
7887                                 inline_costs += 10 * num_calls++;
7888                                 break;
7889                         }
7890                         case CEE_LDVIRTFTN: {
7891                                 MonoInst *args [2];
7892                                 int temp;
7893
7894                                 CHECK_STACK (1);
7895                                 CHECK_OPSIZE (6);
7896                                 n = read32 (ip + 2);
7897                                 cmethod = mini_get_method (method, n, NULL, generic_context);
7898                                 if (!cmethod)
7899                                         goto load_error;
7900                                 mono_class_init (cmethod->klass);
7901
7902                                 if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
7903                                         GENERIC_SHARING_FAILURE (CEE_LDVIRTFTN);
7904
7905                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
7906                                         if (check_linkdemand (cfg, method, cmethod, bblock, ip))
7907                                                 INLINE_FAILURE;
7908                                         CHECK_CFG_EXCEPTION;
7909                                 } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
7910                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
7911                                 }
7912
7913                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
7914
7915                                 --sp;
7916                                 args [0] = *sp;
7917                                 NEW_METHODCONST (cfg, args [1], cmethod);
7918                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
7919                                 NEW_TEMPLOAD (cfg, *sp, temp);
7920                                 sp ++;
7921
7922                                 ip += 6;
7923                                 inline_costs += 10 * num_calls++;
7924                                 break;
7925                         }
7926                         case CEE_LDARG:
7927                                 CHECK_STACK_OVF (1);
7928                                 CHECK_OPSIZE (4);
7929                                 n = read16 (ip + 2);
7930                                 CHECK_ARG (n);
7931                                 NEW_ARGLOAD (cfg, ins, n);
7932                                 LDARG_SOFT_FLOAT (cfg, ins, n, ip);
7933                                 ins->cil_code = ip;
7934                                 *sp++ = ins;
7935                                 ip += 4;
7936                                 break;
7937                         case CEE_LDARGA:
7938                                 CHECK_STACK_OVF (1);
7939                                 CHECK_OPSIZE (4);
7940                                 n = read16 (ip + 2);
7941                                 CHECK_ARG (n);
7942                                 NEW_ARGLOADA (cfg, ins, n);
7943                                 ins->cil_code = ip;
7944                                 *sp++ = ins;
7945                                 ip += 4;
7946                                 break;
7947                         case CEE_STARG:
7948                                 CHECK_STACK (1);
7949                                 --sp;
7950                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
7951                                 CHECK_OPSIZE (4);
7952                                 n = read16 (ip + 2);
7953                                 CHECK_ARG (n);
7954                                 NEW_ARGSTORE (cfg, ins, n, *sp);
7955                                 ins->cil_code = ip;
7956                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
7957                                         UNVERIFIED;
7958                                 STARG_SOFT_FLOAT (cfg, ins, n, ip);
7959                                 if (ins->opcode == CEE_STOBJ) {
7960                                         NEW_ARGLOADA (cfg, ins, n);
7961                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
7962                                 } else
7963                                         MONO_ADD_INS (bblock, ins);
7964                                 ip += 4;
7965                                 break;
7966                         case CEE_LDLOC:
7967                                 CHECK_STACK_OVF (1);
7968                                 CHECK_OPSIZE (4);
7969                                 n = read16 (ip + 2);
7970                                 CHECK_LOCAL (n);
7971                                 NEW_LOCLOAD (cfg, ins, n);
7972                                 LDLOC_SOFT_FLOAT (cfg, ins, n, ip);
7973                                 ins->cil_code = ip;
7974                                 *sp++ = ins;
7975                                 ip += 4;
7976                                 break;
7977                         case CEE_LDLOCA:
7978                                 CHECK_STACK_OVF (1);
7979                                 CHECK_OPSIZE (4);
7980                                 n = read16 (ip + 2);
7981                                 CHECK_LOCAL (n);
7982                                 NEW_LOCLOADA (cfg, ins, n);
7983                                 ins->cil_code = ip;
7984                                 *sp++ = ins;
7985                                 ip += 4;
7986                                 break;
7987                         case CEE_STLOC:
7988                                 CHECK_STACK (1);
7989                                 --sp;
7990                                 CHECK_OPSIZE (4);
7991                                 n = read16 (ip + 2);
7992                                 CHECK_LOCAL (n);
7993                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
7994                                 NEW_LOCSTORE (cfg, ins, n, *sp);
7995                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
7996                                         UNVERIFIED;
7997                                 ins->cil_code = ip;
7998                                 STLOC_SOFT_FLOAT (cfg, ins, n, ip);
7999                                 if (ins->opcode == CEE_STOBJ) {
8000                                         NEW_LOCLOADA (cfg, ins, n);
8001                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
8002                                 } else
8003                                         MONO_ADD_INS (bblock, ins);
8004                                 ip += 4;
8005                                 inline_costs += 1;
8006                                 break;
8007                         case CEE_LOCALLOC:
8008                                 CHECK_STACK (1);
8009                                 --sp;
8010                                 if (sp != stack_start) 
8011                                         UNVERIFIED;
8012                                 if (cfg->method != method) 
8013                                         /* 
8014                                          * Inlining this into a loop in a parent could lead to 
8015                                          * stack overflows which is different behavior than the
8016                                          * non-inlined case, thus disable inlining in this case.
8017                                          */
8018                                         goto inline_failure;
8019                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
8020                                 ins->inst_left = *sp;
8021                                 ins->cil_code = ip;
8022                                 ins->type = STACK_PTR;
8023
8024                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
8025                                 if (header->init_locals)
8026                                         ins->flags |= MONO_INST_INIT;
8027
8028                                 *sp++ = ins;
8029                                 ip += 2;
8030                                 /* FIXME: set init flag if locals init is set in this method */
8031                                 break;
8032                         case CEE_ENDFILTER: {
8033                                 MonoExceptionClause *clause, *nearest;
8034                                 int cc, nearest_num;
8035
8036                                 CHECK_STACK (1);
8037                                 --sp;
8038                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
8039                                         UNVERIFIED;
8040                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
8041                                 ins->inst_left = *sp;
8042                                 ins->cil_code = ip;
8043                                 MONO_ADD_INS (bblock, ins);
8044                                 start_new_bblock = 1;
8045                                 ip += 2;
8046
8047                                 nearest = NULL;
8048                                 nearest_num = 0;
8049                                 for (cc = 0; cc < header->num_clauses; ++cc) {
8050                                         clause = &header->clauses [cc];
8051                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
8052                                                 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
8053                                             (!nearest || (clause->data.filter_offset < nearest->data.filter_offset))) {
8054                                                 nearest = clause;
8055                                                 nearest_num = cc;
8056                                         }
8057                                 }
8058                                 g_assert (nearest);
8059                                 if ((ip - header->code) != nearest->handler_offset)
8060                                         UNVERIFIED;
8061
8062                                 break;
8063                         }
8064                         case CEE_UNALIGNED_:
8065                                 ins_flag |= MONO_INST_UNALIGNED;
8066                                 /* FIXME: record alignment? we can assume 1 for now */
8067                                 CHECK_OPSIZE (3);
8068                                 ip += 3;
8069                                 break;
8070                         case CEE_VOLATILE_:
8071                                 ins_flag |= MONO_INST_VOLATILE;
8072                                 ip += 2;
8073                                 break;
8074                         case CEE_TAIL_:
8075                                 ins_flag   |= MONO_INST_TAILCALL;
8076                                 cfg->flags |= MONO_CFG_HAS_TAIL;
8077                                 /* Can't inline tail calls at this time */
8078                                 inline_costs += 100000;
8079                                 ip += 2;
8080                                 break;
8081                         case CEE_INITOBJ:
8082                                 CHECK_STACK (1);
8083                                 --sp;
8084                                 CHECK_OPSIZE (6);
8085                                 token = read32 (ip + 2);
8086                                 klass = mini_get_class (method, token, generic_context);
8087                                 CHECK_TYPELOAD (klass);
8088
8089                                 if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
8090                                         GENERIC_SHARING_FAILURE (CEE_INITOBJ);
8091
8092                                 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
8093                                         MonoInst *store, *load;
8094                                         NEW_PCONST (cfg, load, NULL);
8095                                         load->cil_code = ip;
8096                                         load->type = STACK_OBJ;
8097                                         load->klass = klass;
8098                                         MONO_INST_NEW (cfg, store, CEE_STIND_REF);
8099                                         store->cil_code = ip;
8100                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8101                                         MONO_ADD_INS (bblock, store);
8102                                         store->inst_i0 = sp [0];
8103                                         store->inst_i1 = load;
8104                                 } else {
8105                                         handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
8106                                 }
8107                                 ip += 6;
8108                                 inline_costs += 1;
8109                                 break;
8110                         case CEE_CONSTRAINED_:
8111                                 /* FIXME: implement */
8112                                 CHECK_OPSIZE (6);
8113                                 token = read32 (ip + 2);
8114                                 constrained_call = mono_class_get_full (image, token, generic_context);
8115                                 CHECK_TYPELOAD (constrained_call);
8116                                 ip += 6;
8117                                 break;
8118                         case CEE_CPBLK:
8119                         case CEE_INITBLK: {
8120                                 MonoInst *iargs [3];
8121                                 CHECK_STACK (3);
8122                                 sp -= 3;
8123                                 if ((cfg->opt & MONO_OPT_INTRINS) && (ip [1] == CEE_CPBLK) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5)) {
8124                                         MonoInst *copy;
8125                                         NEW_MEMCPY (cfg, copy, sp [0], sp [1], n, 0);
8126                                         MONO_ADD_INS (bblock, copy);
8127                                         ip += 2;
8128                                         break;
8129                                 }
8130                                 iargs [0] = sp [0];
8131                                 iargs [1] = sp [1];
8132                                 iargs [2] = sp [2];
8133                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
8134                                 if (ip [1] == CEE_CPBLK) {
8135                                         MonoMethod *memcpy_method = get_memcpy_method ();
8136                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
8137                                 } else {
8138                                         MonoMethod *memset_method = get_memset_method ();
8139                                         mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
8140                                 }
8141                                 ip += 2;
8142                                 inline_costs += 1;
8143                                 break;
8144                         }
8145                         case CEE_NO_:
8146                                 CHECK_OPSIZE (3);
8147                                 if (ip [2] & 0x1)
8148                                         ins_flag |= MONO_INST_NOTYPECHECK;
8149                                 if (ip [2] & 0x2)
8150                                         ins_flag |= MONO_INST_NORANGECHECK;
8151                                 /* we ignore the no-nullcheck for now since we
8152                                  * really do it explicitly only when doing callvirt->call
8153                                  */
8154                                 ip += 3;
8155                                 break;
8156                         case CEE_RETHROW: {
8157                                 MonoInst *load;
8158                                 int handler_offset = -1;
8159
8160                                 for (i = 0; i < header->num_clauses; ++i) {
8161                                         MonoExceptionClause *clause = &header->clauses [i];
8162                                         if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY))
8163                                                 handler_offset = clause->handler_offset;
8164                                 }
8165
8166                                 bblock->flags |= BB_EXCEPTION_UNSAFE;
8167
8168                                 g_assert (handler_offset != -1);
8169
8170                                 NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
8171                                 load->cil_code = ip;
8172                                 MONO_INST_NEW (cfg, ins, OP_RETHROW);
8173                                 ins->inst_left = load;
8174                                 ins->cil_code = ip;
8175                                 MONO_ADD_INS (bblock, ins);
8176                                 sp = stack_start;
8177                                 link_bblock (cfg, bblock, end_bblock);
8178                                 start_new_bblock = 1;
8179                                 ip += 2;
8180                                 break;
8181                         }
8182                         case CEE_SIZEOF:
8183                                 GENERIC_SHARING_FAILURE (CEE_SIZEOF);
8184
8185                                 CHECK_STACK_OVF (1);
8186                                 CHECK_OPSIZE (6);
8187                                 token = read32 (ip + 2);
8188                                 /* FIXXME: handle generics. */
8189                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
8190                                         MonoType *type = mono_type_create_from_typespec (image, token);
8191                                         token = mono_type_size (type, &ialign);
8192                                 } else {
8193                                         MonoClass *klass = mono_class_get_full (image, token, generic_context);
8194                                         CHECK_TYPELOAD (klass);
8195                                         mono_class_init (klass);
8196                                         token = mono_class_value_size (klass, &align);
8197                                 }
8198                                 NEW_ICONST (cfg, ins, token);
8199                                 ins->cil_code = ip;
8200                                 *sp++= ins;
8201                                 ip += 6;
8202                                 break;
8203                         case CEE_REFANYTYPE:
8204                                 CHECK_STACK (1);
8205                                 MONO_INST_NEW (cfg, ins, OP_REFANYTYPE);
8206                                 --sp;
8207                                 ins->type = STACK_MP;
8208                                 ins->inst_left = *sp;
8209                                 ins->type = STACK_VTYPE;
8210                                 ins->klass = mono_defaults.typehandle_class;
8211                                 ins->cil_code = ip;
8212                                 ip += 2;
8213                                 *sp++ = ins;
8214                                 break;
8215                         case CEE_READONLY_:
8216                                 ip += 2;
8217                                 break;
8218                         default:
8219                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
8220                         }
8221                         break;
8222                 }
8223                 default:
8224                         g_error ("opcode 0x%02x not handled", *ip);
8225                 }
8226         }
8227         if (start_new_bblock != 1)
8228                 UNVERIFIED;
8229
8230         bblock->cil_length = ip - bblock->cil_code;
8231         bblock->next_bb = end_bblock;
8232
8233         if (cfg->method == method && cfg->domainvar) {
8234                 MonoInst *store;
8235                 MonoInst *get_domain;
8236                 
8237                 if (! (get_domain = mono_arch_get_domain_intrinsic (cfg))) {
8238                         MonoCallInst *call;
8239                         
8240                         MONO_INST_NEW_CALL (cfg, call, CEE_CALL);
8241                         call->signature = helper_sig_domain_get;
8242                         call->inst.type = STACK_PTR;
8243                         call->fptr = mono_domain_get;
8244                         get_domain = (MonoInst*)call;
8245                 }
8246                 
8247                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
8248                 MONO_ADD_INS (init_localsbb, store);
8249         }
8250
8251         if (cfg->method == method && cfg->got_var)
8252                 mono_emit_load_got_addr (cfg);
8253
8254         if (header->init_locals) {
8255                 MonoInst *store;
8256                 for (i = 0; i < header->num_locals; ++i) {
8257                         MonoType *ptype = header->locals [i];
8258                         int t = ptype->type;
8259                         if (t == MONO_TYPE_VALUETYPE && ptype->data.klass->enumtype)
8260                                 t = ptype->data.klass->enum_basetype->type;
8261                         if (ptype->byref) {
8262                                 NEW_PCONST (cfg, ins, NULL);
8263                                 NEW_LOCSTORE (cfg, store, i, ins);
8264                                 MONO_ADD_INS (init_localsbb, store);
8265                         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
8266                                 NEW_ICONST (cfg, ins, 0);
8267                                 NEW_LOCSTORE (cfg, store, i, ins);
8268                                 MONO_ADD_INS (init_localsbb, store);
8269                         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
8270                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
8271                                 ins->type = STACK_I8;
8272                                 ins->inst_l = 0;
8273                                 NEW_LOCSTORE (cfg, store, i, ins);
8274                                 MONO_ADD_INS (init_localsbb, store);
8275                         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
8276 #ifdef MONO_ARCH_SOFT_FLOAT
8277                                 /* FIXME: handle init of R4 */
8278 #else
8279                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
8280                                 ins->type = STACK_R8;
8281                                 ins->inst_p0 = (void*)&r8_0;
8282                                 NEW_LOCSTORE (cfg, store, i, ins);
8283                                 MONO_ADD_INS (init_localsbb, store);
8284 #endif
8285                         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
8286                                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (ptype))) {
8287                                 NEW_LOCLOADA (cfg, ins, i);
8288                                 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (ptype), NULL, NULL);
8289                         } else {
8290                                 NEW_PCONST (cfg, ins, NULL);
8291                                 NEW_LOCSTORE (cfg, store, i, ins);
8292                                 MONO_ADD_INS (init_localsbb, store);
8293                         }
8294                 }
8295         }
8296
8297         /* resolve backward branches in the middle of an existing basic block */
8298         for (tmp = bb_recheck; tmp; tmp = tmp->next) {
8299                 bblock = tmp->data;
8300                 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
8301                 tblock = find_previous (cfg->cil_offset_to_bb, header->code_size, start_bblock, bblock->cil_code);
8302                 if (tblock != start_bblock) {
8303                         int l;
8304                         split_bblock (cfg, tblock, bblock);
8305                         l = bblock->cil_code - header->code;
8306                         bblock->cil_length = tblock->cil_length - l;
8307                         tblock->cil_length = l;
8308                 } else {
8309                         g_print ("recheck failed.\n");
8310                 }
8311         }
8312
8313         if (cfg->method == method) {
8314                 MonoBasicBlock *bb;
8315                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
8316                         bb->region = mono_find_block_region (cfg, bb->real_offset);
8317                         if (cfg->spvars)
8318                                 mono_create_spvar_for_region (cfg, bb->region);
8319                         if (cfg->verbose_level > 2)
8320                                 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
8321                 }
8322         }
8323
8324         g_slist_free (class_inits);
8325         dont_inline = g_list_remove (dont_inline, method);
8326
8327         if (inline_costs < 0) {
8328                 char *mname;
8329
8330                 /* Method is too large */
8331                 mname = mono_method_full_name (method, TRUE);
8332                 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
8333                 cfg->exception_message = g_strdup_printf ("Method %s is too complex.", mname);
8334                 g_free (mname);
8335                 return -1;
8336         }
8337
8338         return inline_costs;
8339
8340  exception_exit:
8341         g_assert (cfg->exception_type != MONO_EXCEPTION_NONE);
8342         g_slist_free (class_inits);
8343         dont_inline = g_list_remove (dont_inline, method);
8344         return -1;
8345
8346  inline_failure:
8347         g_slist_free (class_inits);
8348         dont_inline = g_list_remove (dont_inline, method);
8349         return -1;
8350
8351  load_error:
8352         g_slist_free (class_inits);
8353         dont_inline = g_list_remove (dont_inline, method);
8354         cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
8355         return -1;
8356
8357  unverified:
8358         g_slist_free (class_inits);
8359         dont_inline = g_list_remove (dont_inline, method);
8360         set_exception_type_from_invalid_il (cfg, method, ip);
8361         return -1;
8362 }
8363
8364 void
8365 mono_print_tree (MonoInst *tree) {
8366         int arity;
8367
8368         if (!tree)
8369                 return;
8370
8371         arity = mono_burg_arity [tree->opcode];
8372
8373         printf (" %s%s", arity?"(":"",  mono_inst_name (tree->opcode));
8374
8375         switch (tree->opcode) {
8376         case OP_ICONST:
8377                 printf ("[%d]", (int)tree->inst_c0);
8378                 break;
8379         case OP_I8CONST:
8380                 printf ("[%lld]", (long long)tree->inst_l);
8381                 break;
8382         case OP_R8CONST:
8383                 printf ("[%f]", *(double*)tree->inst_p0);
8384                 break;
8385         case OP_R4CONST:
8386                 printf ("[%f]", *(float*)tree->inst_p0);
8387                 break;
8388         case OP_ARG:
8389         case OP_LOCAL:
8390                 printf ("[%d]", (int)tree->inst_c0);
8391                 break;
8392         case OP_REGOFFSET:
8393                 if (tree->inst_offset < 0)
8394                         printf ("[-0x%x(%s)]", (int)(-tree->inst_offset), mono_arch_regname (tree->inst_basereg));
8395                 else
8396                         printf ("[0x%x(%s)]", (int)(tree->inst_offset), mono_arch_regname (tree->inst_basereg));
8397                 break;
8398         case OP_REGVAR:
8399                 printf ("[%s]", mono_arch_regname (tree->dreg));
8400                 break;
8401         case CEE_NEWARR:
8402                 printf ("[%s]",  tree->inst_newa_class->name);
8403                 mono_print_tree (tree->inst_newa_len);
8404                 break;
8405         case CEE_CALL:
8406         case CEE_CALLVIRT:
8407         case OP_FCALL:
8408         case OP_FCALLVIRT:
8409         case OP_LCALL:
8410         case OP_LCALLVIRT:
8411         case OP_VCALL:
8412         case OP_VCALLVIRT:
8413         case OP_VOIDCALL:
8414         case OP_VOIDCALLVIRT: {
8415                 MonoCallInst *call = (MonoCallInst*)tree;
8416                 if (call->method)
8417                         printf ("[%s]", call->method->name);
8418                 else if (call->fptr) {
8419                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (call->fptr);
8420                         if (info)
8421                                 printf ("[%s]", info->name);
8422                 }
8423                 break;
8424         }
8425         case OP_PHI: {
8426                 int i;
8427                 printf ("[%d (", (int)tree->inst_c0);
8428                 for (i = 0; i < tree->inst_phi_args [0]; i++) {
8429                         if (i)
8430                                 printf (", ");
8431                         printf ("%d", tree->inst_phi_args [i + 1]);
8432                 }
8433                 printf (")]");
8434                 break;
8435         }
8436         case OP_RENAME:
8437         case OP_RETARG:
8438         case OP_NOP:
8439         case OP_JMP:
8440         case OP_BREAK:
8441                 break;
8442         case OP_LOAD_MEMBASE:
8443         case OP_LOADI4_MEMBASE:
8444         case OP_LOADU4_MEMBASE:
8445         case OP_LOADU1_MEMBASE:
8446         case OP_LOADI1_MEMBASE:
8447         case OP_LOADU2_MEMBASE:
8448         case OP_LOADI2_MEMBASE:
8449                 printf ("[%s] <- [%s + 0x%x]", mono_arch_regname (tree->dreg), mono_arch_regname (tree->inst_basereg), (int)tree->inst_offset);
8450                 break;
8451         case OP_BR:
8452         case OP_CALL_HANDLER:
8453                 printf ("[B%d]", tree->inst_target_bb->block_num);
8454                 break;
8455         case CEE_SWITCH:
8456         case CEE_ISINST:
8457         case CEE_CASTCLASS:
8458         case OP_OUTARG:
8459         case OP_CALL_REG:
8460         case OP_FCALL_REG:
8461         case OP_LCALL_REG:
8462         case OP_VCALL_REG:
8463         case OP_VOIDCALL_REG:
8464                 mono_print_tree (tree->inst_left);
8465                 break;
8466         case CEE_BNE_UN:
8467         case CEE_BEQ:
8468         case CEE_BLT:
8469         case CEE_BLT_UN:
8470         case CEE_BGT:
8471         case CEE_BGT_UN:
8472         case CEE_BGE:
8473         case CEE_BGE_UN:
8474         case CEE_BLE:
8475         case CEE_BLE_UN:
8476                 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
8477                 mono_print_tree (tree->inst_left);
8478                 break;
8479         default:
8480                 if (!mono_arch_print_tree(tree, arity)) {
8481                         if (arity) {
8482                                 mono_print_tree (tree->inst_left);
8483                                 if (arity > 1)
8484                                         mono_print_tree (tree->inst_right);
8485                         }
8486                 }
8487                 break;
8488         }
8489
8490         if (arity)
8491                 printf (")");
8492 }
8493
8494 void
8495 mono_print_tree_nl (MonoInst *tree)
8496 {
8497         mono_print_tree (tree);
8498         printf ("\n");
8499 }
8500
8501 static void
8502 create_helper_signature (void)
8503 {
8504         helper_sig_domain_get = mono_create_icall_signature ("ptr");
8505         helper_sig_class_init_trampoline = mono_create_icall_signature ("void");
8506 }
8507
8508 gconstpointer
8509 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
8510 {
8511         char *name;
8512         MonoMethod *wrapper;
8513         gconstpointer trampoline;
8514         MonoDomain *domain = mono_get_root_domain ();
8515         
8516         if (callinfo->wrapper) {
8517                 return callinfo->wrapper;
8518         }
8519
8520         if (callinfo->trampoline)
8521                 return callinfo->trampoline;
8522
8523         /* 
8524          * We use the lock on the root domain instead of the JIT lock to protect 
8525          * callinfo->trampoline, since we do a lot of stuff inside the critical section.
8526          */
8527         mono_domain_lock (domain);
8528
8529         if (callinfo->trampoline) {
8530                 mono_domain_unlock (domain);
8531                 return callinfo->trampoline;
8532         }
8533
8534         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
8535         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func);
8536         g_free (name);
8537
8538         trampoline = mono_create_ftnptr (domain, mono_create_jit_trampoline_in_domain (domain, wrapper));
8539         mono_register_jit_icall_wrapper (callinfo, trampoline);
8540
8541         callinfo->trampoline = trampoline;
8542
8543         mono_domain_unlock (domain);
8544         
8545         return callinfo->trampoline;
8546 }
8547
8548 static void
8549 mono_init_trampolines (void)
8550 {
8551         mono_trampoline_code [MONO_TRAMPOLINE_GENERIC] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_GENERIC);
8552         mono_trampoline_code [MONO_TRAMPOLINE_JUMP] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_JUMP);
8553         mono_trampoline_code [MONO_TRAMPOLINE_CLASS_INIT] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_CLASS_INIT);
8554 #ifdef MONO_ARCH_HAVE_PIC_AOT
8555         mono_trampoline_code [MONO_TRAMPOLINE_AOT] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_AOT);
8556         mono_trampoline_code [MONO_TRAMPOLINE_AOT_PLT] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_AOT_PLT);
8557 #endif
8558 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
8559         mono_trampoline_code [MONO_TRAMPOLINE_DELEGATE] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_DELEGATE);
8560 #endif
8561 }
8562
8563 static void
8564 mono_init_exceptions (void)
8565 {
8566 #ifndef CUSTOM_EXCEPTION_HANDLING
8567         mono_arch_get_restore_context ();
8568         mono_arch_get_call_filter ();
8569         mono_arch_get_throw_exception ();
8570         mono_arch_get_rethrow_exception ();
8571 #endif
8572 }
8573
8574 guint8 *
8575 mono_get_trampoline_code (MonoTrampolineType tramp_type)
8576 {
8577         return mono_trampoline_code [tramp_type];
8578 }
8579
8580 gpointer
8581 mono_create_class_init_trampoline (MonoVTable *vtable)
8582 {
8583         gpointer code, ptr;
8584
8585         /* previously created trampoline code */
8586         mono_domain_lock (vtable->domain);
8587         ptr = 
8588                 g_hash_table_lookup (vtable->domain->class_init_trampoline_hash,
8589                                                                   vtable);
8590         mono_domain_unlock (vtable->domain);
8591         if (ptr)
8592                 return ptr;
8593
8594 #ifdef MONO_ARCH_HAVE_CREATE_SPECIFIC_TRAMPOLINE
8595         code = mono_arch_create_specific_trampoline (vtable, MONO_TRAMPOLINE_CLASS_INIT, vtable->domain, NULL);
8596 #else
8597         code = mono_arch_create_class_init_trampoline (vtable);
8598 #endif
8599
8600         ptr = mono_create_ftnptr (vtable->domain, code);
8601
8602         /* store trampoline address */
8603         mono_domain_lock (vtable->domain);
8604         g_hash_table_insert (vtable->domain->class_init_trampoline_hash,
8605                                                           vtable, ptr);
8606         mono_domain_unlock (vtable->domain);
8607
8608         mono_jit_lock ();
8609         if (!class_init_hash_addr)
8610                 class_init_hash_addr = g_hash_table_new (NULL, NULL);
8611         g_hash_table_insert (class_init_hash_addr, ptr, vtable);
8612         mono_jit_unlock ();
8613
8614         return ptr;
8615 }
8616
8617 gpointer
8618 mono_create_jump_trampoline (MonoDomain *domain, MonoMethod *method, 
8619                                                          gboolean add_sync_wrapper)
8620 {
8621         MonoJitInfo *ji;
8622         gpointer code;
8623 #ifdef MONO_ARCH_HAVE_CREATE_SPECIFIC_TRAMPOLINE
8624         guint32 code_size;
8625 #endif
8626
8627         if (add_sync_wrapper && method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
8628                 return mono_create_jump_trampoline (domain, mono_marshal_get_synchronized_wrapper (method), FALSE);
8629
8630         code = mono_jit_find_compiled_method (domain, method);
8631         if (code)
8632                 return code;
8633
8634         mono_domain_lock (domain);
8635         code = g_hash_table_lookup (domain->jump_trampoline_hash, method);
8636         mono_domain_unlock (domain);
8637         if (code)
8638                 return code;
8639
8640 #ifdef MONO_ARCH_HAVE_CREATE_SPECIFIC_TRAMPOLINE
8641         code = mono_arch_create_specific_trampoline (method, MONO_TRAMPOLINE_JUMP, mono_domain_get (), &code_size);
8642
8643         mono_domain_lock (domain);
8644         ji = mono_mempool_alloc0 (domain->mp, sizeof (MonoJitInfo));
8645         mono_domain_unlock (domain);
8646         ji->code_start = code;
8647         ji->code_size = code_size;
8648         ji->method = method;
8649 #else
8650         ji = mono_arch_create_jump_trampoline (method);
8651 #endif
8652
8653         /*
8654          * mono_delegate_ctor needs to find the method metadata from the 
8655          * trampoline address, so we save it here.
8656          */
8657
8658         mono_jit_info_table_add (domain, ji);
8659
8660         mono_domain_lock (domain);
8661         g_hash_table_insert (domain->jump_trampoline_hash, method, ji->code_start);
8662         mono_domain_unlock (domain);
8663
8664         return ji->code_start;
8665 }
8666
8667 static gpointer
8668 mono_create_jit_trampoline_in_domain (MonoDomain *domain, MonoMethod *method)
8669 {
8670         gpointer tramp;
8671
8672         mono_domain_lock (domain);
8673         tramp = g_hash_table_lookup (domain->jit_trampoline_hash, method);
8674         mono_domain_unlock (domain);
8675         if (tramp)
8676                 return tramp;
8677
8678         if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
8679                 return mono_create_jit_trampoline (mono_marshal_get_synchronized_wrapper (method));
8680
8681 #ifdef MONO_ARCH_HAVE_CREATE_SPECIFIC_TRAMPOLINE
8682         tramp =  mono_arch_create_specific_trampoline (method, MONO_TRAMPOLINE_GENERIC, domain, NULL);
8683 #else
8684         tramp = mono_arch_create_jit_trampoline (method);
8685 #endif
8686         
8687         mono_domain_lock (domain);
8688         g_hash_table_insert (domain->jit_trampoline_hash, method, tramp);
8689         mono_domain_unlock (domain);
8690
8691         mono_jit_stats.method_trampolines++;
8692
8693         return tramp;
8694 }       
8695
8696 gpointer
8697 mono_create_jit_trampoline (MonoMethod *method)
8698 {
8699         return mono_create_jit_trampoline_in_domain (mono_domain_get (), method);
8700 }
8701
8702 #ifdef MONO_ARCH_HAVE_CREATE_TRAMPOLINE_FROM_TOKEN
8703 gpointer
8704 mono_create_jit_trampoline_from_token (MonoImage *image, guint32 token)
8705 {
8706         gpointer tramp;
8707
8708         MonoDomain *domain = mono_domain_get ();
8709         guint8 *buf, *start;
8710
8711         mono_domain_lock (domain);
8712         buf = start = mono_code_manager_reserve (domain->code_mp, 2 * sizeof (gpointer));
8713         mono_domain_unlock (domain);
8714
8715         *(gpointer*)(gpointer)buf = image;
8716         buf += sizeof (gpointer);
8717         *(guint32*)(gpointer)buf = token;
8718
8719         tramp = mono_arch_create_specific_trampoline (start, MONO_TRAMPOLINE_AOT, domain, NULL);
8720
8721         mono_jit_stats.method_trampolines++;
8722
8723         return tramp;
8724 }       
8725 #endif
8726
8727 static gpointer
8728 mono_create_delegate_trampoline (MonoClass *klass)
8729 {
8730 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
8731         MonoDomain *domain = mono_domain_get ();
8732         gpointer code, ptr;
8733         guint32 code_size;
8734
8735         mono_domain_lock (domain);
8736         ptr = g_hash_table_lookup (domain->delegate_trampoline_hash, klass);
8737         mono_domain_unlock (domain);
8738         if (ptr)
8739                 return ptr;
8740
8741     code = mono_arch_create_specific_trampoline (klass, MONO_TRAMPOLINE_DELEGATE, mono_domain_get (), &code_size);
8742
8743         ptr = mono_create_ftnptr (domain, code);
8744
8745         /* store trampoline address */
8746         mono_domain_lock (domain);
8747         g_hash_table_insert (domain->delegate_trampoline_hash,
8748                                                           klass, ptr);
8749         mono_domain_unlock (domain);
8750
8751         return ptr;
8752 #else
8753         return NULL;
8754 #endif
8755 }
8756
8757 MonoVTable*
8758 mono_find_class_init_trampoline_by_addr (gconstpointer addr)
8759 {
8760         MonoVTable *res;
8761
8762         mono_jit_lock ();
8763         if (class_init_hash_addr)
8764                 res = g_hash_table_lookup (class_init_hash_addr, addr);
8765         else
8766                 res = NULL;
8767         mono_jit_unlock ();
8768         return res;
8769 }
8770
8771 static void
8772 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
8773 {
8774         if (!domain->dynamic_code_hash)
8775                 domain->dynamic_code_hash = g_hash_table_new (NULL, NULL);
8776         g_hash_table_insert (domain->dynamic_code_hash, method, ji);
8777 }
8778
8779 static MonoJitDynamicMethodInfo*
8780 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
8781 {
8782         MonoJitDynamicMethodInfo *res;
8783
8784         if (domain->dynamic_code_hash)
8785                 res = g_hash_table_lookup (domain->dynamic_code_hash, method);
8786         else
8787                 res = NULL;
8788         return res;
8789 }
8790
8791 typedef struct {
8792         MonoClass *vtype;
8793         GList *active;
8794         GSList *slots;
8795 } StackSlotInfo;
8796
8797 static inline GSList*
8798 g_slist_prepend_mempool (MonoMemPool *mp, GSList   *list,
8799                                                  gpointer  data)
8800 {
8801   GSList *new_list;
8802
8803   new_list = mono_mempool_alloc (mp, sizeof (GSList));
8804   new_list->data = data;
8805   new_list->next = list;
8806
8807   return new_list;
8808 }
8809
8810 /*
8811  *  mono_allocate_stack_slots_full:
8812  *
8813  *  Allocate stack slots for all non register allocated variables using a
8814  * linear scan algorithm.
8815  * Returns: an array of stack offsets.
8816  * STACK_SIZE is set to the amount of stack space needed.
8817  * STACK_ALIGN is set to the alignment needed by the locals area.
8818  */
8819 gint32*
8820 mono_allocate_stack_slots_full (MonoCompile *m, gboolean backward, guint32 *stack_size, guint32 *stack_align)
8821 {
8822         int i, slot, offset, size;
8823         guint32 align;
8824         MonoMethodVar *vmv;
8825         MonoInst *inst;
8826         gint32 *offsets;
8827         GList *vars = NULL, *l;
8828         StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
8829         MonoType *t;
8830         int nvtypes;
8831
8832         scalar_stack_slots = mono_mempool_alloc0 (m->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
8833         vtype_stack_slots = NULL;
8834         nvtypes = 0;
8835
8836         offsets = mono_mempool_alloc (m->mempool, sizeof (gint32) * m->num_varinfo);
8837         for (i = 0; i < m->num_varinfo; ++i)
8838                 offsets [i] = -1;
8839
8840         for (i = m->locals_start; i < m->num_varinfo; i++) {
8841                 inst = m->varinfo [i];
8842                 vmv = MONO_VARINFO (m, i);
8843
8844                 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
8845                         continue;
8846
8847                 vars = g_list_prepend (vars, vmv);
8848         }
8849
8850         vars = mono_varlist_sort (m, vars, 0);
8851         offset = 0;
8852         *stack_align = 0;
8853         for (l = vars; l; l = l->next) {
8854                 vmv = l->data;
8855                 inst = m->varinfo [vmv->idx];
8856
8857                 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
8858                 * pinvoke wrappers when they call functions returning structures */
8859                 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF)
8860                         size = mono_class_native_size (inst->inst_vtype->data.klass, &align);
8861                 else {
8862                         int ialign;
8863
8864                         size = mono_type_size (inst->inst_vtype, &ialign);
8865                         align = ialign;
8866                 }
8867
8868                 t = mono_type_get_underlying_type (inst->inst_vtype);
8869                 if (t->byref) {
8870                         slot_info = &scalar_stack_slots [MONO_TYPE_I];
8871                 } else {
8872                         switch (t->type) {
8873                         case MONO_TYPE_GENERICINST:
8874                                 if (!mono_type_generic_inst_is_valuetype (t)) {
8875                                         slot_info = &scalar_stack_slots [t->type];
8876                                         break;
8877                                 }
8878                                 /* Fall through */
8879                         case MONO_TYPE_VALUETYPE:
8880                                 if (!vtype_stack_slots)
8881                                         vtype_stack_slots = mono_mempool_alloc0 (m->mempool, sizeof (StackSlotInfo) * 256);
8882                                 for (i = 0; i < nvtypes; ++i)
8883                                         if (t->data.klass == vtype_stack_slots [i].vtype)
8884                                                 break;
8885                                 if (i < nvtypes)
8886                                         slot_info = &vtype_stack_slots [i];
8887                                 else {
8888                                         g_assert (nvtypes < 256);
8889                                         vtype_stack_slots [nvtypes].vtype = t->data.klass;
8890                                         slot_info = &vtype_stack_slots [nvtypes];
8891                                         nvtypes ++;
8892                                 }
8893                                 break;
8894                         case MONO_TYPE_CLASS:
8895                         case MONO_TYPE_OBJECT:
8896                         case MONO_TYPE_ARRAY:
8897                         case MONO_TYPE_SZARRAY:
8898                         case MONO_TYPE_STRING:
8899                         case MONO_TYPE_PTR:
8900                         case MONO_TYPE_I:
8901                         case MONO_TYPE_U:
8902 #if SIZEOF_VOID_P == 4
8903                         case MONO_TYPE_I4:
8904 #else
8905                         case MONO_TYPE_I8:
8906 #endif
8907                                 /* Share non-float stack slots of the same size */
8908                                 slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
8909                                 break;
8910                         default:
8911                                 slot_info = &scalar_stack_slots [t->type];
8912                         }
8913                 }
8914
8915                 slot = 0xffffff;
8916                 if (m->comp_done & MONO_COMP_LIVENESS) {
8917                         //printf ("START  %2d %08x %08x\n",  vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
8918                         
8919                         /* expire old intervals in active */
8920                         while (slot_info->active) {
8921                                 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
8922
8923                                 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
8924                                         break;
8925
8926                                 //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);
8927
8928                                 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
8929                                 slot_info->slots = g_slist_prepend_mempool (m->mempool, slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
8930                         }
8931
8932                         /* 
8933                          * This also handles the case when the variable is used in an
8934                          * exception region, as liveness info is not computed there.
8935                          */
8936                         /* 
8937                          * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
8938                          * opcodes.
8939                          */
8940                         if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
8941                                 if (slot_info->slots) {
8942                                         slot = GPOINTER_TO_INT (slot_info->slots->data);
8943
8944                                         slot_info->slots = slot_info->slots->next;
8945                                 }
8946
8947                                 slot_info->active = mono_varlist_insert_sorted (m, slot_info->active, vmv, TRUE);
8948                         }
8949                 }
8950
8951                 {
8952                         static int count = 0;
8953                         count ++;
8954
8955                         /*
8956                         if (count == atoi (getenv ("COUNT")))
8957                                 printf ("LAST: %s\n", mono_method_full_name (m->method, TRUE));
8958                         if (count > atoi (getenv ("COUNT")))
8959                                 slot = 0xffffff;
8960                         else {
8961                                 mono_print_tree_nl (inst);
8962                                 }
8963                         */
8964                 }
8965                 if (slot == 0xffffff) {
8966                         /*
8967                          * Allways allocate valuetypes to sizeof (gpointer) to allow more
8968                          * efficient copying (and to work around the fact that OP_MEMCPY
8969                          * and OP_MEMSET ignores alignment).
8970                          */
8971                         if (MONO_TYPE_ISSTRUCT (t))
8972                                 align = sizeof (gpointer);
8973
8974                         if (backward) {
8975                                 offset += size;
8976                                 offset += align - 1;
8977                                 offset &= ~(align - 1);
8978                                 slot = offset;
8979                         }
8980                         else {
8981                                 offset += align - 1;
8982                                 offset &= ~(align - 1);
8983                                 slot = offset;
8984                                 offset += size;
8985                         }
8986
8987                         if (*stack_align == 0)
8988                                 *stack_align = align;
8989                 }
8990
8991                 offsets [vmv->idx] = slot;
8992         }
8993         g_list_free (vars);
8994         for (i = 0; i < MONO_TYPE_PINNED; ++i) {
8995                 if (scalar_stack_slots [i].active)
8996                         g_list_free (scalar_stack_slots [i].active);
8997         }
8998         for (i = 0; i < nvtypes; ++i) {
8999                 if (vtype_stack_slots [i].active)
9000                         g_list_free (vtype_stack_slots [i].active);
9001         }
9002
9003         mono_jit_stats.locals_stack_size += offset;
9004
9005         *stack_size = offset;
9006         return offsets;
9007 }
9008
9009 gint32*
9010 mono_allocate_stack_slots (MonoCompile *m, guint32 *stack_size, guint32 *stack_align)
9011 {
9012         return mono_allocate_stack_slots_full (m, TRUE, stack_size, stack_align);
9013 }
9014
9015 void
9016 mono_register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, gboolean no_throw)
9017 {
9018         MonoJitICallInfo *info;
9019         MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
9020
9021         if (!emul_opcode_map)
9022                 emul_opcode_map = g_new0 (MonoJitICallInfo*, OP_LAST + 1);
9023
9024         g_assert (!sig->hasthis);
9025         g_assert (sig->param_count < 3);
9026
9027         info = mono_register_jit_icall (func, name, sig, no_throw);
9028
9029         emul_opcode_map [opcode] = info;
9030 }
9031
9032 static void
9033 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
9034 {
9035         MonoMethodSignature *sig;
9036
9037         if (sigstr)
9038                 sig = mono_create_icall_signature (sigstr);
9039         else
9040                 sig = NULL;
9041
9042         mono_register_jit_icall (func, name, sig, save);
9043 }
9044
9045 static void
9046 decompose_foreach (MonoInst *tree, gpointer data) 
9047 {
9048         static MonoJitICallInfo *newarr_info = NULL;
9049         static MonoJitICallInfo *newarr_specific_info = NULL;
9050         MonoJitICallInfo *info;
9051         int i;
9052
9053         switch (tree->opcode) {
9054         case CEE_NEWARR: {
9055                 MonoCompile *cfg = data;
9056                 MonoInst *iargs [3];
9057
9058                 if (!newarr_info) {
9059                         newarr_info = mono_find_jit_icall_by_addr (mono_array_new);
9060                         g_assert (newarr_info);
9061                         newarr_specific_info = mono_find_jit_icall_by_addr (mono_array_new_specific);
9062                         g_assert (newarr_specific_info);
9063                 }
9064
9065                 if (cfg->opt & MONO_OPT_SHARED) {
9066                         NEW_DOMAINCONST (cfg, iargs [0]);
9067                         NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
9068                         iargs [2] = tree->inst_newa_len;
9069
9070                         info = newarr_info;
9071                 }
9072                 else {
9073                         MonoVTable *vtable = mono_class_vtable (cfg->domain, mono_array_class_get (tree->inst_newa_class, 1));
9074
9075                         NEW_VTABLECONST (cfg, iargs [0], vtable);
9076                         iargs [1] = tree->inst_newa_len;
9077
9078                         info = newarr_specific_info;
9079                 }
9080
9081                 mono_emulate_opcode (cfg, tree, iargs, info);
9082
9083                 /* Need to decompose arguments after the the opcode is decomposed */
9084                 for (i = 0; i < info->sig->param_count; ++i)
9085                         dec_foreach (iargs [i], cfg);
9086                 break;
9087         }
9088 #ifdef MONO_ARCH_SOFT_FLOAT
9089         case OP_FBEQ:
9090         case OP_FBGE:
9091         case OP_FBGT:
9092         case OP_FBLE:
9093         case OP_FBLT:
9094         case OP_FBNE_UN:
9095         case OP_FBGE_UN:
9096         case OP_FBGT_UN:
9097         case OP_FBLE_UN:
9098         case OP_FBLT_UN: {
9099                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
9100                         MonoCompile *cfg = data;
9101                         MonoInst *iargs [2];
9102                 
9103                         iargs [0] = tree->inst_i0;
9104                         iargs [1] = tree->inst_i1;
9105                 
9106                         mono_emulate_opcode (cfg, tree, iargs, info);
9107
9108                         dec_foreach (iargs [0], cfg);
9109                         dec_foreach (iargs [1], cfg);
9110                         break;
9111                 } else {
9112                         g_assert_not_reached ();
9113                 }
9114                 break;
9115         }
9116         case OP_FCEQ:
9117         case OP_FCGT:
9118         case OP_FCGT_UN:
9119         case OP_FCLT:
9120         case OP_FCLT_UN: {
9121                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
9122                         MonoCompile *cfg = data;
9123                         MonoInst *iargs [2];
9124
9125                         /* the args are in the compare opcode ... */
9126                         iargs [0] = tree->inst_i0;
9127                         iargs [1] = tree->inst_i1;
9128                 
9129                         mono_emulate_opcode (cfg, tree, iargs, info);
9130
9131                         dec_foreach (iargs [0], cfg);
9132                         dec_foreach (iargs [1], cfg);
9133                         break;
9134                 } else {
9135                         g_assert_not_reached ();
9136                 }
9137                 break;
9138         }
9139 #endif
9140
9141         default:
9142                 break;
9143         }
9144 }
9145
9146 void
9147 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
9148
9149         switch (mono_burg_arity [tree->opcode]) {
9150         case 0: break;
9151         case 1: 
9152                 mono_inst_foreach (tree->inst_left, func, data);
9153                 break;
9154         case 2: 
9155                 mono_inst_foreach (tree->inst_left, func, data);
9156                 mono_inst_foreach (tree->inst_right, func, data);
9157                 break;
9158         default:
9159                 g_assert_not_reached ();
9160         }
9161         func (tree, data);
9162 }
9163
9164 G_GNUC_UNUSED
9165 static void
9166 mono_print_bb_code (MonoBasicBlock *bb) {
9167         if (bb->code) {
9168                 MonoInst *c = bb->code;
9169                 while (c) {
9170                         mono_print_tree (c);
9171                         g_print ("\n");
9172                         c = c->next;
9173                 }
9174         }
9175 }
9176
9177 static void
9178 print_dfn (MonoCompile *cfg) {
9179         int i, j;
9180         char *code;
9181         MonoBasicBlock *bb;
9182
9183         g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
9184
9185         for (i = 0; i < cfg->num_bblocks; ++i) {
9186                 bb = cfg->bblocks [i];
9187                 /*if (bb->cil_code) {
9188                         char* code1, *code2;
9189                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
9190                         if (bb->last_ins->cil_code)
9191                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
9192                         else
9193                                 code2 = g_strdup ("");
9194
9195                         code1 [strlen (code1) - 1] = 0;
9196                         code = g_strdup_printf ("%s -> %s", code1, code2);
9197                         g_free (code1);
9198                         g_free (code2);
9199                 } else*/
9200                         code = g_strdup ("\n");
9201                 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
9202                 if (bb->code) {
9203                         MonoInst *c = bb->code;
9204                         while (c) {
9205                                 mono_print_tree (c);
9206                                 g_print ("\n");
9207                                 c = c->next;
9208                         }
9209                 } else {
9210
9211                 }
9212
9213                 g_print ("\tprev:");
9214                 for (j = 0; j < bb->in_count; ++j) {
9215                         g_print (" BB%d", bb->in_bb [j]->block_num);
9216                 }
9217                 g_print ("\t\tsucc:");
9218                 for (j = 0; j < bb->out_count; ++j) {
9219                         g_print (" BB%d", bb->out_bb [j]->block_num);
9220                 }
9221                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
9222
9223                 if (bb->idom)
9224                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
9225
9226                 if (bb->dominators)
9227                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
9228                 if (bb->dfrontier)
9229                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
9230                 g_free (code);
9231         }
9232
9233         g_print ("\n");
9234 }
9235
9236 void
9237 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
9238 {
9239         inst->next = NULL;
9240         if (bb->last_ins) {
9241                 g_assert (bb->code);
9242                 bb->last_ins->next = inst;
9243                 bb->last_ins = inst;
9244         } else {
9245                 bb->last_ins = bb->code = inst;
9246         }
9247 }
9248
9249 void
9250 mono_destroy_compile (MonoCompile *cfg)
9251 {
9252         //mono_mempool_stats (cfg->mempool);
9253         mono_free_loop_info (cfg);
9254         if (cfg->rs)
9255                 mono_regstate_free (cfg->rs);
9256         if (cfg->spvars)
9257                 g_hash_table_destroy (cfg->spvars);
9258         if (cfg->exvars)
9259                 g_hash_table_destroy (cfg->exvars);
9260         mono_mempool_destroy (cfg->mempool);
9261         g_list_free (cfg->ldstr_list);
9262         g_hash_table_destroy (cfg->token_info_hash);
9263
9264         g_free (cfg->varinfo);
9265         g_free (cfg->vars);
9266         g_free (cfg->exception_message);
9267         g_free (cfg);
9268 }
9269
9270 #ifdef HAVE_KW_THREAD
9271 static __thread gpointer mono_lmf_addr MONO_TLS_FAST;
9272 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
9273 /* 
9274  * When this is defined, the current lmf is stored in this tls variable instead of in 
9275  * jit_tls->lmf.
9276  */
9277 static __thread gpointer mono_lmf MONO_TLS_FAST;
9278 #endif
9279 #endif
9280
9281 guint32
9282 mono_get_jit_tls_key (void)
9283 {
9284         return mono_jit_tls_id;
9285 }
9286
9287 gint32
9288 mono_get_lmf_tls_offset (void)
9289 {
9290 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
9291         int offset;
9292         MONO_THREAD_VAR_OFFSET(mono_lmf,offset);
9293         return offset;
9294 #else
9295         return -1;
9296 #endif
9297 }
9298
9299 gint32
9300 mono_get_lmf_addr_tls_offset (void)
9301 {
9302         int offset;
9303         MONO_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
9304         return offset;
9305 }
9306
9307 MonoLMF *
9308 mono_get_lmf (void)
9309 {
9310 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
9311         return mono_lmf;
9312 #else
9313         MonoJitTlsData *jit_tls;
9314
9315         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
9316                 return jit_tls->lmf;
9317
9318         g_assert_not_reached ();
9319         return NULL;
9320 #endif
9321 }
9322
9323 MonoLMF **
9324 mono_get_lmf_addr (void)
9325 {
9326 #ifdef HAVE_KW_THREAD
9327         return mono_lmf_addr;
9328 #else
9329         MonoJitTlsData *jit_tls;
9330
9331         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
9332                 return &jit_tls->lmf;
9333
9334         g_assert_not_reached ();
9335         return NULL;
9336 #endif
9337 }
9338
9339 /* Called by native->managed wrappers */
9340 void
9341 mono_jit_thread_attach (MonoDomain *domain)
9342 {
9343 #ifdef HAVE_KW_THREAD
9344         if (!mono_lmf_addr) {
9345                 mono_thread_attach (domain);
9346         }
9347 #else
9348         if (!TlsGetValue (mono_jit_tls_id))
9349                 mono_thread_attach (domain);
9350 #endif
9351         if (mono_domain_get () != domain)
9352                 mono_domain_set (domain, TRUE);
9353 }       
9354
9355 /**
9356  * mono_thread_abort:
9357  * @obj: exception object
9358  *
9359  * abort the thread, print exception information and stack trace
9360  */
9361 static void
9362 mono_thread_abort (MonoObject *obj)
9363 {
9364         /* MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id); */
9365         
9366         /* handle_remove should be eventually called for this thread, too
9367         g_free (jit_tls);*/
9368
9369         if ((mono_runtime_unhandled_exception_policy_get () == MONO_UNHANLED_POLICY_LEGACY) ||
9370                         (obj->vtable->klass == mono_defaults.threadabortexception_class)) {
9371                 mono_thread_exit ();
9372         } else {
9373                 exit (mono_environment_exitcode_get ());
9374         }
9375 }
9376
9377 static void*
9378 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
9379 {
9380         MonoJitTlsData *jit_tls;
9381         MonoLMF *lmf;
9382
9383         jit_tls = TlsGetValue (mono_jit_tls_id);
9384         if (jit_tls)
9385                 return jit_tls;
9386
9387         jit_tls = g_new0 (MonoJitTlsData, 1);
9388
9389         TlsSetValue (mono_jit_tls_id, jit_tls);
9390
9391         jit_tls->abort_func = abort_func;
9392         jit_tls->end_of_stack = stack_start;
9393
9394         lmf = g_new0 (MonoLMF, 1);
9395         lmf->ebp = -1;
9396
9397         jit_tls->first_lmf = lmf;
9398
9399 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
9400         /* jit_tls->lmf is unused */
9401         mono_lmf = lmf;
9402         mono_lmf_addr = &mono_lmf;
9403 #else
9404 #if defined(HAVE_KW_THREAD)
9405         mono_lmf_addr = &jit_tls->lmf;  
9406 #endif
9407
9408         jit_tls->lmf = lmf;
9409 #endif
9410
9411         mono_arch_setup_jit_tls_data (jit_tls);
9412         mono_setup_altstack (jit_tls);
9413
9414         return jit_tls;
9415 }
9416
9417 static void
9418 mono_thread_start_cb (gsize tid, gpointer stack_start, gpointer func)
9419 {
9420         MonoThread *thread;
9421         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
9422         thread = mono_thread_current ();
9423         mono_debugger_thread_created (tid, thread, jit_tls);
9424         if (thread)
9425                 thread->jit_data = jit_tls;
9426 }
9427
9428 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
9429
9430 static void
9431 mono_thread_abort_dummy (MonoObject *obj)
9432 {
9433   if (mono_thread_attach_aborted_cb)
9434     mono_thread_attach_aborted_cb (obj);
9435   else
9436     mono_thread_abort (obj);
9437 }
9438
9439 static void
9440 mono_thread_attach_cb (gsize tid, gpointer stack_start)
9441 {
9442         MonoThread *thread;
9443         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
9444         thread = mono_thread_current ();
9445         mono_debugger_thread_created (tid, thread, (MonoJitTlsData *) jit_tls);
9446         if (thread)
9447                 thread->jit_data = jit_tls;
9448         if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
9449                 setup_stat_profiler ();
9450 }
9451
9452 static void
9453 mini_thread_cleanup (MonoThread *thread)
9454 {
9455         MonoJitTlsData *jit_tls = thread->jit_data;
9456
9457         if (jit_tls) {
9458                 mono_debugger_thread_cleanup (jit_tls);
9459                 mono_arch_free_jit_tls_data (jit_tls);
9460
9461                 mono_free_altstack (jit_tls);
9462                 g_free (jit_tls->first_lmf);
9463                 g_free (jit_tls);
9464                 thread->jit_data = NULL;
9465                 TlsSetValue (mono_jit_tls_id, NULL);
9466         }
9467 }
9468
9469 void
9470 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
9471 {
9472         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
9473
9474         ji->ip.i = ip;
9475         ji->type = type;
9476         ji->data.target = target;
9477         ji->next = cfg->patch_info;
9478
9479         cfg->patch_info = ji;
9480 }
9481
9482 void
9483 mono_remove_patch_info (MonoCompile *cfg, int ip)
9484 {
9485         MonoJumpInfo **ji = &cfg->patch_info;
9486
9487         while (*ji) {
9488                 if ((*ji)->ip.i == ip)
9489                         *ji = (*ji)->next;
9490                 else
9491                         ji = &((*ji)->next);
9492         }
9493 }
9494
9495 /**
9496  * mono_patch_info_dup_mp:
9497  *
9498  * Make a copy of PATCH_INFO, allocating memory from the mempool MP.
9499  */
9500 MonoJumpInfo*
9501 mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info)
9502 {
9503         MonoJumpInfo *res = mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
9504         memcpy (res, patch_info, sizeof (MonoJumpInfo));
9505
9506         switch (patch_info->type) {
9507         case MONO_PATCH_INFO_RVA:
9508         case MONO_PATCH_INFO_LDSTR:
9509         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
9510         case MONO_PATCH_INFO_LDTOKEN:
9511         case MONO_PATCH_INFO_DECLSEC:
9512                 res->data.token = mono_mempool_alloc (mp, sizeof (MonoJumpInfoToken));
9513                 memcpy (res->data.token, patch_info->data.token, sizeof (MonoJumpInfoToken));
9514                 break;
9515         case MONO_PATCH_INFO_SWITCH:
9516                 res->data.table = mono_mempool_alloc (mp, sizeof (MonoJumpInfoBBTable));
9517                 memcpy (res->data.table, patch_info->data.table, sizeof (MonoJumpInfoBBTable));
9518                 break;
9519         default:
9520                 break;
9521         }
9522
9523         return res;
9524 }
9525
9526 guint
9527 mono_patch_info_hash (gconstpointer data)
9528 {
9529         const MonoJumpInfo *ji = (MonoJumpInfo*)data;
9530
9531         switch (ji->type) {
9532         case MONO_PATCH_INFO_RVA:
9533         case MONO_PATCH_INFO_LDSTR:
9534         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
9535         case MONO_PATCH_INFO_LDTOKEN:
9536         case MONO_PATCH_INFO_DECLSEC:
9537                 return (ji->type << 8) | ji->data.token->token;
9538         case MONO_PATCH_INFO_VTABLE:
9539         case MONO_PATCH_INFO_CLASS:
9540         case MONO_PATCH_INFO_IID:
9541         case MONO_PATCH_INFO_ADJUSTED_IID:
9542                 return (ji->type << 8) | (gssize)ji->data.klass;
9543         case MONO_PATCH_INFO_FIELD:
9544         case MONO_PATCH_INFO_SFLDA:
9545                 return (ji->type << 8) | (gssize)ji->data.field;
9546         case MONO_PATCH_INFO_METHODCONST:
9547         case MONO_PATCH_INFO_METHOD:
9548         case MONO_PATCH_INFO_METHOD_JUMP:
9549                 return (ji->type << 8) | (gssize)ji->data.method;
9550         case MONO_PATCH_INFO_IMAGE:
9551                 return (ji->type << 8) | (gssize)ji->data.image;                
9552         default:
9553                 return (ji->type << 8);
9554         }
9555 }
9556
9557 /* 
9558  * mono_patch_info_equal:
9559  * 
9560  * This might fail to recognize equivalent patches, i.e. floats, so its only
9561  * usable in those cases where this is not a problem, i.e. sharing GOT slots
9562  * in AOT.
9563  */
9564 gint
9565 mono_patch_info_equal (gconstpointer ka, gconstpointer kb)
9566 {
9567         const MonoJumpInfo *ji1 = (MonoJumpInfo*)ka;
9568         const MonoJumpInfo *ji2 = (MonoJumpInfo*)kb;
9569
9570         if (ji1->type != ji2->type)
9571                 return 0;
9572
9573         switch (ji1->type) {
9574         case MONO_PATCH_INFO_RVA:
9575         case MONO_PATCH_INFO_LDSTR:
9576         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
9577         case MONO_PATCH_INFO_LDTOKEN:
9578         case MONO_PATCH_INFO_DECLSEC:
9579                 if ((ji1->data.token->image != ji2->data.token->image) ||
9580                         (ji1->data.token->token != ji2->data.token->token))
9581                         return 0;
9582                 break;
9583         default:
9584                 if (ji1->data.name != ji2->data.name)
9585                         return 0;
9586                 break;
9587         }
9588
9589         return 1;
9590 }
9591
9592 gpointer
9593 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
9594 {
9595         unsigned char *ip = patch_info->ip.i + code;
9596         gconstpointer target = NULL;
9597
9598         switch (patch_info->type) {
9599         case MONO_PATCH_INFO_BB:
9600                 target = patch_info->data.bb->native_offset + code;
9601                 break;
9602         case MONO_PATCH_INFO_ABS:
9603                 target = patch_info->data.target;
9604                 break;
9605         case MONO_PATCH_INFO_LABEL:
9606                 target = patch_info->data.inst->inst_c0 + code;
9607                 break;
9608         case MONO_PATCH_INFO_IP:
9609                 target = ip;
9610                 break;
9611         case MONO_PATCH_INFO_METHOD_REL:
9612                 target = code + patch_info->data.offset;
9613                 break;
9614         case MONO_PATCH_INFO_INTERNAL_METHOD: {
9615                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
9616                 if (!mi) {
9617                         g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
9618                         g_assert_not_reached ();
9619                 }
9620                 target = mono_icall_get_wrapper (mi);
9621                 break;
9622         }
9623         case MONO_PATCH_INFO_METHOD_JUMP: {
9624                 GSList *list;
9625
9626                 /* get the trampoline to the method from the domain */
9627                 target = mono_create_jump_trampoline (domain, patch_info->data.method, TRUE);
9628                 if (!domain->jump_target_hash)
9629                         domain->jump_target_hash = g_hash_table_new (NULL, NULL);
9630                 list = g_hash_table_lookup (domain->jump_target_hash, patch_info->data.method);
9631                 list = g_slist_prepend (list, ip);
9632                 g_hash_table_insert (domain->jump_target_hash, patch_info->data.method, list);
9633                 break;
9634         }
9635         case MONO_PATCH_INFO_METHOD:
9636                 if (patch_info->data.method == method) {
9637                         target = code;
9638                 } else
9639                         /* get the trampoline to the method from the domain */
9640                         target = mono_create_jit_trampoline (patch_info->data.method);
9641                 break;
9642         case MONO_PATCH_INFO_SWITCH: {
9643                 gpointer *jump_table;
9644                 int i;
9645
9646                 if (method && method->dynamic) {
9647                         jump_table = mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
9648                 } else {
9649                         mono_domain_lock (domain);
9650                         jump_table = mono_code_manager_reserve (domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
9651                         mono_domain_unlock (domain);
9652                 }
9653
9654                 for (i = 0; i < patch_info->data.table->table_size; i++) {
9655                         jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
9656                 }
9657                 target = jump_table;
9658                 break;
9659         }
9660         case MONO_PATCH_INFO_METHODCONST:
9661         case MONO_PATCH_INFO_CLASS:
9662         case MONO_PATCH_INFO_IMAGE:
9663         case MONO_PATCH_INFO_FIELD:
9664                 target = patch_info->data.target;
9665                 break;
9666         case MONO_PATCH_INFO_IID:
9667                 mono_class_init (patch_info->data.klass);
9668                 target = GINT_TO_POINTER ((int)patch_info->data.klass->interface_id);
9669                 break;
9670         case MONO_PATCH_INFO_ADJUSTED_IID:
9671                 mono_class_init (patch_info->data.klass);
9672                 target = GINT_TO_POINTER ((int)(-((patch_info->data.klass->interface_id + 1) * SIZEOF_VOID_P)));
9673                 break;
9674         case MONO_PATCH_INFO_VTABLE:
9675                 target = mono_class_vtable (domain, patch_info->data.klass);
9676                 break;
9677         case MONO_PATCH_INFO_CLASS_INIT:
9678                 target = mono_create_class_init_trampoline (mono_class_vtable (domain, patch_info->data.klass));
9679                 break;
9680         case MONO_PATCH_INFO_SFLDA: {
9681                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
9682                 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && (method && mono_class_needs_cctor_run (vtable->klass, method)))
9683                         /* Done by the generated code */
9684                         ;
9685                 else {
9686                         if (run_cctors)
9687                                 mono_runtime_class_init (vtable);
9688                 }
9689                 target = (char*)vtable->data + patch_info->data.field->offset;
9690                 break;
9691         }
9692         case MONO_PATCH_INFO_RVA:
9693                 target = mono_image_rva_map (patch_info->data.token->image, patch_info->data.token->token);
9694                 break;
9695         case MONO_PATCH_INFO_R4:
9696         case MONO_PATCH_INFO_R8:
9697                 target = patch_info->data.target;
9698                 break;
9699         case MONO_PATCH_INFO_EXC_NAME:
9700                 target = patch_info->data.name;
9701                 break;
9702         case MONO_PATCH_INFO_LDSTR:
9703                 target =
9704                         mono_ldstr (domain, patch_info->data.token->image, 
9705                                                 mono_metadata_token_index (patch_info->data.token->token));
9706                 break;
9707         case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
9708                 gpointer handle;
9709                 MonoClass *handle_class;
9710
9711                 handle = mono_ldtoken (patch_info->data.token->image, 
9712                                        patch_info->data.token->token, &handle_class, NULL);
9713                 mono_class_init (handle_class);
9714                 mono_class_init (mono_class_from_mono_type (handle));
9715
9716                 target =
9717                         mono_type_get_object (domain, handle);
9718                 break;
9719         }
9720         case MONO_PATCH_INFO_LDTOKEN: {
9721                 gpointer handle;
9722                 MonoClass *handle_class;
9723                 
9724                 handle = mono_ldtoken (patch_info->data.token->image,
9725                                        patch_info->data.token->token, &handle_class, NULL);
9726                 mono_class_init (handle_class);
9727                 
9728                 target = handle;
9729                 break;
9730         }
9731         case MONO_PATCH_INFO_DECLSEC:
9732                 target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
9733                 break;
9734         case MONO_PATCH_INFO_BB_OVF:
9735         case MONO_PATCH_INFO_EXC_OVF:
9736         case MONO_PATCH_INFO_GOT_OFFSET:
9737         case MONO_PATCH_INFO_NONE:
9738                 break;
9739         default:
9740                 g_assert_not_reached ();
9741         }
9742
9743         return (gpointer)target;
9744 }
9745
9746 static void
9747 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
9748         MonoJitICallInfo *info;
9749
9750         decompose_foreach (tree, cfg);
9751
9752         switch (mono_burg_arity [tree->opcode]) {
9753         case 0: break;
9754         case 1: 
9755                 dec_foreach (tree->inst_left, cfg);
9756
9757                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
9758                         MonoInst *iargs [2];
9759                 
9760                         iargs [0] = tree->inst_left;
9761
9762                         mono_emulate_opcode (cfg, tree, iargs, info);
9763                         return;
9764                 }
9765
9766                 break;
9767         case 2:
9768 #ifdef MONO_ARCH_BIGMUL_INTRINS
9769                 if (tree->opcode == OP_LMUL
9770                                 && (cfg->opt & MONO_OPT_INTRINS)
9771                                 && (tree->inst_left->opcode == CEE_CONV_I8 
9772                                         || tree->inst_left->opcode == CEE_CONV_U8)
9773                                 && tree->inst_left->inst_left->type == STACK_I4
9774                                 && (tree->inst_right->opcode == CEE_CONV_I8 
9775                                         || tree->inst_right->opcode == CEE_CONV_U8)
9776                                 && tree->inst_right->inst_left->type == STACK_I4
9777                                 && tree->inst_left->opcode == tree->inst_right->opcode) {
9778                         tree->opcode = (tree->inst_left->opcode == CEE_CONV_I8 ? OP_BIGMUL: OP_BIGMUL_UN);
9779                         tree->inst_left = tree->inst_left->inst_left;
9780                         tree->inst_right = tree->inst_right->inst_left;
9781                         dec_foreach (tree, cfg);
9782                 } else 
9783 #endif
9784                         if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
9785                         MonoInst *iargs [2];
9786                 
9787                         iargs [0] = tree->inst_i0;
9788                         iargs [1] = tree->inst_i1;
9789                 
9790                         mono_emulate_opcode (cfg, tree, iargs, info);
9791
9792                         dec_foreach (iargs [0], cfg);
9793                         dec_foreach (iargs [1], cfg);
9794                         return;
9795                 } else {
9796                         dec_foreach (tree->inst_left, cfg);
9797                         dec_foreach (tree->inst_right, cfg);
9798                 }
9799                 break;
9800         default:
9801                 g_assert_not_reached ();
9802         }
9803 }
9804
9805 static void
9806 decompose_pass (MonoCompile *cfg) {
9807         MonoBasicBlock *bb;
9808
9809         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9810                 MonoInst *tree;
9811                 cfg->cbb = bb;
9812                 cfg->prev_ins = NULL;
9813                 for (tree = cfg->cbb->code; tree; tree = tree->next) {
9814                         dec_foreach (tree, cfg);
9815                         cfg->prev_ins = tree;
9816                 }
9817         }
9818 }
9819
9820 static void
9821 nullify_basic_block (MonoBasicBlock *bb) 
9822 {
9823         bb->in_count = 0;
9824         bb->out_count = 0;
9825         bb->in_bb = NULL;
9826         bb->out_bb = NULL;
9827         bb->next_bb = NULL;
9828         bb->code = bb->last_ins = NULL;
9829         bb->cil_code = NULL;
9830 }
9831
9832 static void 
9833 replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
9834 {
9835         int i;
9836
9837         for (i = 0; i < bb->out_count; i++) {
9838                 MonoBasicBlock *ob = bb->out_bb [i];
9839                 if (ob == orig) {
9840                         if (!repl) {
9841                                 if (bb->out_count > 1) {
9842                                         bb->out_bb [i] = bb->out_bb [bb->out_count - 1];
9843                                 }
9844                                 bb->out_count--;
9845                         } else {
9846                                 bb->out_bb [i] = repl;
9847                         }
9848                 }
9849         }
9850 }
9851
9852 static void 
9853 replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
9854 {
9855         int i;
9856
9857         for (i = 0; i < bb->in_count; i++) {
9858                 MonoBasicBlock *ib = bb->in_bb [i];
9859                 if (ib == orig) {
9860                         if (!repl) {
9861                                 if (bb->in_count > 1) {
9862                                         bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
9863                                 }
9864                                 bb->in_count--;
9865                         } else {
9866                                 bb->in_bb [i] = repl;
9867                         }
9868                 }
9869         }
9870 }
9871
9872 static void
9873 replace_out_block_in_code (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl) {
9874         MonoInst *inst;
9875         
9876         for (inst = bb->code; inst != NULL; inst = inst->next) {
9877                 if (inst->opcode == OP_CALL_HANDLER) {
9878                         if (inst->inst_target_bb == orig) {
9879                                 inst->inst_target_bb = repl;
9880                         }
9881                 }
9882         }
9883         if (bb->last_ins != NULL) {
9884                 switch (bb->last_ins->opcode) {
9885                 case OP_BR:
9886                         if (bb->last_ins->inst_target_bb == orig) {
9887                                 bb->last_ins->inst_target_bb = repl;
9888                         }
9889                         break;
9890                 case CEE_SWITCH: {
9891                         int i;
9892                         int n = GPOINTER_TO_INT (bb->last_ins->klass);
9893                         for (i = 0; i < n; i++ ) {
9894                                 if (bb->last_ins->inst_many_bb [i] == orig) {
9895                                         bb->last_ins->inst_many_bb [i] = repl;
9896                                 }
9897                         }
9898                         break;
9899                 }
9900                 case CEE_BNE_UN:
9901                 case CEE_BEQ:
9902                 case CEE_BLT:
9903                 case CEE_BLT_UN:
9904                 case CEE_BGT:
9905                 case CEE_BGT_UN:
9906                 case CEE_BGE:
9907                 case CEE_BGE_UN:
9908                 case CEE_BLE:
9909                 case CEE_BLE_UN:
9910                         if (bb->last_ins->inst_true_bb == orig) {
9911                                 bb->last_ins->inst_true_bb = repl;
9912                         }
9913                         if (bb->last_ins->inst_false_bb == orig) {
9914                                 bb->last_ins->inst_false_bb = repl;
9915                         }
9916                         break;
9917                 default:
9918                         break;
9919                 }
9920         }
9921 }
9922
9923 static void 
9924 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
9925 {
9926         int i, j;
9927
9928         for (i = 0; i < bb->out_count; i++) {
9929                 MonoBasicBlock *ob = bb->out_bb [i];
9930                 for (j = 0; j < ob->in_count; j++) {
9931                         if (ob->in_bb [j] == orig) {
9932                                 ob->in_bb [j] = repl;
9933                         }
9934                 }
9935         }
9936
9937 }
9938
9939 /**
9940   * Check if a bb is useless (is just made of NOPs and ends with an
9941   * unconditional branch, or nothing).
9942   * If it is so, unlink it from the CFG and nullify it, and return TRUE.
9943   * Otherwise, return FALSE;
9944   */
9945 static gboolean
9946 remove_block_if_useless (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *previous_bb) {
9947         MonoBasicBlock *target_bb = NULL;
9948         MonoInst *inst;
9949         
9950         /* Do not touch handlers */
9951         if (bb->region != -1) {
9952                 bb->not_useless = TRUE;
9953                 return FALSE;
9954         }
9955         
9956         for (inst = bb->code; inst != NULL; inst = inst->next) {
9957                 switch (inst->opcode) {
9958                 case OP_NOP:
9959                         break;
9960                 case OP_BR:
9961                         target_bb = inst->inst_target_bb;
9962                         break;
9963                 default:
9964                         bb->not_useless = TRUE;
9965                         return FALSE;
9966                 }
9967         }
9968         
9969         if (target_bb == NULL) {
9970                 if ((bb->out_count == 1) && (bb->out_bb [0] == bb->next_bb)) {
9971                         target_bb = bb->next_bb;
9972                 } else {
9973                         /* Do not touch empty BBs that do not "fall through" to their next BB (like the exit BB) */
9974                         return FALSE;
9975                 }
9976         }
9977         
9978         /* Do not touch BBs following a switch (they are the "default" branch) */
9979         if ((previous_bb->last_ins != NULL) && (previous_bb->last_ins->opcode == CEE_SWITCH)) {
9980                 return FALSE;
9981         }
9982         
9983         /* Do not touch BBs following the entry BB and jumping to something that is not */
9984         /* thiry "next" bb (the entry BB cannot contain the branch) */
9985         if ((previous_bb == cfg->bb_entry) && (bb->next_bb != target_bb)) {
9986                 return FALSE;
9987         }
9988
9989         /* 
9990          * Do not touch BBs following a try block as the code in 
9991          * mini_method_compile needs them to compute the length of the try block.
9992          */
9993         if (MONO_BBLOCK_IS_IN_REGION (previous_bb, MONO_REGION_TRY))
9994                 return FALSE;
9995         
9996         /* Check that there is a target BB, and that bb is not an empty loop (Bug 75061) */
9997         if ((target_bb != NULL) && (target_bb != bb)) {
9998                 int i;
9999
10000                 if (cfg->verbose_level > 1) {
10001                         printf ("remove_block_if_useless %s, removed BB%d\n", mono_method_full_name (cfg->method, TRUE), bb->block_num);
10002                 }
10003                 
10004                 /* unlink_bblock () modifies the bb->in_bb array so can't use a for loop here */
10005                 while (bb->in_count) {
10006                         MonoBasicBlock *in_bb = bb->in_bb [0];
10007                         mono_unlink_bblock (cfg, in_bb, bb);
10008                         link_bblock (cfg, in_bb, target_bb);
10009                         replace_out_block_in_code (in_bb, bb, target_bb);
10010                 }
10011                 
10012                 mono_unlink_bblock (cfg, bb, target_bb);
10013                 
10014                 if ((previous_bb != cfg->bb_entry) &&
10015                                 (previous_bb->region == bb->region) &&
10016                                 ((previous_bb->last_ins == NULL) ||
10017                                 ((previous_bb->last_ins->opcode != OP_BR) &&
10018                                 (! (MONO_IS_COND_BRANCH_OP (previous_bb->last_ins))) &&
10019                                 (previous_bb->last_ins->opcode != CEE_SWITCH)))) {
10020                         for (i = 0; i < previous_bb->out_count; i++) {
10021                                 if (previous_bb->out_bb [i] == target_bb) {
10022                                         MonoInst *jump;
10023                                         MONO_INST_NEW (cfg, jump, OP_BR);
10024                                         MONO_ADD_INS (previous_bb, jump);
10025                                         jump->cil_code = previous_bb->cil_code;
10026                                         jump->inst_target_bb = target_bb;
10027                                         break;
10028                                 }
10029                         }
10030                 }
10031                 
10032                 previous_bb->next_bb = bb->next_bb;
10033                 nullify_basic_block (bb);
10034                 
10035                 return TRUE;
10036         } else {
10037                 return FALSE;
10038         }
10039 }
10040
10041 static void
10042 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn) 
10043 {
10044         bb->out_count = bbn->out_count;
10045         bb->out_bb = bbn->out_bb;
10046
10047         replace_basic_block (bb, bbn, bb);
10048
10049         /* Nullify branch at the end of bb */
10050         if (bb->last_ins && MONO_IS_BRANCH_OP (bb->last_ins)) {
10051                 bb->last_ins->opcode = OP_NOP;
10052         }               
10053
10054         if (bb->last_ins) {
10055                 if (bbn->code) {
10056                         bb->last_ins->next = bbn->code;
10057                         bb->last_ins = bbn->last_ins;
10058                 }
10059         } else {
10060                 bb->code = bbn->code;
10061                 bb->last_ins = bbn->last_ins;
10062         }
10063         bb->next_bb = bbn->next_bb;
10064         nullify_basic_block (bbn);
10065 }
10066
10067 static void
10068 move_basic_block_to_end (MonoCompile *cfg, MonoBasicBlock *bb)
10069 {
10070         MonoBasicBlock *bbn, *next;
10071
10072         next = bb->next_bb;
10073
10074         /* Find the previous */
10075         for (bbn = cfg->bb_entry; bbn->next_bb && bbn->next_bb != bb; bbn = bbn->next_bb)
10076                 ;
10077         if (bbn->next_bb) {
10078                 bbn->next_bb = bb->next_bb;
10079         }
10080
10081         /* Find the last */
10082         for (bbn = cfg->bb_entry; bbn->next_bb; bbn = bbn->next_bb)
10083                 ;
10084         bbn->next_bb = bb;
10085         bb->next_bb = NULL;
10086
10087         /* Add a branch */
10088         if (next && (!bb->last_ins || (bb->last_ins->opcode != OP_NOT_REACHED))) {
10089                 MonoInst *ins;
10090
10091                 MONO_INST_NEW (cfg, ins, OP_BR);
10092                 MONO_ADD_INS (bb, ins);
10093                 link_bblock (cfg, bb, next);
10094                 ins->inst_target_bb = next;
10095         }               
10096 }
10097
10098 /* checks that a and b represent the same instructions, conservatively,
10099  * it can return FALSE also for two trees that are equal.
10100  * FIXME: also make sure there are no side effects.
10101  */
10102 static int
10103 same_trees (MonoInst *a, MonoInst *b)
10104 {
10105         int arity;
10106         if (a->opcode != b->opcode)
10107                 return FALSE;
10108         arity = mono_burg_arity [a->opcode];
10109         if (arity == 1) {
10110                 if (a->ssa_op == b->ssa_op && a->ssa_op == MONO_SSA_LOAD && a->inst_i0 == b->inst_i0)
10111                         return TRUE;
10112                 return same_trees (a->inst_left, b->inst_left);
10113         } else if (arity == 2) {
10114                 return same_trees (a->inst_left, b->inst_left) && same_trees (a->inst_right, b->inst_right);
10115         } else if (arity == 0) {
10116                 switch (a->opcode) {
10117                 case OP_ICONST:
10118                         return a->inst_c0 == b->inst_c0;
10119                 default:
10120                         return FALSE;
10121                 }
10122         }
10123         return FALSE;
10124 }
10125
10126 static int
10127 get_unsigned_condbranch (int opcode)
10128 {
10129         switch (opcode) {
10130         case CEE_BLE: return CEE_BLE_UN;
10131         case CEE_BLT: return CEE_BLT_UN;
10132         case CEE_BGE: return CEE_BGE_UN;
10133         case CEE_BGT: return CEE_BGT_UN;
10134         }
10135         g_assert_not_reached ();
10136         return 0;
10137 }
10138
10139 static int
10140 tree_is_unsigned (MonoInst* ins) {
10141         switch (ins->opcode) {
10142         case OP_ICONST:
10143                 return (int)ins->inst_c0 >= 0;
10144         /* array lengths are positive as are string sizes */
10145         case CEE_LDLEN:
10146         case OP_STRLEN:
10147                 return TRUE;
10148         case CEE_CONV_U1:
10149         case CEE_CONV_U2:
10150         case CEE_CONV_U4:
10151         case CEE_CONV_OVF_U1:
10152         case CEE_CONV_OVF_U2:
10153         case CEE_CONV_OVF_U4:
10154                 return TRUE;
10155         case CEE_LDIND_U1:
10156         case CEE_LDIND_U2:
10157         case CEE_LDIND_U4:
10158                 return TRUE;
10159         default:
10160                 return FALSE;
10161         }
10162 }
10163
10164 /* check if an unsigned compare can be used instead of two signed compares
10165  * for (val < 0 || val > limit) conditionals.
10166  * Returns TRUE if the optimization has been applied.
10167  * Note that this can't be applied if the second arg is not positive...
10168  */
10169 static int
10170 try_unsigned_compare (MonoCompile *cfg, MonoBasicBlock *bb)
10171 {
10172         MonoBasicBlock *truet, *falset;
10173         MonoInst *cmp_inst = bb->last_ins->inst_left;
10174         MonoInst *condb;
10175         if (!cmp_inst->inst_right->inst_c0 == 0)
10176                 return FALSE;
10177         truet = bb->last_ins->inst_true_bb;
10178         falset = bb->last_ins->inst_false_bb;
10179         if (falset->in_count != 1)
10180                 return FALSE;
10181         condb = falset->last_ins;
10182         /* target bb must have one instruction */
10183         if (!condb || (condb != falset->code))
10184                 return FALSE;
10185         if ((((condb->opcode == CEE_BLE || condb->opcode == CEE_BLT) && (condb->inst_false_bb == truet))
10186                         || ((condb->opcode == CEE_BGE || condb->opcode == CEE_BGT) && (condb->inst_true_bb == truet)))
10187                         && same_trees (cmp_inst->inst_left, condb->inst_left->inst_left)) {
10188                 if (!tree_is_unsigned (condb->inst_left->inst_right))
10189                         return FALSE;
10190                 condb->opcode = get_unsigned_condbranch (condb->opcode);
10191                 /* change the original condbranch to just point to the new unsigned check */
10192                 bb->last_ins->opcode = OP_BR;
10193                 bb->last_ins->inst_target_bb = falset;
10194                 replace_out_block (bb, truet, NULL);
10195                 replace_in_block (truet, bb, NULL);
10196                 return TRUE;
10197         }
10198         return FALSE;
10199 }
10200
10201 /*
10202  * Optimizes the branches on the Control Flow Graph
10203  *
10204  */
10205 static void
10206 optimize_branches (MonoCompile *cfg)
10207 {
10208         int i, changed = FALSE;
10209         MonoBasicBlock *bb, *bbn;
10210         guint32 niterations;
10211
10212         /*
10213          * Some crazy loops could cause the code below to go into an infinite
10214          * loop, see bug #53003 for an example. To prevent this, we put an upper
10215          * bound on the number of iterations.
10216          */
10217         if (cfg->num_bblocks > 1000)
10218                 niterations = cfg->num_bblocks * 2;
10219         else
10220                 niterations = 1000;
10221
10222         do {
10223                 MonoBasicBlock *previous_bb;
10224                 changed = FALSE;
10225                 niterations --;
10226
10227                 /* we skip the entry block (exit is handled specially instead ) */
10228                 for (previous_bb = cfg->bb_entry, bb = cfg->bb_entry->next_bb; bb; previous_bb = bb, bb = bb->next_bb) {
10229
10230                         /* dont touch code inside exception clauses */
10231                         if (bb->region != -1)
10232                                 continue;
10233
10234                         if (!bb->not_useless && remove_block_if_useless (cfg, bb, previous_bb)) {
10235                                 changed = TRUE;
10236                                 continue;
10237                         }
10238
10239                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
10240                                 if (cfg->verbose_level > 2)
10241                                         g_print ("nullify block triggered %d\n", bbn->block_num);
10242
10243                                 bb->next_bb = bbn->next_bb;
10244
10245                                 for (i = 0; i < bbn->out_count; i++)
10246                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
10247
10248                                 nullify_basic_block (bbn);                      
10249                                 changed = TRUE;
10250                         }
10251
10252                         if (bb->out_count == 1) {
10253                                 bbn = bb->out_bb [0];
10254
10255                                 /* conditional branches where true and false targets are the same can be also replaced with OP_BR */
10256                                 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins)) {
10257                                         MonoInst *pop;
10258                                         MONO_INST_NEW (cfg, pop, CEE_POP);
10259                                         pop->inst_left = bb->last_ins->inst_left->inst_left;
10260                                         mono_add_ins_to_end (bb, pop);
10261                                         MONO_INST_NEW (cfg, pop, CEE_POP);
10262                                         pop->inst_left = bb->last_ins->inst_left->inst_right;
10263                                         mono_add_ins_to_end (bb, pop);
10264                                         bb->last_ins->opcode = OP_BR;
10265                                         bb->last_ins->inst_target_bb = bb->last_ins->inst_true_bb;
10266                                         changed = TRUE;
10267                                         if (cfg->verbose_level > 2)
10268                                                 g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count);
10269                                 }
10270
10271                                 if (bb->region == bbn->region && bb->next_bb == bbn) {
10272                                         /* the block are in sequence anyway ... */
10273
10274                                         /* branches to the following block can be removed */
10275                                         if (bb->last_ins && bb->last_ins->opcode == OP_BR) {
10276                                                 bb->last_ins->opcode = OP_NOP;
10277                                                 changed = TRUE;
10278                                                 if (cfg->verbose_level > 2)
10279                                                         g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
10280                                         }
10281
10282                                         if (bbn->in_count == 1) {
10283
10284                                                 if (bbn != cfg->bb_exit) {
10285                                                         if (cfg->verbose_level > 2)
10286                                                                 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
10287                                                         merge_basic_blocks (bb, bbn);
10288                                                         changed = TRUE;
10289                                                         continue;
10290                                                 }
10291
10292                                                 //mono_print_bb_code (bb);
10293                                         }
10294                                 }
10295                         }
10296                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
10297                                 if (cfg->verbose_level > 2) {
10298                                         g_print ("nullify block triggered %d\n", bbn->block_num);
10299                                 }
10300                                 bb->next_bb = bbn->next_bb;
10301
10302                                 for (i = 0; i < bbn->out_count; i++)
10303                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
10304
10305                                 nullify_basic_block (bbn);                      
10306                                 changed = TRUE;
10307                                 continue;
10308                         }
10309
10310                         if (bb->out_count == 1) {
10311                                 bbn = bb->out_bb [0];
10312
10313                                 if (bb->last_ins && bb->last_ins->opcode == OP_BR) {
10314                                         bbn = bb->last_ins->inst_target_bb;
10315                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == OP_BR &&
10316                                             bbn->code->inst_target_bb->region == bb->region) {
10317                                                 
10318                                                 if (cfg->verbose_level > 2)
10319                                                         g_print ("in %s branch to branch triggered %d -> %d -> %d\n", cfg->method->name, 
10320                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num);
10321
10322                                                 replace_in_block (bbn, bb, NULL);
10323                                                 replace_out_block (bb, bbn, bbn->code->inst_target_bb);
10324                                                 link_bblock (cfg, bb, bbn->code->inst_target_bb);
10325                                                 bb->last_ins->inst_target_bb = bbn->code->inst_target_bb;
10326                                                 changed = TRUE;
10327                                                 continue;
10328                                         }
10329                                 }
10330                         } else if (bb->out_count == 2) {
10331                                 if (bb->last_ins && MONO_IS_COND_BRANCH_NOFP (bb->last_ins)) {
10332                                         int branch_result = mono_eval_cond_branch (bb->last_ins);
10333                                         MonoBasicBlock *taken_branch_target = NULL, *untaken_branch_target = NULL;
10334                                         if (branch_result == BRANCH_TAKEN) {
10335                                                 taken_branch_target = bb->last_ins->inst_true_bb;
10336                                                 untaken_branch_target = bb->last_ins->inst_false_bb;
10337                                         } else if (branch_result == BRANCH_NOT_TAKEN) {
10338                                                 taken_branch_target = bb->last_ins->inst_false_bb;
10339                                                 untaken_branch_target = bb->last_ins->inst_true_bb;
10340                                         }
10341                                         if (taken_branch_target) {
10342                                                 /* if mono_eval_cond_branch () is ever taken to handle 
10343                                                  * non-constant values to compare, issue a pop here.
10344                                                  */
10345                                                 bb->last_ins->opcode = OP_BR;
10346                                                 bb->last_ins->inst_target_bb = taken_branch_target;
10347                                                 mono_unlink_bblock (cfg, bb, untaken_branch_target);
10348                                                 changed = TRUE;
10349                                                 continue;
10350                                         }
10351                                         bbn = bb->last_ins->inst_true_bb;
10352                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == OP_BR &&
10353                                             bbn->code->inst_target_bb->region == bb->region) {
10354                                                 if (cfg->verbose_level > 2)             
10355                                                         g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n", 
10356                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num, 
10357                                                                  bbn->code->opcode);
10358
10359                                                 /* 
10360                                                  * Unlink, then relink bblocks to avoid various
10361                                                  * tricky situations when the two targets of the branch
10362                                                  * are equal, or will become equal after the change.
10363                                                  */
10364                                                 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_true_bb);
10365                                                 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_false_bb);
10366
10367                                                 bb->last_ins->inst_true_bb = bbn->code->inst_target_bb;
10368
10369                                                 link_bblock (cfg, bb, bb->last_ins->inst_true_bb);
10370                                                 link_bblock (cfg, bb, bb->last_ins->inst_false_bb);
10371
10372                                                 changed = TRUE;
10373                                                 continue;
10374                                         }
10375
10376                                         bbn = bb->last_ins->inst_false_bb;
10377                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == OP_BR &&
10378                                             bbn->code->inst_target_bb->region == bb->region) {
10379                                                 if (cfg->verbose_level > 2)
10380                                                         g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n", 
10381                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num, 
10382                                                                  bbn->code->opcode);
10383
10384                                                 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_true_bb);
10385                                                 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_false_bb);
10386
10387                                                 bb->last_ins->inst_false_bb = bbn->code->inst_target_bb;
10388
10389                                                 link_bblock (cfg, bb, bb->last_ins->inst_true_bb);
10390                                                 link_bblock (cfg, bb, bb->last_ins->inst_false_bb);
10391
10392                                                 changed = TRUE;
10393                                                 continue;
10394                                         }
10395                                 }
10396
10397                                 /* detect and optimize to unsigned compares checks like: if (v < 0 || v > limit */
10398                                 if (bb->last_ins && bb->last_ins->opcode == CEE_BLT && bb->last_ins->inst_left->inst_right->opcode == OP_ICONST) {
10399                                         if (try_unsigned_compare (cfg, bb)) {
10400                                                 /*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));*/
10401                                                 changed = TRUE;
10402                                                 continue;
10403                                         }
10404                                 }
10405
10406                                 if (bb->last_ins && MONO_IS_COND_BRANCH_NOFP (bb->last_ins)) {
10407                                         if (bb->last_ins->inst_false_bb->out_of_line && (bb->region == bb->last_ins->inst_false_bb->region)) {
10408                                                 /* Reverse the branch */
10409                                                 bb->last_ins->opcode = reverse_branch_op (bb->last_ins->opcode);
10410                                                 bbn = bb->last_ins->inst_false_bb;
10411                                                 bb->last_ins->inst_false_bb = bb->last_ins->inst_true_bb;
10412                                                 bb->last_ins->inst_true_bb = bbn;
10413
10414                                                 move_basic_block_to_end (cfg, bb->last_ins->inst_true_bb);
10415                                                 if (cfg->verbose_level > 2)
10416                                                         g_print ("cbranch to throw block triggered %d.\n", 
10417                                                                          bb->block_num);
10418                                         }
10419                                 }
10420                         }
10421                 }
10422         } while (changed && (niterations > 0));
10423
10424 }
10425
10426 static void
10427 mono_compile_create_vars (MonoCompile *cfg)
10428 {
10429         MonoMethodSignature *sig;
10430         MonoMethodHeader *header;
10431         int i;
10432
10433         header = mono_method_get_header (cfg->method);
10434
10435         sig = mono_method_signature (cfg->method);
10436         
10437         if (!MONO_TYPE_IS_VOID (sig->ret)) {
10438                 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
10439                 cfg->ret->opcode = OP_RETARG;
10440                 cfg->ret->inst_vtype = sig->ret;
10441                 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
10442         }
10443         if (cfg->verbose_level > 2)
10444                 g_print ("creating vars\n");
10445
10446         cfg->args = mono_mempool_alloc0 (cfg->mempool, (sig->param_count + sig->hasthis) * sizeof (MonoInst*));
10447
10448         if (sig->hasthis)
10449                 cfg->args [0] = mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
10450
10451         for (i = 0; i < sig->param_count; ++i) {
10452                 cfg->args [i + sig->hasthis] = mono_compile_create_var (cfg, sig->params [i], OP_ARG);
10453                 if (sig->params [i]->byref) {
10454                         cfg->disable_ssa = TRUE;
10455                 }
10456         }
10457
10458         cfg->locals_start = cfg->num_varinfo;
10459
10460         if (cfg->verbose_level > 2)
10461                 g_print ("creating locals\n");
10462
10463         for (i = 0; i < header->num_locals; ++i)
10464                 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
10465         if (cfg->verbose_level > 2)
10466                 g_print ("locals done\n");
10467
10468 #ifdef MONO_ARCH_HAVE_CREATE_VARS
10469         mono_arch_create_vars (cfg);
10470 #endif
10471 }
10472
10473 void
10474 mono_print_code (MonoCompile *cfg)
10475 {
10476         MonoBasicBlock *bb;
10477         
10478         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10479                 MonoInst *tree = bb->code;      
10480
10481                 if (!tree)
10482                         continue;
10483                 
10484                 g_print ("CODE BLOCK %d (nesting %d):\n", bb->block_num, bb->nesting);
10485
10486                 for (; tree; tree = tree->next) {
10487                         mono_print_tree (tree);
10488                         g_print ("\n");
10489                 }
10490
10491                 if (bb->last_ins)
10492                         bb->last_ins->next = NULL;
10493         }
10494 }
10495
10496 extern const char * const mono_burg_rule_string [];
10497
10498 static void
10499 emit_state (MonoCompile *cfg, MBState *state, int goal)
10500 {
10501         MBState *kids [10];
10502         int ern = mono_burg_rule (state, goal);
10503         const guint16 *nts = mono_burg_nts_data + mono_burg_nts [ern];
10504
10505         //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
10506         switch (goal) {
10507         case MB_NTERM_reg:
10508                 //if (state->reg2)
10509                 //      state->reg1 = state->reg2; /* chain rule */
10510                 //else
10511 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
10512                 if (!state->reg1)
10513 #endif
10514                         state->reg1 = mono_regstate_next_int (cfg->rs);
10515                 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
10516                 break;
10517         case MB_NTERM_lreg:
10518                 state->reg1 = mono_regstate_next_int (cfg->rs);
10519                 state->reg2 = mono_regstate_next_int (cfg->rs);
10520                 break;
10521         case MB_NTERM_freg:
10522 #ifdef MONO_ARCH_SOFT_FLOAT
10523                 state->reg1 = mono_regstate_next_int (cfg->rs);
10524                 state->reg2 = mono_regstate_next_int (cfg->rs);
10525 #else
10526                 state->reg1 = mono_regstate_next_float (cfg->rs);
10527 #endif
10528                 break;
10529         default:
10530 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
10531                 /*
10532                  * Enabling this might cause bugs to surface in the local register
10533                  * allocators on some architectures like x86.
10534                  */
10535                 if ((state->tree->ssa_op == MONO_SSA_STORE) && (state->left->tree->opcode == OP_REGVAR)) {
10536                         /* Do not optimize away reg-reg moves */
10537                         if (! ((state->right->tree->ssa_op == MONO_SSA_LOAD) && (state->right->left->tree->opcode == OP_REGVAR))) {
10538                                 state->right->reg1 = state->left->tree->dreg;
10539                         }
10540                 }
10541 #endif
10542
10543                 /* do nothing */
10544                 break;
10545         }
10546         if (nts [0]) {
10547                 mono_burg_kids (state, ern, kids);
10548
10549                 emit_state (cfg, kids [0], nts [0]);
10550                 if (nts [1]) {
10551                         emit_state (cfg, kids [1], nts [1]);
10552                         if (nts [2]) {
10553                                 g_assert (!nts [3]);
10554                                 emit_state (cfg, kids [2], nts [2]);
10555                         }
10556                 }
10557         }
10558
10559 //      g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
10560         mono_burg_emit (ern, state, state->tree, cfg);
10561 }
10562
10563 #define DEBUG_SELECTION
10564
10565 static void 
10566 mini_select_instructions (MonoCompile *cfg)
10567 {
10568         MonoBasicBlock *bb;
10569         
10570         cfg->state_pool = mono_mempool_new ();
10571         cfg->rs = mono_regstate_new ();
10572
10573         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10574                 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
10575                     bb->next_bb != bb->last_ins->inst_false_bb) {
10576
10577                         /* we are careful when inverting, since bugs like #59580
10578                          * could show up when dealing with NaNs.
10579                          */
10580                         if (MONO_IS_COND_BRANCH_NOFP(bb->last_ins) && bb->next_bb == bb->last_ins->inst_true_bb) {
10581                                 MonoBasicBlock *tmp =  bb->last_ins->inst_true_bb;
10582                                 bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb;
10583                                 bb->last_ins->inst_false_bb = tmp;
10584
10585                                 bb->last_ins->opcode = reverse_branch_op (bb->last_ins->opcode);
10586                         } else {                        
10587                                 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
10588                                 inst->opcode = OP_BR;
10589                                 inst->inst_target_bb = bb->last_ins->inst_false_bb;
10590                                 mono_bblock_add_inst (bb, inst);
10591                         }
10592                 }
10593         }
10594
10595 #ifdef DEBUG_SELECTION
10596         if (cfg->verbose_level >= 4) {
10597         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10598                 MonoInst *tree = bb->code;      
10599                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
10600                 if (!tree)
10601                         continue;
10602                 for (; tree; tree = tree->next) {
10603                         mono_print_tree (tree);
10604                         g_print ("\n");
10605                 }
10606         }
10607         }
10608 #endif
10609
10610         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10611                 MonoInst *tree = bb->code, *next;       
10612                 MBState *mbstate;
10613
10614                 if (!tree)
10615                         continue;
10616                 bb->code = NULL;
10617                 bb->last_ins = NULL;
10618                 
10619                 cfg->cbb = bb;
10620                 mono_regstate_reset (cfg->rs);
10621
10622 #ifdef DEBUG_SELECTION
10623                 if (cfg->verbose_level >= 3)
10624                         g_print ("LABEL BLOCK %d:\n", bb->block_num);
10625 #endif
10626                 for (; tree; tree = next) {
10627                         next = tree->next;
10628 #ifdef DEBUG_SELECTION
10629                         if (cfg->verbose_level >= 3) {
10630                                 mono_print_tree (tree);
10631                                 g_print ("\n");
10632                         }
10633 #endif
10634
10635                         if (!(mbstate = mono_burg_label (tree, cfg))) {
10636                                 g_warning ("unable to label tree %p", tree);
10637                                 mono_print_tree (tree);
10638                                 g_print ("\n");                         
10639                                 g_assert_not_reached ();
10640                         }
10641                         emit_state (cfg, mbstate, MB_NTERM_stmt);
10642                 }
10643                 bb->max_vreg = cfg->rs->next_vreg;
10644
10645                 if (bb->last_ins)
10646                         bb->last_ins->next = NULL;
10647
10648                 mono_mempool_empty (cfg->state_pool); 
10649         }
10650         mono_mempool_destroy (cfg->state_pool); 
10651 }
10652
10653 void
10654 mono_codegen (MonoCompile *cfg)
10655 {
10656         MonoJumpInfo *patch_info;
10657         MonoBasicBlock *bb;
10658         int i, max_epilog_size;
10659         guint8 *code;
10660
10661         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10662                 cfg->spill_count = 0;
10663                 /* we reuse dfn here */
10664                 /* bb->dfn = bb_count++; */
10665                 mono_arch_local_regalloc (cfg, bb);
10666         }
10667
10668         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
10669                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
10670
10671         code = mono_arch_emit_prolog (cfg);
10672
10673         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
10674                 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
10675
10676         cfg->code_len = code - cfg->native_code;
10677         cfg->prolog_end = cfg->code_len;
10678
10679         mono_debug_open_method (cfg);
10680
10681         /* emit code all basic blocks */
10682         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10683                 bb->native_offset = cfg->code_len;
10684                 mono_arch_output_basic_block (cfg, bb);
10685
10686                 if (bb == cfg->bb_exit) {
10687                         cfg->epilog_begin = cfg->code_len;
10688
10689                         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
10690                                 code = cfg->native_code + cfg->code_len;
10691                                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
10692                                 cfg->code_len = code - cfg->native_code;
10693                                 g_assert (cfg->code_len < cfg->code_size);
10694                         }
10695
10696                         mono_arch_emit_epilog (cfg);
10697                 }
10698         }
10699
10700         mono_arch_emit_exceptions (cfg);
10701
10702         max_epilog_size = 0;
10703
10704         code = cfg->native_code + cfg->code_len;
10705
10706         /* we always allocate code in cfg->domain->code_mp to increase locality */
10707         cfg->code_size = cfg->code_len + max_epilog_size;
10708         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
10709
10710         if (cfg->method->dynamic) {
10711                 /* Allocate the code into a separate memory pool so it can be freed */
10712                 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
10713                 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
10714                 mono_domain_lock (cfg->domain);
10715                 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
10716                 mono_domain_unlock (cfg->domain);
10717
10718                 code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size);
10719         } else {
10720                 mono_domain_lock (cfg->domain);
10721                 code = mono_code_manager_reserve (cfg->domain->code_mp, cfg->code_size);
10722                 mono_domain_unlock (cfg->domain);
10723         }
10724
10725         memcpy (code, cfg->native_code, cfg->code_len);
10726         g_free (cfg->native_code);
10727         cfg->native_code = code;
10728         code = cfg->native_code + cfg->code_len;
10729   
10730         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
10731         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
10732                 switch (patch_info->type) {
10733                 case MONO_PATCH_INFO_ABS: {
10734                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
10735                         if (info) {
10736                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
10737                                 if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && 
10738                                         strstr (cfg->method->name, info->name))
10739                                         /*
10740                                          * This is an icall wrapper, and this is a call to the
10741                                          * wrapped function.
10742                                          */
10743                                         ;
10744                                 else {
10745                                         /* for these array methods we currently register the same function pointer
10746                                          * since it's a vararg function. But this means that mono_find_jit_icall_by_addr ()
10747                                          * will return the incorrect one depending on the order they are registered.
10748                                          * See tests/test-arr.cs
10749                                          */
10750                                         if (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL) {
10751                                                 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
10752                                                 patch_info->data.name = info->name;
10753                                         }
10754                                 }
10755                         }
10756                         else {
10757                                 MonoVTable *vtable = mono_find_class_init_trampoline_by_addr (patch_info->data.target);
10758                                 if (vtable) {
10759                                         patch_info->type = MONO_PATCH_INFO_CLASS_INIT;
10760                                         patch_info->data.klass = vtable->klass;
10761                                 }
10762                         }
10763                         break;
10764                 }
10765                 case MONO_PATCH_INFO_SWITCH: {
10766                         gpointer *table;
10767                         if (cfg->method->dynamic) {
10768                                 table = mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
10769                         } else {
10770                                 mono_domain_lock (cfg->domain);
10771                                 table = mono_code_manager_reserve (cfg->domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
10772                                 mono_domain_unlock (cfg->domain);
10773                         }
10774
10775                         if (!cfg->compile_aot)
10776                                 /* In the aot case, the patch already points to the correct location */
10777                                 patch_info->ip.i = patch_info->ip.label->inst_c0;
10778                         for (i = 0; i < patch_info->data.table->table_size; i++) {
10779                                 table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
10780                         }
10781                         patch_info->data.table->table = (MonoBasicBlock**)table;
10782                         break;
10783                 }
10784                 default:
10785                         /* do nothing */
10786                         break;
10787                 }
10788         }
10789
10790 #ifdef VALGRIND_JIT_REGISTER_MAP
10791 if (valgrind_register){
10792                 char* nm = mono_method_full_name (cfg->method, TRUE);
10793                 VALGRIND_JIT_REGISTER_MAP (nm, cfg->native_code, cfg->native_code + cfg->code_len);
10794                 g_free (nm);
10795         }
10796 #endif
10797  
10798         if (cfg->verbose_level > 0) {
10799                 char* nm = mono_method_full_name (cfg->method, TRUE);
10800                 g_print ("Method %s emitted at %p to %p (code length %d) [%s]\n", 
10801                                  nm, 
10802                                  cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
10803                 g_free (nm);
10804         }
10805
10806 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
10807         mono_arch_save_unwind_info (cfg);
10808 #endif
10809         
10810         mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
10811
10812         if (cfg->method->dynamic) {
10813                 mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
10814         } else {
10815                 mono_domain_lock (cfg->domain);
10816                 mono_code_manager_commit (cfg->domain->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
10817                 mono_domain_unlock (cfg->domain);
10818         }
10819         
10820         mono_arch_flush_icache (cfg->native_code, cfg->code_len);
10821
10822         mono_debug_close_method (cfg);
10823 }
10824
10825
10826
10827 static void
10828 remove_critical_edges (MonoCompile *cfg) {
10829         MonoBasicBlock *bb;
10830         MonoBasicBlock *previous_bb;
10831         
10832         if (cfg->verbose_level > 3) {
10833                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10834                         int i;
10835                         printf ("remove_critical_edges %s, BEFORE BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
10836                         for (i = 0; i < bb->in_count; i++) {
10837                                 printf (" %d", bb->in_bb [i]->block_num);
10838                         }
10839                         printf (") (out:");
10840                         for (i = 0; i < bb->out_count; i++) {
10841                                 printf (" %d", bb->out_bb [i]->block_num);
10842                         }
10843                         printf (")");
10844                         if (bb->last_ins != NULL) {
10845                                 printf (" ");
10846                                 mono_print_tree (bb->last_ins);
10847                         }
10848                         printf ("\n");
10849                 }
10850         }
10851         
10852         for (previous_bb = cfg->bb_entry, bb = previous_bb->next_bb; bb != NULL; previous_bb = previous_bb->next_bb, bb = bb->next_bb) {
10853                 if (bb->in_count > 1) {
10854                         int in_bb_index;
10855                         for (in_bb_index = 0; in_bb_index < bb->in_count; in_bb_index++) {
10856                                 MonoBasicBlock *in_bb = bb->in_bb [in_bb_index];
10857                                 if (in_bb->out_count > 1) {
10858                                         MonoBasicBlock *new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
10859                                         new_bb->block_num = cfg->num_bblocks++;
10860 //                                      new_bb->real_offset = bb->real_offset;
10861                                         new_bb->region = bb->region;
10862                                         
10863                                         /* Do not alter the CFG while altering the BB list */
10864                                         if (previous_bb->region == bb->region) {
10865                                                 if (previous_bb != cfg->bb_entry) {
10866                                                         /* If previous_bb "followed through" to bb, */
10867                                                         /* keep it linked with a OP_BR */
10868                                                         if ((previous_bb->last_ins == NULL) ||
10869                                                                         ((previous_bb->last_ins->opcode != OP_BR) &&
10870                                                                         (! (MONO_IS_COND_BRANCH_OP (previous_bb->last_ins))) &&
10871                                                                         (previous_bb->last_ins->opcode != CEE_SWITCH))) {
10872                                                                 int i;
10873                                                                 /* Make sure previous_bb really falls through bb */
10874                                                                 for (i = 0; i < previous_bb->out_count; i++) {
10875                                                                         if (previous_bb->out_bb [i] == bb) {
10876                                                                                 MonoInst *jump;
10877                                                                                 MONO_INST_NEW (cfg, jump, OP_BR);
10878                                                                                 MONO_ADD_INS (previous_bb, jump);
10879                                                                                 jump->cil_code = previous_bb->cil_code;
10880                                                                                 jump->inst_target_bb = bb;
10881                                                                                 break;
10882                                                                         }
10883                                                                 }
10884                                                         }
10885                                                 } else {
10886                                                         /* We cannot add any inst to the entry BB, so we must */
10887                                                         /* put a new BB in the middle to hold the OP_BR */
10888                                                         MonoInst *jump;
10889                                                         MonoBasicBlock *new_bb_after_entry = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
10890                                                         new_bb_after_entry->block_num = cfg->num_bblocks++;
10891 //                                                      new_bb_after_entry->real_offset = bb->real_offset;
10892                                                         new_bb_after_entry->region = bb->region;
10893                                                         
10894                                                         MONO_INST_NEW (cfg, jump, OP_BR);
10895                                                         MONO_ADD_INS (new_bb_after_entry, jump);
10896                                                         jump->cil_code = bb->cil_code;
10897                                                         jump->inst_target_bb = bb;
10898                                                         
10899                                                         previous_bb->next_bb = new_bb_after_entry;
10900                                                         previous_bb = new_bb_after_entry;
10901                                                         
10902                                                         if (cfg->verbose_level > 2) {
10903                                                                 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);
10904                                                         }
10905                                                 }
10906                                         }
10907                                         
10908                                         /* Insert new_bb in the BB list */
10909                                         previous_bb->next_bb = new_bb;
10910                                         new_bb->next_bb = bb;
10911                                         previous_bb = new_bb;
10912                                         
10913                                         /* Setup in_bb and out_bb */
10914                                         new_bb->in_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
10915                                         new_bb->in_bb [0] = in_bb;
10916                                         new_bb->in_count = 1;
10917                                         new_bb->out_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
10918                                         new_bb->out_bb [0] = bb;
10919                                         new_bb->out_count = 1;
10920                                         
10921                                         /* Relink in_bb and bb to (from) new_bb */
10922                                         replace_out_block (in_bb, bb, new_bb);
10923                                         replace_out_block_in_code (in_bb, bb, new_bb);
10924                                         replace_in_block (bb, in_bb, new_bb);
10925                                         
10926                                         if (cfg->verbose_level > 2) {
10927                                                 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);
10928                                         }
10929                                 }
10930                         }
10931                 }
10932         }
10933         
10934         if (cfg->verbose_level > 3) {
10935                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10936                         int i;
10937                         printf ("remove_critical_edges %s, AFTER BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
10938                         for (i = 0; i < bb->in_count; i++) {
10939                                 printf (" %d", bb->in_bb [i]->block_num);
10940                         }
10941                         printf (") (out:");
10942                         for (i = 0; i < bb->out_count; i++) {
10943                                 printf (" %d", bb->out_bb [i]->block_num);
10944                         }
10945                         printf (")");
10946                         if (bb->last_ins != NULL) {
10947                                 printf (" ");
10948                                 mono_print_tree (bb->last_ins);
10949                         }
10950                         printf ("\n");
10951                 }
10952         }
10953 }
10954
10955 /*
10956  * mini_method_compile:
10957  * @method: the method to compile
10958  * @opts: the optimization flags to use
10959  * @domain: the domain where the method will be compiled in
10960  * @run_cctors: whether we should run type ctors if possible
10961  * @compile_aot: whether this is an AOT compilation
10962  * @parts: debug flag
10963  *
10964  * Returns: a MonoCompile* pointer. Caller must check the exception_type
10965  * field in the returned struct to see if compilation succeded.
10966  */
10967 MonoCompile*
10968 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
10969 {
10970         MonoMethodHeader *header = mono_method_get_header (method);
10971         guint8 *ip;
10972         MonoCompile *cfg;
10973         MonoJitInfo *jinfo;
10974         int dfn = 0, i, code_size_ratio;
10975         gboolean deadce_has_run = FALSE;
10976         gboolean try_generic_shared;
10977         MonoMethod *method_to_compile;
10978         int gsctx_size;
10979
10980         mono_jit_stats.methods_compiled++;
10981         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
10982                 mono_profiler_method_jit (method);
10983  
10984         if (compile_aot)
10985                 /* We are passed the original generic method definition */
10986                 try_generic_shared = (opts & MONO_OPT_GSHARED) && (method->generic_container || method->klass->generic_container);
10987         else
10988                 try_generic_shared = (opts & MONO_OPT_GSHARED) && mono_method_is_generic_sharable_impl (method);
10989
10990         if (opts & MONO_OPT_GSHARED) {
10991                 if (try_generic_shared)
10992                         mono_stats.generics_sharable_methods++;
10993                 else if (mono_method_is_generic_impl (method))
10994                         mono_stats.generics_unsharable_methods++;
10995         }
10996
10997  restart_compile:
10998         if (try_generic_shared) {
10999                 MonoMethod *declaring_method;
11000                 MonoGenericContext *shared_context;
11001
11002                 if (compile_aot) {
11003                         declaring_method = method;
11004                 } else {
11005                         declaring_method = mono_method_get_declaring_generic_method (method);
11006                         g_assert (method->klass->generic_class->container_class == declaring_method->klass);
11007                 }
11008
11009                 if (declaring_method->generic_container)
11010                         shared_context = &declaring_method->generic_container->context;
11011                 else
11012                         shared_context = &declaring_method->klass->generic_container->context;
11013
11014                 method_to_compile = mono_class_inflate_generic_method (declaring_method, shared_context);
11015                 g_assert (method_to_compile);
11016         } else {
11017                 method_to_compile = method;
11018         }
11019
11020         cfg = g_new0 (MonoCompile, 1);
11021         cfg->method = method_to_compile;
11022         cfg->mempool = mono_mempool_new ();
11023         cfg->opt = opts;
11024         cfg->prof_options = mono_profiler_get_events ();
11025         cfg->run_cctors = run_cctors;
11026         cfg->domain = domain;
11027         cfg->verbose_level = mini_verbose;
11028         cfg->compile_aot = compile_aot;
11029         cfg->skip_visibility = method->skip_visibility;
11030         if (try_generic_shared)
11031                 cfg->generic_sharing_context = (MonoGenericSharingContext*)&cfg->generic_sharing_context;
11032         cfg->token_info_hash = g_hash_table_new (NULL, NULL);
11033         if (!header) {
11034                 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
11035                 cfg->exception_message = g_strdup_printf ("Missing or incorrect header for method %s", cfg->method->name);
11036                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
11037                         mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
11038                 return cfg;
11039         }
11040
11041         ip = (guint8 *)header->code;
11042
11043         cfg->intvars = mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * header->max_stack);
11044         cfg->aliasing_info = NULL;
11045         
11046         if (cfg->verbose_level > 2)
11047                 g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
11048
11049         /*
11050          * create MonoInst* which represents arguments and local variables
11051          */
11052         mono_compile_create_vars (cfg);
11053
11054         if ((i = mono_method_to_ir (cfg, method_to_compile, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
11055                 if (try_generic_shared && cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
11056                         if (compile_aot)
11057                                 return cfg;
11058                         mono_destroy_compile (cfg);
11059                         try_generic_shared = FALSE;
11060                         goto restart_compile;
11061                 }
11062                 g_assert (cfg->exception_type != MONO_EXCEPTION_GENERIC_SHARING_FAILED);
11063
11064                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
11065                         mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
11066                 /* cfg contains the details of the failure, so let the caller cleanup */
11067                 return cfg;
11068         }
11069
11070         mono_jit_stats.basic_blocks += cfg->num_bblocks;
11071         mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
11072
11073         if ((cfg->num_varinfo > 2000) && !cfg->compile_aot) {
11074                 /* 
11075                  * we disable some optimizations if there are too many variables
11076                  * because JIT time may become too expensive. The actual number needs 
11077                  * to be tweaked and eventually the non-linear algorithms should be fixed.
11078                  */
11079                 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
11080                 cfg->disable_ssa = TRUE;
11081         }
11082
11083         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
11084
11085         if (cfg->opt & MONO_OPT_BRANCH)
11086                 optimize_branches (cfg);
11087
11088         if (cfg->opt & MONO_OPT_SSAPRE) {
11089                 remove_critical_edges (cfg);
11090         }
11091
11092         /* Depth-first ordering on basic blocks */
11093         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
11094
11095         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
11096         if (cfg->num_bblocks != dfn + 1) {
11097                 MonoBasicBlock *bb;
11098
11099                 cfg->num_bblocks = dfn + 1;
11100
11101                 if (!header->clauses) {
11102                         /* remove unreachable code, because the code in them may be 
11103                          * inconsistent  (access to dead variables for example) */
11104                         for (bb = cfg->bb_entry; bb;) {
11105                                 MonoBasicBlock *bbn = bb->next_bb;
11106
11107                                 if (bbn && bbn->region == -1 && !bbn->dfn) {
11108                                         if (cfg->verbose_level > 1)
11109                                                 g_print ("found unreachable code in BB%d\n", bbn->block_num);
11110                                         bb->next_bb = bbn->next_bb;
11111                                         nullify_basic_block (bbn);                      
11112                                 } else {
11113                                         bb = bb->next_bb;
11114                                 }
11115                         }
11116                 }
11117         }
11118
11119         if (cfg->opt & MONO_OPT_LOOP) {
11120                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
11121                 mono_compute_natural_loops (cfg);
11122         }
11123
11124         /* after method_to_ir */
11125         if (parts == 1)
11126                 return cfg;
11127
11128 //#define DEBUGSSA "logic_run"
11129 #define DEBUGSSA_CLASS "Tests"
11130 #ifdef DEBUGSSA
11131
11132         if (!header->num_clauses && !cfg->disable_ssa) {
11133                 mono_local_cprop (cfg);
11134 #ifndef DISABLE_SSA
11135                 mono_ssa_compute (cfg);
11136 #endif
11137         }
11138 #else 
11139
11140         /* fixme: add all optimizations which requires SSA */
11141         if (cfg->opt & (MONO_OPT_SSA | MONO_OPT_ABCREM | MONO_OPT_SSAPRE)) {
11142                 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
11143                         mono_local_cprop (cfg);
11144 #ifndef DISABLE_SSA
11145                         mono_ssa_compute (cfg);
11146 #endif
11147
11148                         if (cfg->verbose_level >= 2) {
11149                                 print_dfn (cfg);
11150                         }
11151                 }
11152         }
11153 #endif
11154
11155         /* after SSA translation */
11156         if (parts == 2)
11157                 return cfg;
11158
11159         if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
11160                 if (cfg->comp_done & MONO_COMP_SSA) {
11161 #ifndef DISABLE_SSA
11162                         mono_ssa_cprop (cfg);
11163 #endif
11164                 } else {
11165                         mono_local_cprop (cfg);
11166                 }
11167         }
11168
11169 #ifndef DISABLE_SSA
11170         if (cfg->comp_done & MONO_COMP_SSA) {                   
11171                 //mono_ssa_deadce (cfg);
11172
11173                 //mono_ssa_strength_reduction (cfg);
11174
11175                 if (cfg->opt & MONO_OPT_SSAPRE) {
11176                         mono_perform_ssapre (cfg);
11177                         //mono_local_cprop (cfg);
11178                 }
11179                 
11180                 if (cfg->opt & MONO_OPT_DEADCE) {
11181                         mono_ssa_deadce (cfg);
11182                         deadce_has_run = TRUE;
11183                 }
11184                 
11185                 if ((cfg->flags & MONO_CFG_HAS_LDELEMA) && (cfg->opt & MONO_OPT_ABCREM))
11186                         mono_perform_abc_removal (cfg);
11187                 
11188                 mono_ssa_remove (cfg);
11189
11190                 if (cfg->opt & MONO_OPT_BRANCH)
11191                         optimize_branches (cfg);
11192         }
11193 #endif
11194
11195         /* after SSA removal */
11196         if (parts == 3)
11197                 return cfg;
11198
11199         if (cfg->verbose_level > 4) {
11200                 printf ("BEFORE DECOMPSE START\n");
11201                 mono_print_code (cfg);
11202                 printf ("BEFORE DECOMPSE END\n");
11203         }
11204         
11205         decompose_pass (cfg);
11206
11207         if (cfg->got_var) {
11208                 GList *regs;
11209
11210                 g_assert (cfg->got_var_allocated);
11211
11212                 /* 
11213                  * Allways allocate the GOT var to a register, because keeping it
11214                  * in memory will increase the number of live temporaries in some
11215                  * code created by inssel.brg, leading to the well known spills+
11216                  * branches problem. Testcase: mcs crash in 
11217                  * System.MonoCustomAttrs:GetCustomAttributes.
11218                  */
11219                 regs = mono_arch_get_global_int_regs (cfg);
11220                 g_assert (regs);
11221                 cfg->got_var->opcode = OP_REGVAR;
11222                 cfg->got_var->dreg = GPOINTER_TO_INT (regs->data);
11223                 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
11224                 
11225                 g_list_free (regs);
11226         }
11227
11228         /* todo: remove code when we have verified that the liveness for try/catch blocks
11229          * works perfectly 
11230          */
11231         /* 
11232          * Currently, this can't be commented out since exception blocks are not
11233          * processed during liveness analysis.
11234          */
11235         mono_liveness_handle_exception_clauses (cfg);
11236
11237         if (cfg->opt & MONO_OPT_LINEARS) {
11238                 GList *vars, *regs;
11239                 
11240                 /* For now, compute aliasing info only if needed for deadce... */
11241                 if ((cfg->opt & MONO_OPT_DEADCE) && (! deadce_has_run) && (header->num_clauses == 0)) {
11242                         cfg->aliasing_info = mono_build_aliasing_information (cfg);
11243                 }
11244
11245                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
11246                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
11247                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
11248                         mono_analyze_liveness (cfg);
11249
11250                 if (cfg->aliasing_info != NULL) {
11251                         mono_aliasing_deadce (cfg->aliasing_info);
11252                         deadce_has_run = TRUE;
11253                 }
11254                 
11255                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
11256                         regs = mono_arch_get_global_int_regs (cfg);
11257                         if (cfg->got_var)
11258                                 regs = g_list_delete_link (regs, regs);
11259                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
11260                 }
11261                 
11262                 if (cfg->aliasing_info != NULL) {
11263                         mono_destroy_aliasing_information (cfg->aliasing_info);
11264                         cfg->aliasing_info = NULL;
11265                 }
11266         }
11267
11268         //mono_print_code (cfg);
11269
11270     //print_dfn (cfg);
11271         
11272         /* variables are allocated after decompose, since decompose could create temps */
11273         mono_arch_allocate_vars (cfg);
11274
11275         if (cfg->opt & MONO_OPT_CFOLD)
11276                 mono_constant_fold (cfg);
11277
11278         mini_select_instructions (cfg);
11279
11280         mono_codegen (cfg);
11281         if (cfg->verbose_level >= 2) {
11282                 char *id =  mono_method_full_name (cfg->method, FALSE);
11283                 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
11284                 g_free (id);
11285         }
11286
11287         if (cfg->generic_sharing_context)
11288                 gsctx_size = sizeof (MonoGenericSharingContext*);
11289         else
11290                 gsctx_size = 0;
11291
11292         if (cfg->method->dynamic) {
11293                 jinfo = g_malloc0 (sizeof (MonoJitInfo) + (header->num_clauses * sizeof (MonoJitExceptionInfo)) +
11294                                 gsctx_size);
11295         } else {
11296                 /* we access cfg->domain->mp */
11297                 mono_domain_lock (cfg->domain);
11298                 jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo) +
11299                                 (header->num_clauses * sizeof (MonoJitExceptionInfo)) +
11300                                 gsctx_size);
11301                 mono_domain_unlock (cfg->domain);
11302         }
11303
11304         jinfo->method = method;
11305         jinfo->code_start = cfg->native_code;
11306         jinfo->code_size = cfg->code_len;
11307         jinfo->used_regs = cfg->used_int_regs;
11308         jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
11309         jinfo->cas_inited = FALSE; /* initialization delayed at the first stalk walk using this method */
11310         jinfo->num_clauses = header->num_clauses;
11311
11312         if (cfg->generic_sharing_context) {
11313                 jinfo->has_generic_sharing_context = 1;
11314                 mono_jit_info_set_generic_sharing_context (jinfo, cfg->generic_sharing_context);
11315         }
11316
11317         if (header->num_clauses) {
11318                 int i;
11319
11320                 for (i = 0; i < header->num_clauses; i++) {
11321                         MonoExceptionClause *ec = &header->clauses [i];
11322                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
11323                         MonoBasicBlock *tblock;
11324                         MonoInst *exvar;
11325
11326                         ei->flags = ec->flags;
11327
11328                         exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
11329                         ei->exvar_offset = exvar ? exvar->inst_offset : 0;
11330
11331                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
11332                                 tblock = cfg->cil_offset_to_bb [ec->data.filter_offset];
11333                                 g_assert (tblock);
11334                                 ei->data.filter = cfg->native_code + tblock->native_offset;
11335                         } else {
11336                                 ei->data.catch_class = ec->data.catch_class;
11337                         }
11338
11339                         tblock = cfg->cil_offset_to_bb [ec->try_offset];
11340                         g_assert (tblock);
11341                         ei->try_start = cfg->native_code + tblock->native_offset;
11342                         g_assert (tblock->native_offset);
11343                         tblock = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
11344                         g_assert (tblock);
11345                         ei->try_end = cfg->native_code + tblock->native_offset;
11346                         g_assert (tblock->native_offset);
11347                         tblock = cfg->cil_offset_to_bb [ec->handler_offset];
11348                         g_assert (tblock);
11349                         ei->handler_start = cfg->native_code + tblock->native_offset;
11350                 }
11351         }
11352
11353         cfg->jit_info = jinfo;
11354 #if defined(__arm__)
11355         mono_arch_fixup_jinfo (cfg);
11356 #endif
11357
11358         mono_domain_lock (cfg->domain);
11359         mono_jit_info_table_add (cfg->domain, jinfo);
11360
11361         if (cfg->method->dynamic)
11362                 mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = jinfo;
11363         mono_domain_unlock (cfg->domain);
11364
11365         /* collect statistics */
11366         mono_jit_stats.allocated_code_size += cfg->code_len;
11367         code_size_ratio = cfg->code_len;
11368         if (code_size_ratio > mono_jit_stats.biggest_method_size) {
11369                         mono_jit_stats.biggest_method_size = code_size_ratio;
11370                         mono_jit_stats.biggest_method = method;
11371         }
11372         code_size_ratio = (code_size_ratio * 100) / mono_method_get_header (method)->code_size;
11373         if (code_size_ratio > mono_jit_stats.max_code_size_ratio) {
11374                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
11375                 mono_jit_stats.max_ratio_method = method;
11376         }
11377         mono_jit_stats.native_code_size += cfg->code_len;
11378
11379         if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
11380                 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
11381
11382         return cfg;
11383 }
11384
11385 static MonoJitInfo*
11386 lookup_generic_method (MonoDomain *domain, MonoMethod *method)
11387 {
11388         MonoMethod *open_method;
11389
11390         if (!mono_method_is_generic_sharable_impl (method))
11391                 return NULL;
11392
11393         open_method = mono_method_get_declaring_generic_method (method);
11394
11395         return mono_domain_lookup_shared_generic (domain, open_method);
11396 }
11397
11398 static MonoJitInfo*
11399 lookup_method (MonoDomain *domain, MonoMethod *method)
11400 {
11401         MonoJitInfo *ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, method);
11402
11403         if (ji != NULL)
11404                 return ji;
11405
11406         return lookup_generic_method (domain, method);
11407 }
11408
11409 static gpointer
11410 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt)
11411 {
11412         MonoCompile *cfg;
11413         gpointer code = NULL;
11414         MonoJitInfo *info;
11415
11416 #ifdef MONO_USE_AOT_COMPILER
11417         if ((opt & MONO_OPT_AOT) && !(mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)) {
11418                 MonoDomain *domain = mono_domain_get ();
11419
11420                 mono_class_init (method->klass);
11421
11422                 mono_domain_lock (domain);
11423                 if ((code = mono_aot_get_method (domain, method))) {
11424                         mono_domain_unlock (domain);
11425                         mono_runtime_class_init (mono_class_vtable (domain, method->klass));
11426                         return code;
11427                 }
11428
11429                 mono_domain_unlock (domain);
11430         }
11431 #endif
11432
11433         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
11434             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
11435                 MonoMethod *nm;
11436                 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
11437
11438                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE && !MONO_CLASS_IS_IMPORT(method->klass))
11439                         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);
11440
11441                 if (!piinfo->addr) {
11442                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
11443                                 piinfo->addr = mono_lookup_internal_call (method);
11444                         else
11445                                 if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
11446                                         mono_lookup_pinvoke_call (method, NULL, NULL);
11447                 }
11448                         nm = mono_marshal_get_native_wrapper (method);
11449                         return mono_get_addr_from_ftnptr (mono_compile_method (nm));
11450
11451                         //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE) 
11452                         //mono_debug_add_wrapper (method, nm);
11453         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
11454                 const char *name = method->name;
11455                 MonoMethod *nm;
11456
11457                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
11458                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
11459                                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name ("mono_delegate_ctor");
11460                                 g_assert (mi);
11461                                 return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper (mi));
11462                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
11463                                 nm = mono_marshal_get_delegate_invoke (method, NULL);
11464                                         return mono_get_addr_from_ftnptr (mono_compile_method (nm));
11465                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
11466                                 nm = mono_marshal_get_delegate_begin_invoke (method);
11467                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
11468                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
11469                                 nm = mono_marshal_get_delegate_end_invoke (method);
11470                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
11471                         }
11472                 }
11473                 return NULL;
11474         }
11475
11476         cfg = mini_method_compile (method, opt, target_domain, TRUE, FALSE, 0);
11477
11478         switch (cfg->exception_type) {
11479         case MONO_EXCEPTION_NONE: break;
11480         case MONO_EXCEPTION_TYPE_LOAD:
11481         case MONO_EXCEPTION_MISSING_FIELD:
11482         case MONO_EXCEPTION_MISSING_METHOD:
11483         case MONO_EXCEPTION_FILE_NOT_FOUND: {
11484                 /* Throw a type load exception if needed */
11485                 MonoLoaderError *error = mono_loader_get_last_error ();
11486                 MonoException *ex;
11487
11488                 if (error) {
11489                         ex = mono_loader_error_prepare_exception (error);
11490                 } else {
11491                         if (cfg->exception_ptr) {
11492                                 ex = mono_class_get_exception_for_failure (cfg->exception_ptr);
11493                         } else {
11494                                 if (cfg->exception_type == MONO_EXCEPTION_MISSING_FIELD)
11495                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingFieldException", cfg->exception_message);
11496                                 else if (cfg->exception_type == MONO_EXCEPTION_MISSING_METHOD)
11497                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingMethodException", cfg->exception_message);
11498                                 else if (cfg->exception_type == MONO_EXCEPTION_TYPE_LOAD)
11499                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "TypeLoadException", cfg->exception_message);
11500                                 else if (cfg->exception_type == MONO_EXCEPTION_FILE_NOT_FOUND)
11501                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FileNotFoundException", cfg->exception_message);
11502                                 else
11503                                         g_assert_not_reached ();
11504                         }
11505                 }
11506                 mono_destroy_compile (cfg);
11507                 mono_raise_exception (ex);
11508                 break;
11509         }
11510         case MONO_EXCEPTION_INVALID_PROGRAM: {
11511                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", cfg->exception_message);
11512                 mono_destroy_compile (cfg);
11513                 mono_raise_exception (ex);
11514                 break;
11515         }
11516         case MONO_EXCEPTION_UNVERIFIABLE_IL: {
11517                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.Security", "VerificationException", cfg->exception_message);
11518                 mono_destroy_compile (cfg);
11519                 mono_raise_exception (ex);
11520                 break;
11521         }
11522         case MONO_EXCEPTION_METHOD_ACCESS: {
11523                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MethodAccessException", cfg->exception_message);
11524                 mono_destroy_compile (cfg);
11525                 mono_raise_exception (ex);
11526                 break;
11527         }
11528         case MONO_EXCEPTION_FIELD_ACCESS: {
11529                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FieldAccessException", cfg->exception_message);
11530                 mono_destroy_compile (cfg);
11531                 mono_raise_exception (ex);
11532                 break;
11533         }
11534         /* this can only be set if the security manager is active */
11535         case MONO_EXCEPTION_SECURITY_LINKDEMAND: {
11536                 MonoSecurityManager* secman = mono_security_manager_get_methods ();
11537                 MonoObject *exc = NULL;
11538                 gpointer args [2];
11539
11540                 args [0] = &cfg->exception_data;
11541                 args [1] = &method;
11542                 mono_runtime_invoke (secman->linkdemandsecurityexception, NULL, args, &exc);
11543
11544                 mono_destroy_compile (cfg);
11545                 cfg = NULL;
11546
11547                 mono_raise_exception ((MonoException*)exc);
11548         }
11549         default:
11550                 g_assert_not_reached ();
11551         }
11552
11553         mono_domain_lock (target_domain);
11554
11555         /* Check if some other thread already did the job. In this case, we can
11556        discard the code this thread generated. */
11557
11558         if ((info = lookup_method (target_domain, method))) {
11559                 /* We can't use a domain specific method in another domain */
11560                 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
11561                         code = info->code_start;
11562 //                      printf("Discarding code for method %s\n", method->name);
11563                 }
11564         }
11565         
11566         if (code == NULL) {
11567                 mono_internal_hash_table_insert (&target_domain->jit_code_hash, method, cfg->jit_info);
11568                 code = cfg->native_code;
11569
11570                 if (cfg->generic_sharing_context && mono_method_is_generic_sharable_impl (method)) {
11571                         /* g_print ("inserting method %s.%s.%s\n", method->klass->name_space, method->klass->name, method->name); */
11572                         mono_domain_register_shared_generic (target_domain, 
11573                                 mono_method_get_declaring_generic_method (method), cfg->jit_info);
11574                         mono_stats.generics_shared_methods++;
11575                 }
11576         }
11577
11578         mono_destroy_compile (cfg);
11579
11580         if (target_domain->jump_target_hash) {
11581                 MonoJumpInfo patch_info;
11582                 GSList *list, *tmp;
11583                 list = g_hash_table_lookup (target_domain->jump_target_hash, method);
11584                 if (list) {
11585                         patch_info.next = NULL;
11586                         patch_info.ip.i = 0;
11587                         patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
11588                         patch_info.data.method = method;
11589                         g_hash_table_remove (target_domain->jump_target_hash, method);
11590                 }
11591                 for (tmp = list; tmp; tmp = tmp->next)
11592                         mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info, TRUE);
11593                 g_slist_free (list);
11594         }
11595
11596         mono_domain_unlock (target_domain);
11597
11598         mono_runtime_class_init (mono_class_vtable (target_domain, method->klass));
11599         return code;
11600 }
11601
11602 static gpointer
11603 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt)
11604 {
11605         MonoDomain *target_domain, *domain = mono_domain_get ();
11606         MonoJitInfo *info;
11607         gpointer p;
11608         MonoJitICallInfo *callinfo = NULL;
11609
11610         /*
11611          * ICALL wrappers are handled specially, since there is only one copy of them
11612          * shared by all appdomains.
11613          */
11614         if ((method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (strstr (method->name, "__icall_wrapper_") == method->name)) {
11615                 const char *icall_name;
11616
11617                 icall_name = method->name + strlen ("__icall_wrapper_");
11618                 g_assert (icall_name);
11619                 callinfo = mono_find_jit_icall_by_name (icall_name);
11620                 g_assert (callinfo);
11621
11622                 /* Must be domain neutral since there is only one copy */
11623                 opt |= MONO_OPT_SHARED;
11624         }
11625
11626         if (opt & MONO_OPT_SHARED)
11627                 target_domain = mono_get_root_domain ();
11628         else 
11629                 target_domain = domain;
11630
11631         mono_domain_lock (target_domain);
11632
11633         if ((info = lookup_method (target_domain, method))) {
11634                 /* We can't use a domain specific method in another domain */
11635                 if (! ((domain != target_domain) && !info->domain_neutral)) {
11636                         mono_domain_unlock (target_domain);
11637                         mono_jit_stats.methods_lookups++;
11638                         mono_runtime_class_init (mono_class_vtable (domain, method->klass));
11639                         return mono_create_ftnptr (target_domain, info->code_start);
11640                 }
11641         }
11642
11643         mono_domain_unlock (target_domain);
11644         p = mono_create_ftnptr (target_domain, mono_jit_compile_method_inner (method, target_domain, opt));
11645
11646         if (callinfo) {
11647                 mono_jit_lock ();
11648                 if (!callinfo->wrapper) {
11649                         callinfo->wrapper = p;
11650                         mono_register_jit_icall_wrapper (callinfo, p);
11651                         mono_debug_add_icall_wrapper (method, callinfo);
11652                 }
11653                 mono_jit_unlock ();
11654         }
11655
11656         return p;
11657 }
11658
11659 static gpointer
11660 mono_jit_compile_method (MonoMethod *method)
11661 {
11662         return mono_jit_compile_method_with_opt (method, default_opt);
11663 }
11664
11665 static void
11666 invalidated_delegate_trampoline (char *desc)
11667 {
11668         g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
11669                  "See http://www.go-mono.com/delegate.html for an explanation and ways to fix this.",
11670                  desc);
11671 }
11672
11673 /*
11674  * mono_jit_free_method:
11675  *
11676  *  Free all memory allocated by the JIT for METHOD.
11677  */
11678 static void
11679 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
11680 {
11681         MonoJitDynamicMethodInfo *ji;
11682         gboolean destroy = TRUE;
11683
11684         g_assert (method->dynamic);
11685
11686         mono_domain_lock (domain);
11687         ji = mono_dynamic_code_hash_lookup (domain, method);
11688         mono_domain_unlock (domain);
11689
11690         if (!ji)
11691                 return;
11692         mono_domain_lock (domain);
11693         g_hash_table_remove (domain->dynamic_code_hash, method);
11694         mono_internal_hash_table_remove (&domain->jit_code_hash, method);
11695         g_hash_table_remove (domain->jump_trampoline_hash, method);
11696         mono_domain_unlock (domain);
11697
11698 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
11699         if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
11700                 /*
11701                  * Instead of freeing the code, change it to call an error routine
11702                  * so people can fix their code.
11703                  */
11704                 char *type = mono_type_full_name (&method->klass->byval_arg);
11705                 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
11706
11707                 g_free (type);
11708                 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
11709                 destroy = FALSE;
11710         }
11711 #endif
11712
11713         /* 
11714          * This needs to be done before freeing code_mp, since the code address is the
11715          * key in the table, so if we free the code_mp first, another thread can grab the
11716          * same code address and replace our entry in the table.
11717          */
11718         mono_jit_info_table_remove (domain, ji->ji);
11719
11720         if (destroy)
11721                 mono_code_manager_destroy (ji->code_mp);
11722         mono_thread_hazardous_free_or_queue (ji->ji, g_free);
11723         g_free (ji);
11724 }
11725
11726 static gpointer
11727 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
11728 {
11729         MonoDomain *target_domain;
11730         MonoJitInfo *info;
11731
11732         if (default_opt & MONO_OPT_SHARED)
11733                 target_domain = mono_get_root_domain ();
11734         else 
11735                 target_domain = domain;
11736
11737         mono_domain_lock (target_domain);
11738
11739         if ((info = lookup_method (target_domain, method))) {
11740                 /* We can't use a domain specific method in another domain */
11741                 if (! ((domain != target_domain) && !info->domain_neutral)) {
11742                         mono_domain_unlock (target_domain);
11743                         mono_jit_stats.methods_lookups++;
11744                         return info->code_start;
11745                 }
11746         }
11747
11748         mono_domain_unlock (target_domain);
11749
11750         return NULL;
11751 }
11752
11753 /**
11754  * mono_jit_runtime_invoke:
11755  * @method: the method to invoke
11756  * @obj: this pointer
11757  * @params: array of parameter values.
11758  * @exc: used to catch exceptions objects
11759  */
11760 static MonoObject*
11761 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
11762 {
11763         MonoMethod *invoke;
11764         MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
11765         void* compiled_method;
11766
11767         if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
11768                 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
11769                 return NULL;
11770         }
11771
11772         invoke = mono_marshal_get_runtime_invoke (method);
11773         runtime_invoke = mono_jit_compile_method (invoke);
11774         
11775         /* We need this here becuase mono_marshal_get_runtime_invoke can be place 
11776          * the helper method in System.Object and not the target class
11777          */
11778         mono_runtime_class_init (mono_class_vtable (mono_domain_get (), method->klass));
11779
11780         if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
11781                 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
11782                 /* 
11783                  * Array Get/Set/Address methods. The JIT implements them using inline code 
11784                  * inside the runtime invoke wrappers, so no need to compile them.
11785                  */
11786                 compiled_method = NULL;
11787         } else {
11788                 compiled_method = mono_jit_compile_method (method);
11789         }
11790         return runtime_invoke (obj, params, exc, compiled_method);
11791 }
11792
11793 #ifdef MONO_GET_CONTEXT
11794 #define GET_CONTEXT MONO_GET_CONTEXT
11795 #endif
11796
11797 #ifndef GET_CONTEXT
11798 #ifdef PLATFORM_WIN32
11799 #define GET_CONTEXT \
11800         struct sigcontext *ctx = (struct sigcontext*)_dummy;
11801 #else
11802 #ifdef MONO_ARCH_USE_SIGACTION
11803 #define GET_CONTEXT \
11804     void *ctx = context;
11805 #elif defined(__sparc__)
11806 #define GET_CONTEXT \
11807     void *ctx = sigctx;
11808 #else
11809 #define GET_CONTEXT \
11810         void **_p = (void **)&_dummy; \
11811         struct sigcontext *ctx = (struct sigcontext *)++_p;
11812 #endif
11813 #endif
11814 #endif
11815
11816 #ifdef MONO_ARCH_USE_SIGACTION
11817 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, siginfo_t *info, void *context)
11818 #elif defined(__sparc__)
11819 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, void *sigctx)
11820 #else
11821 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy)
11822 #endif
11823
11824 static void
11825 SIG_HANDLER_SIGNATURE (sigfpe_signal_handler)
11826 {
11827         MonoException *exc = NULL;
11828 #ifndef MONO_ARCH_USE_SIGACTION
11829         void *info = NULL;
11830 #endif
11831         GET_CONTEXT;
11832
11833 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
11834         if (mono_arch_is_int_overflow (ctx, info))
11835                 exc = mono_get_exception_arithmetic ();
11836         else
11837                 exc = mono_get_exception_divide_by_zero ();
11838 #else
11839         exc = mono_get_exception_divide_by_zero ();
11840 #endif
11841         
11842         mono_arch_handle_exception (ctx, exc, FALSE);
11843 }
11844
11845 static void
11846 SIG_HANDLER_SIGNATURE (sigill_signal_handler)
11847 {
11848         MonoException *exc;
11849         GET_CONTEXT;
11850
11851         exc = mono_get_exception_execution_engine ("SIGILL");
11852         
11853         mono_arch_handle_exception (ctx, exc, FALSE);
11854 }
11855
11856 static void
11857 SIG_HANDLER_SIGNATURE (sigsegv_signal_handler)
11858 {
11859 #ifndef MONO_ARCH_SIGSEGV_ON_ALTSTACK
11860         MonoException *exc = NULL;
11861 #endif
11862         MonoJitInfo *ji;
11863
11864 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
11865         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
11866 #endif
11867         GET_CONTEXT;
11868
11869 #ifdef MONO_ARCH_USE_SIGACTION
11870         if (debug_options.collect_pagefault_stats) {
11871                 if (mono_raw_buffer_is_pagefault (info->si_addr)) {
11872                         mono_raw_buffer_handle_pagefault (info->si_addr);
11873                         return;
11874                 }
11875                 if (mono_aot_is_pagefault (info->si_addr)) {
11876                         mono_aot_handle_pagefault (info->si_addr);
11877                         return;
11878                 }
11879         }
11880 #endif
11881
11882         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (ctx));
11883
11884 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
11885         /* we got a stack overflow in the soft-guard pages
11886          * There are two cases:
11887          * 1) managed code caused the overflow: we unprotect the soft-guard page
11888          * and let the arch-specific code trigger the exception handling mechanism
11889          * in the thread stack. The soft-guard pages will be protected again as the stack is unwound.
11890          * 2) unmanaged code caused the overflow: we unprotect the soft-guard page
11891          * and hope we can continue with those enabled, at least until the hard-guard page
11892          * is hit. The alternative to continuing here is to just print a message and abort.
11893          * We may add in the future the code to protect the pages again in the codepath
11894          * when we return from unmanaged to managed code.
11895          */
11896         if (jit_tls->stack_ovf_guard_size && (guint8*)info->si_addr >= (guint8*)jit_tls->stack_ovf_guard_base &&
11897                         (guint8*)info->si_addr < (guint8*)jit_tls->stack_ovf_guard_base + jit_tls->stack_ovf_guard_size) {
11898                 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
11899                 if (ji) {
11900                         mono_arch_handle_altstack_exception (ctx, info->si_addr, TRUE);
11901                 } else {
11902                         /* We print a message: after this even managed stack overflows
11903                          * may crash the runtime
11904                          */
11905                         fprintf (stderr, "Stack overflow in unmanaged: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
11906                 }
11907                 return;
11908         }
11909         /* The hard-guard page has been hit: there is not much we can do anymore
11910          * Print a hopefully clear message and abort.
11911          */
11912         if (jit_tls->stack_size && 
11913                         ABS ((guint8*)info->si_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 32768) {
11914                 const char *method;
11915                 /* we don't do much now, but we can warn the user with a useful message */
11916                 fprintf (stderr, "Stack overflow: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
11917                 if (ji && ji->method)
11918                         method = mono_method_full_name (ji->method, TRUE);
11919                 else
11920                         method = "Unmanaged";
11921                 fprintf (stderr, "At %s\n", method);
11922                 abort ();
11923         } else {
11924                 mono_arch_handle_altstack_exception (ctx, info->si_addr, FALSE);
11925         }
11926 #else
11927
11928         if (!ji) {
11929                 mono_handle_native_sigsegv (SIGSEGV, ctx);
11930         }
11931                         
11932         mono_arch_handle_exception (ctx, exc, FALSE);
11933 #endif
11934 }
11935
11936 #ifndef PLATFORM_WIN32
11937
11938 static void
11939 SIG_HANDLER_SIGNATURE (sigabrt_signal_handler)
11940 {
11941         MonoJitInfo *ji;
11942         GET_CONTEXT;
11943
11944         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
11945         if (!ji) {
11946                 mono_handle_native_sigsegv (SIGABRT, ctx);
11947         }
11948 }
11949
11950 static void
11951 SIG_HANDLER_SIGNATURE (sigusr1_signal_handler)
11952 {
11953         gboolean running_managed;
11954         MonoException *exc;
11955         MonoThread *thread = mono_thread_current ();
11956         void *ji;
11957         
11958         GET_CONTEXT;
11959
11960         if (thread->thread_dump_requested) {
11961                 thread->thread_dump_requested = FALSE;
11962
11963                 mono_print_thread_dump (ctx);
11964         }
11965
11966         /*
11967          * FIXME:
11968          * This is an async signal, so the code below must not call anything which
11969          * is not async safe. That includes the pthread locking functions. If we
11970          * know that we interrupted managed code, then locking is safe.
11971          */
11972         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
11973         running_managed = ji != NULL;
11974         
11975         exc = mono_thread_request_interruption (running_managed); 
11976         if (!exc) return;
11977
11978         mono_arch_handle_exception (ctx, exc, FALSE);
11979 }
11980
11981 static void
11982 SIG_HANDLER_SIGNATURE (sigprof_signal_handler)
11983 {
11984         GET_CONTEXT;
11985
11986         mono_profiler_stat_hit (mono_arch_ip_from_context (ctx), ctx);
11987 }
11988
11989 static void
11990 SIG_HANDLER_SIGNATURE (sigquit_signal_handler)
11991 {
11992         GET_CONTEXT;
11993
11994         printf ("Full thread dump:\n");
11995
11996         mono_threads_request_thread_dump ();
11997
11998         /*
11999          * print_thread_dump () skips the current thread, since sending a signal
12000          * to it would invoke the signal handler below the sigquit signal handler,
12001          * and signal handlers don't create an lmf, so the stack walk could not
12002          * be performed.
12003          */
12004         mono_print_thread_dump (ctx);
12005 }
12006
12007 static void
12008 SIG_HANDLER_SIGNATURE (sigusr2_signal_handler)
12009 {
12010         gboolean enabled = mono_trace_is_enabled ();
12011
12012         mono_trace_enable (!enabled);
12013 }
12014
12015 #endif
12016
12017 static void
12018 SIG_HANDLER_SIGNATURE (sigint_signal_handler)
12019 {
12020         MonoException *exc;
12021         GET_CONTEXT;
12022
12023         exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
12024         
12025         mono_arch_handle_exception (ctx, exc, FALSE);
12026 }
12027
12028 #ifdef PLATFORM_MACOSX
12029
12030 /*
12031  * This code disables the CrashReporter of MacOS X by installing
12032  * a dummy Mach exception handler.
12033  */
12034
12035 /*
12036  * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/exc_server.html
12037  */
12038 extern
12039 boolean_t
12040 exc_server (mach_msg_header_t *request_msg,
12041             mach_msg_header_t *reply_msg);
12042
12043 /*
12044  * The exception message
12045  */
12046 typedef struct {
12047         mach_msg_base_t msg;  /* common mach message header */
12048         char payload [1024];  /* opaque */
12049 } mach_exception_msg_t;
12050
12051 /* The exception port */
12052 static mach_port_t mach_exception_port = VM_MAP_NULL;
12053
12054 /*
12055  * Implicitly called by exc_server. Must be public.
12056  *
12057  * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/catch_exception_raise.html
12058  */
12059 kern_return_t
12060 catch_exception_raise (
12061         mach_port_t exception_port,
12062         mach_port_t thread,
12063         mach_port_t task,
12064         exception_type_t exception,
12065         exception_data_t code,
12066         mach_msg_type_number_t code_count)
12067 {
12068         /* consume the exception */
12069         return KERN_FAILURE;
12070 }
12071
12072 /*
12073  * Exception thread handler.
12074  */
12075 static
12076 void *
12077 mach_exception_thread (void *arg)
12078 {
12079         for (;;) {
12080                 mach_exception_msg_t request;
12081                 mach_exception_msg_t reply;
12082                 mach_msg_return_t result;
12083
12084                 /* receive from "mach_exception_port" */
12085                 result = mach_msg (&request.msg.header,
12086                                    MACH_RCV_MSG | MACH_RCV_LARGE,
12087                                    0,
12088                                    sizeof (request),
12089                                    mach_exception_port,
12090                                    MACH_MSG_TIMEOUT_NONE,
12091                                    MACH_PORT_NULL);
12092
12093                 g_assert (result == MACH_MSG_SUCCESS);
12094
12095                 /* dispatch to catch_exception_raise () */
12096                 exc_server (&request.msg.header, &reply.msg.header);
12097
12098                 /* send back to sender */
12099                 result = mach_msg (&reply.msg.header,
12100                                    MACH_SEND_MSG,
12101                                    reply.msg.header.msgh_size,
12102                                    0,
12103                                    MACH_PORT_NULL,
12104                                    MACH_MSG_TIMEOUT_NONE,
12105                                    MACH_PORT_NULL);
12106
12107                 g_assert (result == MACH_MSG_SUCCESS);
12108         }
12109         return NULL;
12110 }
12111
12112 static void
12113 macosx_register_exception_handler ()
12114 {
12115         mach_port_t task;
12116         pthread_attr_t attr;
12117         pthread_t thread;
12118
12119         if (mach_exception_port != VM_MAP_NULL)
12120                 return;
12121
12122         task = mach_task_self ();
12123
12124         /* create the "mach_exception_port" with send & receive rights */
12125         g_assert (mach_port_allocate (task, MACH_PORT_RIGHT_RECEIVE,
12126                                       &mach_exception_port) == KERN_SUCCESS);
12127         g_assert (mach_port_insert_right (task, mach_exception_port, mach_exception_port,
12128                                           MACH_MSG_TYPE_MAKE_SEND) == KERN_SUCCESS);
12129
12130         /* create the exception handler thread */
12131         g_assert (!pthread_attr_init (&attr));
12132         g_assert (!pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED));
12133         g_assert (!pthread_create (&thread, &attr, mach_exception_thread, NULL));
12134         pthread_attr_destroy (&attr);
12135
12136         /*
12137          * register "mach_exception_port" as a receiver for the
12138          * EXC_BAD_ACCESS exception
12139          *
12140          * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/task_set_exception_ports.html
12141          */
12142         g_assert (task_set_exception_ports (task, EXC_MASK_BAD_ACCESS,
12143                                             mach_exception_port,
12144                                             EXCEPTION_DEFAULT,
12145                                             MACHINE_THREAD_STATE) == KERN_SUCCESS);
12146 }
12147 #endif
12148
12149 #ifndef PLATFORM_WIN32
12150 static void
12151 add_signal_handler (int signo, gpointer handler)
12152 {
12153         struct sigaction sa;
12154
12155 #ifdef MONO_ARCH_USE_SIGACTION
12156         sa.sa_sigaction = handler;
12157         sigemptyset (&sa.sa_mask);
12158         sa.sa_flags = SA_SIGINFO;
12159 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12160         if (signo == SIGSEGV)
12161                 sa.sa_flags |= SA_ONSTACK;
12162 #endif
12163 #else
12164         sa.sa_handler = handler;
12165         sigemptyset (&sa.sa_mask);
12166         sa.sa_flags = 0;
12167 #endif
12168         g_assert (sigaction (signo, &sa, NULL) != -1);
12169 }
12170
12171 static void
12172 remove_signal_handler (int signo)
12173 {
12174         struct sigaction sa;
12175
12176         sa.sa_handler = SIG_DFL;
12177         sigemptyset (&sa.sa_mask);
12178         sa.sa_flags = 0;
12179
12180         g_assert (sigaction (signo, &sa, NULL) != -1);
12181 }
12182 #endif
12183
12184 static void
12185 mono_runtime_install_handlers (void)
12186 {
12187 #ifdef PLATFORM_WIN32
12188         win32_seh_init();
12189         win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
12190         win32_seh_set_handler(SIGILL, sigill_signal_handler);
12191         win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
12192         if (debug_options.handle_sigint)
12193                 win32_seh_set_handler(SIGINT, sigint_signal_handler);
12194
12195 #else /* !PLATFORM_WIN32 */
12196
12197
12198 #ifdef PLATFORM_MACOSX
12199         macosx_register_exception_handler ();
12200 #endif
12201
12202         if (debug_options.handle_sigint)
12203                 add_signal_handler (SIGINT, sigint_signal_handler);
12204
12205         add_signal_handler (SIGFPE, sigfpe_signal_handler);
12206         add_signal_handler (SIGQUIT, sigquit_signal_handler);
12207         add_signal_handler (SIGILL, sigill_signal_handler);
12208         add_signal_handler (SIGBUS, sigsegv_signal_handler);
12209         if (mono_jit_trace_calls != NULL)
12210                 add_signal_handler (SIGUSR2, sigusr2_signal_handler);
12211
12212         add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
12213         signal (SIGPIPE, SIG_IGN);
12214
12215         add_signal_handler (SIGABRT, sigabrt_signal_handler);
12216
12217         /* catch SIGSEGV */
12218         add_signal_handler (SIGSEGV, sigsegv_signal_handler);
12219 #endif /* PLATFORM_WIN32 */
12220 }
12221
12222 static void
12223 mono_runtime_cleanup_handlers (void)
12224 {
12225 #ifdef PLATFORM_WIN32
12226         win32_seh_cleanup();
12227 #else
12228         if (debug_options.handle_sigint)
12229                 remove_signal_handler (SIGINT);
12230
12231         remove_signal_handler (SIGFPE);
12232         remove_signal_handler (SIGQUIT);
12233         remove_signal_handler (SIGILL);
12234         remove_signal_handler (SIGBUS);
12235         if (mono_jit_trace_calls != NULL)
12236                 remove_signal_handler (SIGUSR2);
12237
12238         remove_signal_handler (mono_thread_get_abort_signal ());
12239
12240         remove_signal_handler (SIGABRT);
12241
12242         remove_signal_handler (SIGSEGV);
12243 #endif /* PLATFORM_WIN32 */
12244 }
12245
12246
12247 #ifdef HAVE_LINUX_RTC_H
12248 #include <linux/rtc.h>
12249 #include <sys/ioctl.h>
12250 #include <fcntl.h>
12251 static int rtc_fd = -1;
12252
12253 static int
12254 enable_rtc_timer (gboolean enable)
12255 {
12256         int flags;
12257         flags = fcntl (rtc_fd, F_GETFL);
12258         if (flags < 0) {
12259                 perror ("getflags");
12260                 return 0;
12261         }
12262         if (enable)
12263                 flags |= FASYNC;
12264         else
12265                 flags &= ~FASYNC;
12266         if (fcntl (rtc_fd, F_SETFL, flags) == -1) {
12267                 perror ("setflags");
12268                 return 0;
12269         }
12270         return 1;
12271 }
12272 #endif
12273
12274 #ifdef PLATFORM_WIN32
12275 static HANDLE win32_main_thread;
12276 static MMRESULT win32_timer;
12277
12278 static void CALLBACK
12279 win32_time_proc (UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
12280 {
12281         CONTEXT context;
12282
12283         context.ContextFlags = CONTEXT_CONTROL;
12284         if (GetThreadContext (win32_main_thread, &context)) {
12285 #ifdef _WIN64
12286                 mono_profiler_stat_hit ((guchar *) context.Rip, &context);
12287 #else
12288                 mono_profiler_stat_hit ((guchar *) context.Eip, &context);
12289 #endif
12290         }
12291 }
12292 #endif
12293
12294 static void
12295 setup_stat_profiler (void)
12296 {
12297 #ifdef ITIMER_PROF
12298         struct itimerval itval;
12299         static int inited = 0;
12300 #ifdef HAVE_LINUX_RTC_H
12301         const char *rtc_freq;
12302         if (!inited && (rtc_freq = g_getenv ("MONO_RTC"))) {
12303                 int freq = 0;
12304                 inited = 1;
12305                 if (*rtc_freq)
12306                         freq = atoi (rtc_freq);
12307                 if (!freq)
12308                         freq = 1024;
12309                 rtc_fd = open ("/dev/rtc", O_RDONLY);
12310                 if (rtc_fd == -1) {
12311                         perror ("open /dev/rtc");
12312                         return;
12313                 }
12314                 add_signal_handler (SIGPROF, sigprof_signal_handler);
12315                 if (ioctl (rtc_fd, RTC_IRQP_SET, freq) == -1) {
12316                         perror ("set rtc freq");
12317                         return;
12318                 }
12319                 if (ioctl (rtc_fd, RTC_PIE_ON, 0) == -1) {
12320                         perror ("start rtc");
12321                         return;
12322                 }
12323                 if (fcntl (rtc_fd, F_SETSIG, SIGPROF) == -1) {
12324                         perror ("setsig");
12325                         return;
12326                 }
12327                 if (fcntl (rtc_fd, F_SETOWN, getpid ()) == -1) {
12328                         perror ("setown");
12329                         return;
12330                 }
12331                 enable_rtc_timer (TRUE);
12332                 return;
12333         }
12334         if (rtc_fd >= 0)
12335                 return;
12336 #endif
12337
12338         itval.it_interval.tv_usec = 999;
12339         itval.it_interval.tv_sec = 0;
12340         itval.it_value = itval.it_interval;
12341         setitimer (ITIMER_PROF, &itval, NULL);
12342         if (inited)
12343                 return;
12344         inited = 1;
12345         add_signal_handler (SIGPROF, sigprof_signal_handler);
12346 #elif defined (PLATFORM_WIN32)
12347         static int inited = 0;
12348         TIMECAPS timecaps;
12349
12350         if (inited)
12351                 return;
12352
12353         inited = 1;
12354         if (timeGetDevCaps (&timecaps, sizeof (timecaps)) != TIMERR_NOERROR)
12355                 return;
12356
12357         if ((win32_main_thread = OpenThread (READ_CONTROL | THREAD_GET_CONTEXT, FALSE, GetCurrentThreadId ())) == NULL)
12358                 return;
12359
12360         if (timeBeginPeriod (1) != TIMERR_NOERROR)
12361                 return;
12362
12363         if ((win32_timer = timeSetEvent (1, 0, win32_time_proc, 0, TIME_PERIODIC)) == 0) {
12364                 timeEndPeriod (1);
12365                 return;
12366         }
12367 #endif
12368 }
12369
12370 /* mono_jit_create_remoting_trampoline:
12371  * @method: pointer to the method info
12372  *
12373  * Creates a trampoline which calls the remoting functions. This
12374  * is used in the vtable of transparent proxies.
12375  * 
12376  * Returns: a pointer to the newly created code 
12377  */
12378 static gpointer
12379 mono_jit_create_remoting_trampoline (MonoMethod *method, MonoRemotingTarget target)
12380 {
12381         MonoMethod *nm;
12382         guint8 *addr = NULL;
12383
12384         if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || 
12385             (mono_method_signature (method)->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
12386                 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
12387                 addr = mono_compile_method (nm);
12388         } else {
12389                 addr = mono_compile_method (method);
12390         }
12391         return mono_get_addr_from_ftnptr (addr);
12392 }
12393
12394 #ifdef MONO_ARCH_HAVE_IMT
12395 static gpointer
12396 mini_get_imt_trampoline (void)
12397 {
12398         static gpointer tramp = NULL;
12399         if (!tramp)
12400                 tramp =  mono_arch_create_specific_trampoline (MONO_FAKE_IMT_METHOD, MONO_TRAMPOLINE_GENERIC, mono_get_root_domain (), NULL);
12401         return tramp;
12402 }
12403 #endif
12404
12405 #ifdef MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
12406 gpointer
12407 mini_get_vtable_trampoline (void)
12408 {
12409         static gpointer tramp = NULL;
12410         if (!tramp)
12411                 tramp =  mono_arch_create_specific_trampoline (MONO_FAKE_VTABLE_METHOD, MONO_TRAMPOLINE_GENERIC, mono_get_root_domain (), NULL);
12412         return tramp;
12413 }
12414 #endif
12415
12416 static void
12417 mini_parse_debug_options (void)
12418 {
12419         char *options = getenv ("MONO_DEBUG");
12420         gchar **args, **ptr;
12421         
12422         if (!options)
12423                 return;
12424
12425         args = g_strsplit (options, ",", -1);
12426
12427         for (ptr = args; ptr && *ptr; ptr++) {
12428                 const char *arg = *ptr;
12429
12430                 if (!strcmp (arg, "handle-sigint"))
12431                         debug_options.handle_sigint = TRUE;
12432                 else if (!strcmp (arg, "keep-delegates"))
12433                         debug_options.keep_delegates = TRUE;
12434                 else if (!strcmp (arg, "collect-pagefault-stats"))
12435                         debug_options.collect_pagefault_stats = TRUE;
12436                 else if (!strcmp (arg, "break-on-unverified"))
12437                         debug_options.break_on_unverified = TRUE;
12438                 else {
12439                         fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
12440                         fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'collect-pagefault-stats', 'break-on-unverified'\n");
12441                         exit (1);
12442                 }
12443         }
12444 }
12445
12446 MonoDomain *
12447 mini_init (const char *filename, const char *runtime_version)
12448 {
12449         MonoDomain *domain;
12450
12451 #ifdef __linux__
12452         if (access ("/proc/self/maps", F_OK) != 0) {
12453                 g_print ("Mono requires /proc to be mounted.\n");
12454                 exit (1);
12455         }
12456 #endif
12457
12458         /* Happens when using the embedding interface */
12459         if (!default_opt_set)
12460                 default_opt = mono_parse_default_optimizations (NULL);
12461
12462         InitializeCriticalSection (&jit_mutex);
12463
12464         if (!global_codeman)
12465                 global_codeman = mono_code_manager_new ();
12466         jit_icall_name_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
12467
12468         mono_arch_cpu_init ();
12469
12470         mono_arch_init ();
12471
12472         mono_init_trampolines ();
12473
12474         mono_init_exceptions ();
12475
12476         if (!g_thread_supported ())
12477                 g_thread_init (NULL);
12478
12479         if (getenv ("MONO_DEBUG") != NULL)
12480                 mini_parse_debug_options ();
12481
12482         /*
12483          * Handle the case when we are called from a thread different from the main thread,
12484          * confusing libgc.
12485          * FIXME: Move this to libgc where it belongs.
12486          *
12487          * we used to do this only when running on valgrind,
12488          * but it happens also in other setups.
12489          */
12490 #if defined(HAVE_BOEHM_GC)
12491 #if defined(HAVE_PTHREAD_GETATTR_NP) && defined(HAVE_PTHREAD_ATTR_GETSTACK)
12492         {
12493                 size_t size;
12494                 void *sstart;
12495                 pthread_attr_t attr;
12496                 pthread_getattr_np (pthread_self (), &attr);
12497                 pthread_attr_getstack (&attr, &sstart, &size);
12498                 pthread_attr_destroy (&attr); 
12499                 /*g_print ("stackbottom pth is: %p\n", (char*)sstart + size);*/
12500 #ifdef __ia64__
12501                 /*
12502                  * The calculation above doesn't seem to work on ia64, also we need to set
12503                  * GC_register_stackbottom as well, but don't know how.
12504                  */
12505 #else
12506                 /* apparently with some linuxthreads implementations sstart can be NULL,
12507                  * fallback to the more imprecise method (bug# 78096).
12508                  */
12509                 if (sstart) {
12510                         GC_stackbottom = (char*)sstart + size;
12511                 } else {
12512                         gsize stack_bottom = (gsize)&domain;
12513                         stack_bottom += 4095;
12514                         stack_bottom &= ~4095;
12515                         GC_stackbottom = (char*)stack_bottom;
12516                 }
12517 #endif
12518         }
12519 #elif defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
12520                 GC_stackbottom = (char*)pthread_get_stackaddr_np (pthread_self ());
12521 #else
12522         {
12523                 gsize stack_bottom = (gsize)&domain;
12524                 stack_bottom += 4095;
12525                 stack_bottom &= ~4095;
12526                 /*g_print ("stackbottom is: %p\n", (char*)stack_bottom);*/
12527                 GC_stackbottom = (char*)stack_bottom;
12528         }
12529 #endif
12530 #endif
12531         MONO_GC_PRE_INIT ();
12532
12533         mono_jit_tls_id = TlsAlloc ();
12534         setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
12535
12536         mono_burg_init ();
12537
12538         if (default_opt & MONO_OPT_AOT)
12539                 mono_aot_init ();
12540
12541         mono_runtime_install_handlers ();
12542         mono_threads_install_cleanup (mini_thread_cleanup);
12543
12544 #define JIT_TRAMPOLINES_WORK
12545 #ifdef JIT_TRAMPOLINES_WORK
12546         mono_install_compile_method (mono_jit_compile_method);
12547         mono_install_free_method (mono_jit_free_method);
12548         mono_install_trampoline (mono_create_jit_trampoline);
12549         mono_install_jump_trampoline (mono_create_jump_trampoline);
12550         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
12551         mono_install_delegate_trampoline (mono_create_delegate_trampoline);
12552 #endif
12553 #define JIT_INVOKE_WORKS
12554 #ifdef JIT_INVOKE_WORKS
12555         mono_install_runtime_invoke (mono_jit_runtime_invoke);
12556         mono_install_handler (mono_arch_get_throw_exception ());
12557 #endif
12558         mono_install_stack_walk (mono_jit_walk_stack);
12559         mono_install_init_vtable (mono_aot_init_vtable);
12560         mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
12561         mono_install_get_class_from_name (mono_aot_get_class_from_name);
12562         mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
12563
12564         if (debug_options.collect_pagefault_stats) {
12565                 mono_raw_buffer_set_make_unreadable (TRUE);
12566                 mono_aot_set_make_unreadable (TRUE);
12567         }
12568
12569         if (runtime_version)
12570                 domain = mono_init_version (filename, runtime_version);
12571         else
12572                 domain = mono_init_from_assembly (filename, filename);
12573 #ifdef MONO_ARCH_HAVE_IMT
12574         mono_install_imt_thunk_builder (mono_arch_build_imt_thunk);
12575         mono_install_imt_trampoline (mini_get_imt_trampoline ());
12576 #if MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
12577         mono_install_vtable_trampoline (mini_get_vtable_trampoline ());
12578 #endif
12579 #endif
12580         mono_icall_init ();
12581
12582         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info", 
12583                                 ves_icall_get_frame_info);
12584         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace", 
12585                                 ves_icall_get_trace);
12586         mono_add_internal_call ("System.Exception::get_trace", 
12587                                 ves_icall_System_Exception_get_trace);
12588         mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityFrame",
12589                                 ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
12590         mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityStack",
12591                                 ves_icall_System_Security_SecurityFrame_GetSecurityStack);
12592         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers", 
12593                                 mono_runtime_install_handlers);
12594
12595
12596         create_helper_signature ();
12597
12598 #define JIT_CALLS_WORK
12599 #ifdef JIT_CALLS_WORK
12600         /* Needs to be called here since register_jit_icall depends on it */
12601         mono_marshal_init ();
12602
12603         mono_arch_register_lowlevel_calls ();
12604         register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
12605         register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
12606         register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
12607         register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
12608         register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
12609         register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "void", TRUE);
12610         register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
12611
12612         register_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
12613         register_icall (mono_arch_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
12614         register_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", "void ptr", TRUE); 
12615 #if MONO_ARCH_HAVE_THROW_CORLIB_EXCEPTION
12616         register_icall (mono_arch_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception", 
12617                                  "void ptr", TRUE);
12618 #endif
12619         register_icall (mono_thread_get_pending_exception, "mono_thread_get_pending_exception", "object", FALSE);
12620         register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "void", FALSE);
12621         register_icall (mono_thread_force_interruption_checkpoint, "mono_thread_force_interruption_checkpoint", "void", FALSE);
12622         register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
12623         register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
12624
12625         /* 
12626          * NOTE, NOTE, NOTE, NOTE:
12627          * when adding emulation for some opcodes, remember to also add a dummy
12628          * rule to the burg files, because we need the arity information to be correct.
12629          */
12630 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
12631         mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, TRUE);
12632         mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, FALSE);
12633         mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, FALSE);
12634         mono_register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, FALSE);
12635         mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, FALSE);
12636         mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, FALSE);
12637         mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, FALSE);
12638 #endif
12639
12640 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
12641         mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, TRUE);
12642         mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, TRUE);
12643         mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, TRUE);
12644 #endif
12645
12646 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
12647         mono_register_opcode_emulation (CEE_DIV, "__emul_idiv", "int32 int32 int32", mono_idiv, FALSE);
12648         mono_register_opcode_emulation (CEE_DIV_UN, "__emul_idiv_un", "int32 int32 int32", mono_idiv_un, FALSE);
12649         mono_register_opcode_emulation (CEE_REM, "__emul_irem", "int32 int32 int32", mono_irem, FALSE);
12650         mono_register_opcode_emulation (CEE_REM_UN, "__emul_irem_un", "int32 int32 int32", mono_irem_un, FALSE);
12651 #endif
12652
12653 #ifdef MONO_ARCH_EMULATE_MUL_DIV
12654         mono_register_opcode_emulation (CEE_MUL_OVF, "__emul_imul_ovf", "int32 int32 int32", mono_imul_ovf, FALSE);
12655         mono_register_opcode_emulation (CEE_MUL_OVF_UN, "__emul_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, FALSE);
12656         mono_register_opcode_emulation (CEE_MUL, "__emul_imul", "int32 int32 int32", mono_imul, TRUE);
12657 #endif
12658 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_SOFT_FLOAT)
12659         mono_register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, FALSE);
12660 #endif
12661
12662         mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, FALSE);
12663         mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, FALSE);
12664         mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, FALSE);
12665         mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, FALSE);
12666
12667 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
12668         mono_register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, FALSE);
12669 #endif
12670 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
12671         mono_register_opcode_emulation (CEE_CONV_R_UN, "__emul_conv_r_un", "double int32", mono_conv_to_r8_un, FALSE);
12672 #endif
12673 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
12674         mono_register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, FALSE);
12675 #endif
12676 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
12677         mono_register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, FALSE);
12678 #endif
12679 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
12680         mono_register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", "double long", mono_lconv_to_r8_un, FALSE);
12681 #endif
12682 #ifdef MONO_ARCH_EMULATE_FREM
12683         mono_register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, FALSE);
12684 #endif
12685
12686 #ifdef MONO_ARCH_SOFT_FLOAT
12687         mono_register_opcode_emulation (OP_FSUB, "__emul_fsub", "double double double", mono_fsub, FALSE);
12688         mono_register_opcode_emulation (OP_FADD, "__emul_fadd", "double double double", mono_fadd, FALSE);
12689         mono_register_opcode_emulation (OP_FMUL, "__emul_fmul", "double double double", mono_fmul, FALSE);
12690         mono_register_opcode_emulation (OP_FNEG, "__emul_fneg", "double double", mono_fneg, FALSE);
12691         mono_register_opcode_emulation (CEE_CONV_R8, "__emul_conv_r8", "double int32", mono_conv_to_r8, FALSE);
12692         mono_register_opcode_emulation (CEE_CONV_R4, "__emul_conv_r4", "double int32", mono_conv_to_r4, FALSE);
12693         mono_register_opcode_emulation (OP_FCONV_TO_R4, "__emul_fconv_to_r4", "double double", mono_fconv_r4, FALSE);
12694         mono_register_opcode_emulation (OP_FCONV_TO_I1, "__emul_fconv_to_i1", "int8 double", mono_fconv_i1, FALSE);
12695         mono_register_opcode_emulation (OP_FCONV_TO_I2, "__emul_fconv_to_i2", "int16 double", mono_fconv_i2, FALSE);
12696         mono_register_opcode_emulation (OP_FCONV_TO_I4, "__emul_fconv_to_i4", "int32 double", mono_fconv_i4, FALSE);
12697         mono_register_opcode_emulation (OP_FCONV_TO_U1, "__emul_fconv_to_u1", "uint8 double", mono_fconv_u1, FALSE);
12698         mono_register_opcode_emulation (OP_FCONV_TO_U2, "__emul_fconv_to_u2", "uint16 double", mono_fconv_u2, FALSE);
12699
12700         mono_register_opcode_emulation (OP_FBEQ, "__emul_fcmp_eq", "uint32 double double", mono_fcmp_eq, FALSE);
12701         mono_register_opcode_emulation (OP_FBLT, "__emul_fcmp_lt", "uint32 double double", mono_fcmp_lt, FALSE);
12702         mono_register_opcode_emulation (OP_FBGT, "__emul_fcmp_gt", "uint32 double double", mono_fcmp_gt, FALSE);
12703         mono_register_opcode_emulation (OP_FBLE, "__emul_fcmp_le", "uint32 double double", mono_fcmp_le, FALSE);
12704         mono_register_opcode_emulation (OP_FBGE, "__emul_fcmp_ge", "uint32 double double", mono_fcmp_ge, FALSE);
12705         mono_register_opcode_emulation (OP_FBNE_UN, "__emul_fcmp_ne_un", "uint32 double double", mono_fcmp_ne_un, FALSE);
12706         mono_register_opcode_emulation (OP_FBLT_UN, "__emul_fcmp_lt_un", "uint32 double double", mono_fcmp_lt_un, FALSE);
12707         mono_register_opcode_emulation (OP_FBGT_UN, "__emul_fcmp_gt_un", "uint32 double double", mono_fcmp_gt_un, FALSE);
12708         mono_register_opcode_emulation (OP_FBLE_UN, "__emul_fcmp_le_un", "uint32 double double", mono_fcmp_le_un, FALSE);
12709         mono_register_opcode_emulation (OP_FBGE_UN, "__emul_fcmp_ge_un", "uint32 double double", mono_fcmp_ge_un, FALSE);
12710
12711         mono_register_opcode_emulation (OP_FCEQ, "__emul_fcmp_ceq", "uint32 double double", mono_fceq, FALSE);
12712         mono_register_opcode_emulation (OP_FCGT, "__emul_fcmp_cgt", "uint32 double double", mono_fcgt, FALSE);
12713         mono_register_opcode_emulation (OP_FCGT_UN, "__emul_fcmp_cgt_un", "uint32 double double", mono_fcgt_un, FALSE);
12714         mono_register_opcode_emulation (OP_FCLT, "__emul_fcmp_clt", "uint32 double double", mono_fclt, FALSE);
12715         mono_register_opcode_emulation (OP_FCLT_UN, "__emul_fcmp_clt_un", "uint32 double double", mono_fclt_un, FALSE);
12716
12717         register_icall (mono_fload_r4, "mono_fload_r4", "double ptr", FALSE);
12718         register_icall (mono_fstore_r4, "mono_fstore_r4", "void double ptr", FALSE);
12719         register_icall (mono_fload_r4_arg, "mono_fload_r4_arg", "uint32 double", FALSE);
12720 #endif
12721
12722 #if SIZEOF_VOID_P == 4
12723         mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, TRUE);
12724 #endif
12725
12726         /* other jit icalls */
12727         register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
12728         register_icall (mono_class_static_field_address , "mono_class_static_field_address", 
12729                                  "ptr ptr ptr", FALSE);
12730         register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
12731         register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
12732         register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
12733         register_icall (mono_helper_stelem_ref_check, "helper_stelem_ref_check", "void object object", FALSE);
12734         register_icall (mono_object_new, "mono_object_new", "object ptr ptr", FALSE);
12735         register_icall (mono_object_new_specific, "mono_object_new_specific", "object ptr", FALSE);
12736         register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
12737         register_icall (mono_array_new_specific, "mono_array_new_specific", "object ptr int32", FALSE);
12738         register_icall (mono_runtime_class_init, "mono_runtime_class_init", "void ptr", FALSE);
12739         register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
12740         register_icall (mono_ldftn_nosync, "mono_ldftn_nosync", "ptr ptr", FALSE);
12741         register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
12742         register_icall (mono_helper_compile_generic_method, "compile_generic_method", "ptr object ptr ptr ptr", FALSE);
12743         register_icall (mono_helper_ldstr, "helper_ldstr", "object ptr int", FALSE);
12744         register_icall (mono_helper_ldstr_mscorlib, "helper_ldstr_mscorlib", "object int", FALSE);
12745         register_icall (mono_helper_newobj_mscorlib, "helper_newobj_mscorlib", "object int", FALSE);
12746         register_icall (mono_value_copy, "mono_value_copy", "void ptr ptr ptr", FALSE);
12747         register_icall (mono_helper_get_rgctx_other_ptr, "get_rgctx_other_ptr", "ptr ptr ptr int32 int32", FALSE);
12748 #endif
12749
12750 #define JIT_RUNTIME_WORKS
12751 #ifdef JIT_RUNTIME_WORKS
12752         mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
12753         mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
12754 #endif
12755
12756         mono_generic_sharing_init ();
12757
12758         mono_thread_attach (domain);
12759         return domain;
12760 }
12761
12762 MonoJitStats mono_jit_stats = {0};
12763
12764 static void 
12765 print_jit_stats (void)
12766 {
12767         if (mono_jit_stats.enabled) {
12768                 g_print ("Mono Jit statistics\n");
12769                 g_print ("Compiled methods:       %ld\n", mono_jit_stats.methods_compiled);
12770                 g_print ("Methods from AOT:       %ld\n", mono_jit_stats.methods_aot);
12771                 g_print ("Methods cache lookup:   %ld\n", mono_jit_stats.methods_lookups);
12772                 g_print ("Method trampolines:     %ld\n", mono_jit_stats.method_trampolines);
12773                 g_print ("Basic blocks:           %ld\n", mono_jit_stats.basic_blocks);
12774                 g_print ("Max basic blocks:       %ld\n", mono_jit_stats.max_basic_blocks);
12775                 g_print ("Allocated vars:         %ld\n", mono_jit_stats.allocate_var);
12776                 g_print ("Analyze stack repeat:   %ld\n", mono_jit_stats.analyze_stack_repeat);
12777                 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
12778                 g_print ("Native code size:       %ld\n", mono_jit_stats.native_code_size);
12779                 g_print ("Max code size ratio:    %.2f (%s::%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
12780                                 mono_jit_stats.max_ratio_method->klass->name, mono_jit_stats.max_ratio_method->name);
12781                 g_print ("Biggest method:         %ld (%s::%s)\n", mono_jit_stats.biggest_method_size,
12782                                 mono_jit_stats.biggest_method->klass->name, mono_jit_stats.biggest_method->name);
12783                 g_print ("Code reallocs:          %ld\n", mono_jit_stats.code_reallocs);
12784                 g_print ("Allocated code size:    %ld\n", mono_jit_stats.allocated_code_size);
12785                 g_print ("Inlineable methods:     %ld\n", mono_jit_stats.inlineable_methods);
12786                 g_print ("Inlined methods:        %ld\n", mono_jit_stats.inlined_methods);
12787                 g_print ("Locals stack size:      %ld\n", mono_jit_stats.locals_stack_size);
12788
12789                 g_print ("\nCreated object count:   %ld\n", mono_stats.new_object_count);
12790                 g_print ("Delegates created:      %ld\n", mono_stats.delegate_creations);
12791                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
12792                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
12793                 g_print ("Generic vtables:        %ld\n", mono_stats.generic_vtable_count);
12794                 g_print ("Methods:                %ld\n", mono_stats.method_count);
12795                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
12796                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
12797                 g_print ("Mscorlib mempool size:  %d\n", mono_mempool_get_allocated (mono_defaults.corlib->mempool));
12798
12799                 g_print ("\nGeneric instances:      %ld\n", mono_stats.generic_instance_count);
12800                 g_print ("Initialized classes:    %ld\n", mono_stats.generic_class_count);
12801                 g_print ("Inflated methods:       %ld / %ld\n", mono_stats.inflated_method_count_2,
12802                          mono_stats.inflated_method_count);
12803                 g_print ("Inflated types:         %ld\n", mono_stats.inflated_type_count);
12804                 g_print ("Generics metadata size: %ld\n", mono_stats.generics_metadata_size);
12805                 g_print ("Generics virtual invokes: %ld\n", mono_jit_stats.generic_virtual_invocations);
12806
12807                 g_print ("Sharable generic methods: %ld\n", mono_stats.generics_sharable_methods);
12808                 g_print ("Unsharable generic methods: %ld\n", mono_stats.generics_unsharable_methods);
12809                 g_print ("Shared generic methods: %ld\n", mono_stats.generics_shared_methods);
12810
12811                 g_print ("Dynamic code allocs:    %ld\n", mono_stats.dynamic_code_alloc_count);
12812                 g_print ("Dynamic code bytes:     %ld\n", mono_stats.dynamic_code_bytes_count);
12813                 g_print ("Dynamic code frees:     %ld\n", mono_stats.dynamic_code_frees_count);
12814
12815                 g_print ("IMT tables size:        %ld\n", mono_stats.imt_tables_size);
12816                 g_print ("IMT number of tables:   %ld\n", mono_stats.imt_number_of_tables);
12817                 g_print ("IMT number of methods:  %ld\n", mono_stats.imt_number_of_methods);
12818                 g_print ("IMT used slots:         %ld\n", mono_stats.imt_used_slots);
12819                 g_print ("IMT colliding slots:    %ld\n", mono_stats.imt_slots_with_collisions);
12820                 g_print ("IMT max collisions:     %ld\n", mono_stats.imt_max_collisions_in_slot);
12821                 g_print ("IMT methods at max col: %ld\n", mono_stats.imt_method_count_when_max_collisions);
12822                 g_print ("IMT thunks size:        %ld\n", mono_stats.imt_thunks_size);
12823
12824                 g_print ("JIT info table inserts: %ld\n", mono_stats.jit_info_table_insert_count);
12825                 g_print ("JIT info table removes: %ld\n", mono_stats.jit_info_table_remove_count);
12826                 g_print ("JIT info table lookups: %ld\n", mono_stats.jit_info_table_lookup_count);
12827
12828                 g_print ("Hazardous pointers:     %ld\n", mono_stats.hazardous_pointer_count);
12829
12830                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
12831                         g_print ("\nDecl security check   : %ld\n", mono_jit_stats.cas_declsec_check);
12832                         g_print ("LinkDemand (user)     : %ld\n", mono_jit_stats.cas_linkdemand);
12833                         g_print ("LinkDemand (icall)    : %ld\n", mono_jit_stats.cas_linkdemand_icall);
12834                         g_print ("LinkDemand (pinvoke)  : %ld\n", mono_jit_stats.cas_linkdemand_pinvoke);
12835                         g_print ("LinkDemand (aptc)     : %ld\n", mono_jit_stats.cas_linkdemand_aptc);
12836                         g_print ("Demand (code gen)     : %ld\n", mono_jit_stats.cas_demand_generation);
12837                 }
12838                 if (debug_options.collect_pagefault_stats) {
12839                         g_print ("Metadata pagefaults   : %d\n", mono_raw_buffer_get_n_pagefaults ());
12840                         g_print ("AOT pagefaults        : %d\n", mono_aot_get_n_pagefaults ());
12841                 }
12842         }
12843 }
12844
12845 void
12846 mini_cleanup (MonoDomain *domain)
12847 {
12848 #ifdef HAVE_LINUX_RTC_H
12849         if (rtc_fd >= 0)
12850                 enable_rtc_timer (FALSE);
12851 #endif
12852
12853         /* 
12854          * mono_runtime_cleanup() and mono_domain_finalize () need to
12855          * be called early since they need the execution engine still
12856          * fully working (mono_domain_finalize may invoke managed finalizers
12857          * and mono_runtime_cleanup will wait for other threads to finish).
12858          */
12859         mono_domain_finalize (domain, 2000);
12860
12861         /* This accesses metadata so needs to be called before runtime shutdown */
12862         print_jit_stats ();
12863
12864         mono_runtime_cleanup (domain);
12865
12866         mono_profiler_shutdown ();
12867
12868         mono_icall_cleanup ();
12869
12870         mono_runtime_cleanup_handlers ();
12871
12872         mono_domain_free (domain, TRUE);
12873
12874         mono_debugger_cleanup ();
12875
12876         mono_code_manager_destroy (global_codeman);
12877         g_hash_table_destroy (jit_icall_name_hash);
12878         if (class_init_hash_addr)
12879                 g_hash_table_destroy (class_init_hash_addr);
12880         g_free (emul_opcode_map);
12881
12882         mono_arch_cleanup ();
12883
12884         mono_cleanup ();
12885
12886         mono_trace_cleanup ();
12887
12888         mono_counters_dump (-1, stdout);
12889
12890         if (mono_inject_async_exc_method)
12891                 mono_method_desc_free (mono_inject_async_exc_method);
12892
12893         TlsFree(mono_jit_tls_id);
12894
12895         DeleteCriticalSection (&jit_mutex);
12896
12897         DeleteCriticalSection (&mono_delegate_section);
12898 }
12899
12900 void
12901 mono_set_defaults (int verbose_level, guint32 opts)
12902 {
12903         mini_verbose = verbose_level;
12904         default_opt = opts;
12905         default_opt_set = TRUE;
12906 }
12907
12908 static void
12909 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
12910 {
12911         GHashTable *assemblies = (GHashTable*)user_data;
12912         MonoImage *image = mono_assembly_get_image (ass);
12913         MonoMethod *method, *invoke;
12914         int i, count = 0;
12915
12916         if (g_hash_table_lookup (assemblies, ass))
12917                 return;
12918
12919         g_hash_table_insert (assemblies, ass, ass);
12920
12921         if (mini_verbose > 0)
12922                 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
12923
12924         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
12925                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
12926                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
12927                         continue;
12928
12929                 count++;
12930                 if (mini_verbose > 1) {
12931                         char * desc = mono_method_full_name (method, TRUE);
12932                         g_print ("Compiling %d %s\n", count, desc);
12933                         g_free (desc);
12934                 }
12935                 mono_compile_method (method);
12936                 if (strcmp (method->name, "Finalize") == 0) {
12937                         invoke = mono_marshal_get_runtime_invoke (method);
12938                         mono_compile_method (invoke);
12939                 }
12940                 if (method->klass->marshalbyref && mono_method_signature (method)->hasthis) {
12941                         invoke = mono_marshal_get_remoting_invoke_with_check (method);
12942                         mono_compile_method (invoke);
12943                 }
12944         }
12945
12946         /* Load and precompile referenced assemblies as well */
12947         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
12948                 mono_assembly_load_reference (image, i);
12949                 if (image->references [i])
12950                         mono_precompile_assembly (image->references [i], assemblies);
12951         }
12952 }
12953
12954 void mono_precompile_assemblies ()
12955 {
12956         GHashTable *assemblies = g_hash_table_new (NULL, NULL);
12957
12958         mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
12959
12960         g_hash_table_destroy (assemblies);
12961 }