2008-07-09 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 HAVE_VALGRIND_MEMCHECK_H
30 #include <valgrind/memcheck.h>
31 #endif
32
33 #include <mono/metadata/assembly.h>
34 #include <mono/metadata/loader.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/class.h>
37 #include <mono/metadata/object.h>
38 #include <mono/metadata/exception.h>
39 #include <mono/metadata/opcodes.h>
40 #include <mono/metadata/mono-endian.h>
41 #include <mono/metadata/tokentype.h>
42 #include <mono/metadata/tabledefs.h>
43 #include <mono/metadata/threads.h>
44 #include <mono/metadata/marshal.h>
45 #include <mono/metadata/socket-io.h>
46 #include <mono/metadata/appdomain.h>
47 #include <mono/metadata/debug-helpers.h>
48 #include <mono/io-layer/io-layer.h>
49 #include "mono/metadata/profiler.h"
50 #include <mono/metadata/profiler-private.h>
51 #include <mono/metadata/mono-config.h>
52 #include <mono/metadata/environment.h>
53 #include <mono/metadata/mono-debug.h>
54 #include <mono/metadata/monitor.h>
55 #include <mono/metadata/gc-internal.h>
56 #include <mono/metadata/security-manager.h>
57 #include <mono/metadata/threads-types.h>
58 #include <mono/metadata/rawbuffer.h>
59 #include <mono/metadata/security-core-clr.h>
60 #include <mono/metadata/verify.h>
61 #include <mono/metadata/verify-internals.h>
62 #include <mono/utils/mono-math.h>
63 #include <mono/utils/mono-compiler.h>
64 #include <mono/utils/mono-counters.h>
65 #include <mono/utils/mono-logger.h>
66 #include <mono/utils/mono-mmap.h>
67 #include <mono/utils/dtrace.h>
68
69 #include "mini.h"
70 #include <string.h>
71 #include <ctype.h>
72 #include "inssel.h"
73 #include "trace.h"
74
75 #include "jit-icalls.h"
76
77 #include "aliasing.h"
78
79 #include "debug-mini.h"
80
81 #define BRANCH_COST 100
82 #define INLINE_LENGTH_LIMIT 20
83 #define INLINE_FAILURE do {\
84                 if ((cfg->method != method) && (method->wrapper_type == MONO_WRAPPER_NONE))\
85                         goto inline_failure;\
86         } while (0)
87 #define CHECK_CFG_EXCEPTION do {\
88                 if (cfg->exception_type != MONO_EXCEPTION_NONE)\
89                         goto exception_exit;\
90         } while (0)
91 #define METHOD_ACCESS_FAILURE do {      \
92                 char *method_fname = mono_method_full_name (method, TRUE);      \
93                 char *cil_method_fname = mono_method_full_name (cil_method, TRUE);      \
94                 cfg->exception_type = MONO_EXCEPTION_METHOD_ACCESS;     \
95                 cfg->exception_message = g_strdup_printf ("Method `%s' is inaccessible from method `%s'\n", cil_method_fname, method_fname);    \
96                 g_free (method_fname);  \
97                 g_free (cil_method_fname);      \
98                 goto exception_exit;    \
99         } while (0)
100 #define FIELD_ACCESS_FAILURE do {       \
101                 char *method_fname = mono_method_full_name (method, TRUE);      \
102                 char *field_fname = mono_field_full_name (field);       \
103                 cfg->exception_type = MONO_EXCEPTION_FIELD_ACCESS;      \
104                 cfg->exception_message = g_strdup_printf ("Field `%s' is inaccessible from method `%s'\n", field_fname, method_fname);  \
105                 g_free (method_fname);  \
106                 g_free (field_fname);   \
107                 goto exception_exit;    \
108         } while (0)
109 #define GENERIC_SHARING_FAILURE(opcode) do {            \
110                 if (cfg->generic_sharing_context) {     \
111             if (cfg->verbose_level > 1) \
112                             printf ("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__); \
113                         cfg->exception_type = MONO_EXCEPTION_GENERIC_SHARING_FAILED;    \
114                         goto exception_exit;    \
115                 }                       \
116         } while (0)
117 #define GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD(opcode) do {                        \
118                 if (method->klass->valuetype)   \
119                         GENERIC_SHARING_FAILURE ((opcode)); \
120         } while (0)
121 #define GET_RGCTX(rgctx, context_used) do {                                             \
122                 MonoInst *this = NULL;                                  \
123                 g_assert (context_used);                                \
124                 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD(*ip);       \
125                 if (!(method->flags & METHOD_ATTRIBUTE_STATIC) &&       \
126                                 !((context_used) & MONO_GENERIC_CONTEXT_USED_METHOD)) \
127                         NEW_ARGLOAD (cfg, this, 0);                     \
128                 (rgctx) = get_runtime_generic_context (cfg, method, (context_used), this, ip); \
129         } while (0)
130
131
132 #define MONO_CHECK_THIS(ins) (mono_method_signature (cfg->method)->hasthis && (ins)->ssa_op == MONO_SSA_LOAD && (ins)->inst_left->inst_c0 == 0)
133
134 static void setup_stat_profiler (void);
135 gboolean  mono_arch_print_tree(MonoInst *tree, int arity);
136 static gpointer mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt);
137 static gpointer mono_jit_compile_method (MonoMethod *method);
138 inline static int mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip);
139
140 static void handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, 
141                           const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native, gboolean write_barrier);
142
143 static void dec_foreach (MonoInst *tree, MonoCompile *cfg);
144
145 static int mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
146                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
147                    guint inline_offset, gboolean is_virtual_call);
148
149 #ifdef MONO_ARCH_SOFT_FLOAT
150 static void
151 handle_store_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, MonoInst *val, const unsigned char *ip);
152 #endif
153
154 /* helper methods signature */
155 static MonoMethodSignature *helper_sig_class_init_trampoline = NULL;
156 static MonoMethodSignature *helper_sig_generic_class_init_trampoline = NULL;
157 static MonoMethodSignature *helper_sig_rgctx_lazy_fetch_trampoline = NULL;
158 static MonoMethodSignature *helper_sig_domain_get = NULL;
159
160 static guint32 default_opt = 0;
161 static gboolean default_opt_set = FALSE;
162
163 guint32 mono_jit_tls_id = -1;
164
165 #ifdef HAVE_KW_THREAD
166 static __thread gpointer mono_jit_tls MONO_TLS_FAST;
167 #endif
168
169 MonoTraceSpec *mono_jit_trace_calls = NULL;
170 gboolean mono_break_on_exc = FALSE;
171 #ifndef DISABLE_AOT
172 gboolean mono_compile_aot = FALSE;
173 #endif
174 /* If this is set, no code is generated dynamically, everything is taken from AOT files */
175 gboolean mono_aot_only = FALSE;
176 /* Whenever to use IMT */
177 #ifdef MONO_ARCH_HAVE_IMT
178 gboolean mono_use_imt = TRUE;
179 #else
180 gboolean mono_use_imt = FALSE;
181 #endif
182 MonoMethodDesc *mono_inject_async_exc_method = NULL;
183 int mono_inject_async_exc_pos;
184 MonoMethodDesc *mono_break_at_bb_method = NULL;
185 int mono_break_at_bb_bb_num;
186
187 static int mini_verbose = 0;
188
189 #define mono_jit_lock() EnterCriticalSection (&jit_mutex)
190 #define mono_jit_unlock() LeaveCriticalSection (&jit_mutex)
191 static CRITICAL_SECTION jit_mutex;
192
193 static GHashTable *rgctx_lazy_fetch_trampoline_hash = NULL;
194
195 static MonoCodeManager *global_codeman = NULL;
196
197 static GHashTable *jit_icall_name_hash = NULL;
198
199 static MonoDebugOptions debug_options;
200
201 #ifdef VALGRIND_JIT_REGISTER_MAP
202 static int valgrind_register = 0;
203 #endif
204
205 /*
206  * Table written to by the debugger with a 1-based index into the
207  * mono_breakpoint_info table, which contains changes made to
208  * the JIT instructions by the debugger.
209  */
210 gssize
211 mono_breakpoint_info_index [MONO_BREAKPOINT_ARRAY_SIZE];
212
213 /* Whenever to check for pending exceptions in managed-to-native wrappers */
214 gboolean check_for_pending_exc = TRUE;
215
216 gboolean
217 mono_running_on_valgrind (void)
218 {
219 #ifdef HAVE_VALGRIND_MEMCHECK_H
220                 if (RUNNING_ON_VALGRIND){
221 #ifdef VALGRIND_JIT_REGISTER_MAP
222                         valgrind_register = TRUE;
223 #endif
224                         return TRUE;
225                 } else
226                         return FALSE;
227 #else
228                 return FALSE;
229 #endif
230 }
231
232 typedef struct {
233         void *ip;
234         MonoMethod *method;
235 } FindTrampUserData;
236
237 static void
238 find_tramp (gpointer key, gpointer value, gpointer user_data)
239 {
240         FindTrampUserData *ud = (FindTrampUserData*)user_data;
241
242         if (value == ud->ip)
243                 ud->method = (MonoMethod*)key;
244 }
245
246 /* debug function */
247 G_GNUC_UNUSED static char*
248 get_method_from_ip (void *ip)
249 {
250         MonoJitInfo *ji;
251         char *method;
252         char *res;
253         MonoDomain *domain = mono_domain_get ();
254         MonoDebugSourceLocation *location;
255         FindTrampUserData user_data;
256         
257         ji = mono_jit_info_table_find (domain, ip);
258         if (!ji) {
259                 user_data.ip = ip;
260                 user_data.method = NULL;
261                 mono_domain_lock (domain);
262                 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
263                 mono_domain_unlock (domain);
264                 if (user_data.method) {
265                         char *mname = mono_method_full_name (user_data.method, TRUE);
266                         res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
267                         g_free (mname);
268                         return res;
269                 }
270                 else
271                         return NULL;
272         }
273         method = mono_method_full_name (ji->method, TRUE);
274         /* FIXME: unused ? */
275         location = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
276
277         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);
278
279         mono_debug_free_source_location (location);
280         g_free (method);
281
282         return res;
283 }
284
285 /** 
286  * mono_pmip:
287  * @ip: an instruction pointer address
288  *
289  * This method is used from a debugger to get the name of the
290  * method at address @ip.   This routine is typically invoked from
291  * a debugger like this:
292  *
293  * (gdb) print mono_pmip ($pc)
294  *
295  * Returns: the name of the method at address @ip.
296  */
297 G_GNUC_UNUSED char *
298 mono_pmip (void *ip)
299 {
300         return get_method_from_ip (ip);
301 }
302
303 /** 
304  * mono_print_method_from_ip
305  * @ip: an instruction pointer address
306  *
307  * This method is used from a debugger to get the name of the
308  * method at address @ip.
309  *
310  * This prints the name of the method at address @ip in the standard
311  * output.  Unlike mono_pmip which returns a string, this routine
312  * prints the value on the standard output. 
313  */
314 void
315 mono_print_method_from_ip (void *ip)
316 {
317         MonoJitInfo *ji;
318         char *method;
319         MonoDebugSourceLocation *source;
320         MonoDomain *domain = mono_domain_get ();
321         FindTrampUserData user_data;
322         
323         ji = mono_jit_info_table_find (domain, ip);
324         if (!ji) {
325                 user_data.ip = ip;
326                 user_data.method = NULL;
327                 mono_domain_lock (domain);
328                 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
329                 mono_domain_unlock (domain);
330                 if (user_data.method) {
331                         char *mname = mono_method_full_name (user_data.method, TRUE);
332                         printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
333                         g_free (mname);
334                 }
335                 else
336                         g_print ("No method at %p\n", ip);
337                 return;
338         }
339         method = mono_method_full_name (ji->method, TRUE);
340         source = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
341
342         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);
343
344         if (source)
345                 g_print ("%s:%d\n", source->source_file, source->row);
346
347         mono_debug_free_source_location (source);
348         g_free (method);
349 }
350         
351 /* 
352  * mono_method_same_domain:
353  *
354  * Determine whenever two compiled methods are in the same domain, thus
355  * the address of the callee can be embedded in the caller.
356  */
357 gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
358 {
359         if (!caller || !callee)
360                 return FALSE;
361
362         /*
363          * If the call was made from domain-neutral to domain-specific 
364          * code, we can't patch the call site.
365          */
366         if (caller->domain_neutral && !callee->domain_neutral)
367                 return FALSE;
368
369         if ((caller->method->klass == mono_defaults.appdomain_class) &&
370                 (strstr (caller->method->name, "InvokeInDomain"))) {
371                  /* The InvokeInDomain methods change the current appdomain */
372                 return FALSE;
373         }
374
375         return TRUE;
376 }
377
378 /*
379  * mono_global_codeman_reserve:
380  *
381  *  Allocate code memory from the global code manager.
382  */
383 void *mono_global_codeman_reserve (int size)
384 {
385         void *ptr;
386
387         if (mono_aot_only)
388                 g_error ("Attempting to allocate from the global code manager while running with --aot-only.\n");
389
390         if (!global_codeman) {
391                 /* This can happen during startup */
392                 global_codeman = mono_code_manager_new ();
393                 return mono_code_manager_reserve (global_codeman, size);
394         }
395         else {
396                 mono_jit_lock ();
397                 ptr = mono_code_manager_reserve (global_codeman, size);
398                 mono_jit_unlock ();
399                 return ptr;
400         }
401 }
402
403 MonoJumpInfoToken *
404 mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
405 {
406         MonoJumpInfoToken *res = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
407         res->image = image;
408         res->token = token;
409
410         return res;
411 }
412
413 #define MONO_INIT_VARINFO(vi,id) do { \
414         (vi)->range.first_use.pos.bid = 0xffff; \
415         (vi)->reg = -1; \
416         (vi)->idx = (id); \
417 } while (0)
418
419 //#define UNVERIFIED do { G_BREAKPOINT (); goto unverified; } while (0)
420 #define UNVERIFIED do { if (debug_options.break_on_unverified) G_BREAKPOINT (); else goto unverified; } while (0)
421
422 /*
423  * Basic blocks have two numeric identifiers:
424  * dfn: Depth First Number
425  * block_num: unique ID assigned at bblock creation
426  */
427 #define NEW_BBLOCK(cfg,new_bb) do {     \
428                 new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock)); \
429                 MONO_INST_LIST_INIT (&new_bb->ins_list); \
430         } while (0)
431
432 #define ADD_BBLOCK(cfg,b) do {  \
433                 cfg->cil_offset_to_bb [(b)->cil_code - cfg->cil_start] = (b);   \
434                 (b)->block_num = cfg->num_bblocks++;    \
435                 (b)->real_offset = real_offset; \
436         } while (0)
437
438 #define GET_BBLOCK(cfg,tblock,ip) do {  \
439                 (tblock) = cfg->cil_offset_to_bb [(ip) - cfg->cil_start]; \
440                 if (!(tblock)) {        \
441                         if ((ip) >= end || (ip) < header->code) UNVERIFIED; \
442                         NEW_BBLOCK (cfg, (tblock));     \
443                         (tblock)->cil_code = (ip);      \
444                         ADD_BBLOCK (cfg, (tblock));     \
445                 } \
446         } while (0)
447
448 #define CHECK_BBLOCK(target,ip,tblock) do {     \
449                 if ((target) < (ip) && \
450                                 MONO_INST_LIST_EMPTY (&(tblock)->ins_list)) { \
451                         bb_recheck = g_list_prepend (bb_recheck, (tblock)); \
452                         if (cfg->verbose_level > 2) \
453                                 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)); \
454                 } \
455         } while (0)
456
457 #define NEW_ICONST(cfg,dest,val) do {   \
458                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
459                 (dest)->opcode = OP_ICONST;     \
460                 (dest)->inst_c0 = (val);        \
461                 (dest)->type = STACK_I4;        \
462         } while (0)
463
464 #define NEW_PCONST(cfg,dest,val) do {   \
465                 MONO_INST_NEW ((cfg), (dest), OP_PCONST);       \
466                 (dest)->inst_p0 = (val);        \
467                 (dest)->type = STACK_PTR;       \
468         } while (0)
469
470
471 #ifdef MONO_ARCH_NEED_GOT_VAR
472
473 #define NEW_PATCH_INFO(cfg,dest,el1,el2) do {   \
474                 MONO_INST_NEW ((cfg), (dest), OP_PATCH_INFO);   \
475                 (dest)->inst_left = (gpointer)(el1);    \
476                 (dest)->inst_right = (gpointer)(el2);   \
477         } while (0)
478
479 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do {                     \
480                 MONO_INST_NEW ((cfg), (dest), OP_NOP); \
481                 (dest)->opcode = cfg->compile_aot ? OP_GOT_ENTRY : OP_PCONST; \
482                 if (cfg->compile_aot) {                                 \
483                         MonoInst *group, *got_var, *got_loc;            \
484                         got_loc = mono_get_got_var (cfg);               \
485                         NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0); \
486                         NEW_PATCH_INFO ((cfg), group, cons, patch_type); \
487                         (dest)->inst_p0 = got_var;                      \
488                         (dest)->inst_p1 = group;                        \
489                 } else {                                                \
490                         (dest)->inst_p0 = (cons);                       \
491                         (dest)->inst_i1 = (gpointer)(patch_type);       \
492                 }                                                       \
493                 (dest)->type = STACK_PTR;                               \
494         } while (0)
495
496 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type,stack_class) do { \
497                 MonoInst *group, *got_var, *got_loc;                    \
498                 MONO_INST_NEW ((cfg), (dest), OP_GOT_ENTRY); \
499                 got_loc = mono_get_got_var (cfg);                       \
500                 NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0);        \
501                 NEW_PATCH_INFO ((cfg), group, NULL, patch_type);        \
502                 group->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token)); \
503                 (dest)->inst_p0 = got_var;                              \
504                 (dest)->inst_p1 = group;                                \
505                 (dest)->type = (stack_type);                    \
506         (dest)->klass = (stack_class);          \
507         } while (0)
508
509 #else
510
511 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do {    \
512                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
513                 (dest)->opcode = cfg->compile_aot ? OP_AOTCONST : OP_PCONST;    \
514                 (dest)->inst_p0 = (cons);       \
515                 (dest)->inst_i1 = (gpointer)(patch_type); \
516                 (dest)->type = STACK_PTR;       \
517     } while (0)
518
519 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type,stack_class) do { \
520                 MONO_INST_NEW ((cfg), (dest), OP_AOTCONST);     \
521                 (dest)->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token));  \
522                 (dest)->inst_p1 = (gpointer)(patch_type); \
523                 (dest)->type = (stack_type);    \
524         (dest)->klass = (stack_class);          \
525     } while (0)
526
527 #endif
528
529 #define NEW_CLASSCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_CLASS, (val))
530
531 #define NEW_IMAGECONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_IMAGE, (val))
532
533 #define NEW_FIELDCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_FIELD, (val))
534
535 #define NEW_METHODCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_METHODCONST, (val))
536
537 #define NEW_VTABLECONST(cfg,dest,vtable) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_VTABLE, cfg->compile_aot ? (gpointer)((vtable)->klass) : (vtable))
538
539 #define NEW_SFLDACONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_SFLDA, (val))
540
541 #define NEW_LDSTRCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDSTR, (image), (token), STACK_OBJ, mono_defaults.string_class)
542
543 #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)
544
545 #define NEW_LDTOKENCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDTOKEN, (image), (token), STACK_PTR, NULL)
546
547 #define NEW_DECLSECCONST(cfg,dest,image,entry) do { \
548                 if (cfg->compile_aot) { \
549                         NEW_AOTCONST_TOKEN (cfg, dest, MONO_PATCH_INFO_DECLSEC, image, (entry).index, STACK_OBJ, NULL); \
550                 } else { \
551                         NEW_PCONST (cfg, args [0], (entry).blob); \
552                 } \
553         } while (0)
554
555 #define NEW_DOMAINCONST(cfg,dest) do { \
556                 if (cfg->opt & MONO_OPT_SHARED) { \
557                         /* avoid depending on undefined C behavior in sequence points */ \
558                         MonoInst* __domain_var = mono_get_domainvar (cfg); \
559                         NEW_TEMPLOAD (cfg, dest, __domain_var->inst_c0); \
560                 } else { \
561                         NEW_PCONST (cfg, dest, (cfg)->domain); \
562                 } \
563         } while (0)
564
565 #define GET_VARINFO_INST(cfg,num) ((cfg)->varinfo [(num)]->inst)
566
567 #define NEW_ARGLOAD(cfg,dest,num) do {  \
568                 if (arg_array [(num)]->opcode == OP_ICONST) (dest) = arg_array [(num)]; else { \
569                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
570                 (dest)->ssa_op = MONO_SSA_LOAD; \
571                 (dest)->inst_i0 = arg_array [(num)];    \
572                 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
573                 type_to_eval_stack_type ((cfg), param_types [(num)], (dest));   \
574                 (dest)->klass = (dest)->inst_i0->klass; \
575         }} while (0)
576
577 #define NEW_LOCLOAD(cfg,dest,num) do {  \
578                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
579                 (dest)->ssa_op = MONO_SSA_LOAD; \
580                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
581                 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
582                 type_to_eval_stack_type ((cfg), header->locals [(num)], (dest));        \
583                 (dest)->klass = (dest)->inst_i0->klass; \
584         } while (0)
585
586 #define NEW_LOCLOADA(cfg,dest,num) do { \
587                 MONO_INST_NEW ((cfg), (dest), OP_LDADDR);       \
588                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
589                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
590                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
591                 (dest)->type = STACK_MP;        \
592                 (dest)->klass = (dest)->inst_i0->klass; \
593         if (!MONO_TYPE_ISSTRUCT (header->locals [(num)])) \
594            (cfg)->disable_ssa = TRUE; \
595         } while (0)
596
597 #define NEW_RETLOADA(cfg,dest) do {     \
598         if (cfg->vret_addr) { \
599                     MONO_INST_NEW ((cfg), (dest), OP_NOP);      \
600                     (dest)->ssa_op = MONO_SSA_LOAD;     \
601                     (dest)->inst_i0 = cfg->vret_addr; \
602                     (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
603             (dest)->type = STACK_MP; \
604                     (dest)->klass = (dest)->inst_i0->klass;     \
605         } else { \
606                         MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
607                     (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;    \
608                     (dest)->inst_i0 = (cfg)->ret;       \
609                     (dest)->inst_i0->flags |= MONO_INST_INDIRECT;       \
610                     (dest)->opcode = cfg->ret_var_is_local ? OP_LDADDR : CEE_LDIND_I;   \
611                     (dest)->type = STACK_MP;    \
612                     (dest)->klass = (dest)->inst_i0->klass;     \
613             (cfg)->disable_ssa = TRUE; \
614         } \
615         } while (0)
616
617 #define NEW_ARGLOADA(cfg,dest,num) do { \
618                 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
619                 MONO_INST_NEW ((cfg), (dest), OP_LDADDR);       \
620                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
621                 (dest)->inst_i0 = arg_array [(num)];    \
622                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
623                 (dest)->type = STACK_MP;        \
624                 (dest)->klass = (dest)->inst_i0->klass; \
625                 (cfg)->disable_ssa = TRUE; \
626         } while (0)
627
628 #define NEW_TEMPLOAD(cfg,dest,num) do { \
629                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
630                 (dest)->ssa_op = MONO_SSA_LOAD; \
631                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
632                 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
633                 type_to_eval_stack_type ((cfg), (dest)->inst_i0->inst_vtype, (dest));   \
634                 (dest)->klass = (dest)->inst_i0->klass; \
635         } while (0)
636
637 #define NEW_TEMPLOADA(cfg,dest,num) do {        \
638                 MONO_INST_NEW ((cfg), (dest), OP_LDADDR);       \
639                 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN;        \
640                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
641                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
642                 (dest)->type = STACK_MP;        \
643                 (dest)->klass = (dest)->inst_i0->klass; \
644         if (!MONO_TYPE_ISSTRUCT (cfg->varinfo [(num)]->inst_vtype)) \
645            (cfg)->disable_ssa = TRUE; \
646         } while (0)
647
648 #define NEW_INDLOAD(cfg,dest,addr,vtype) do {   \
649                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
650                 (dest)->inst_left = addr;       \
651                 (dest)->opcode = mini_type_to_ldind ((cfg), vtype);     \
652                 type_to_eval_stack_type ((cfg), vtype, (dest)); \
653                 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/     \
654         } while (0)
655
656 #define NEW_INDSTORE(cfg,dest,addr,value,vtype) do {    \
657                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
658                 (dest)->inst_i0 = addr; \
659                 (dest)->opcode = mini_type_to_stind ((cfg), vtype);     \
660                 (dest)->inst_i1 = (value);      \
661                 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/     \
662         } while (0)
663
664 #define NEW_TEMPSTORE(cfg,dest,num,inst) do {   \
665                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
666                 (dest)->ssa_op = MONO_SSA_STORE;        \
667                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
668                 (dest)->opcode = mini_type_to_stind ((cfg), (dest)->inst_i0->inst_vtype); \
669                 (dest)->inst_i1 = (inst);       \
670                 (dest)->klass = (dest)->inst_i0->klass; \
671         } while (0)
672
673 #define NEW_LOCSTORE(cfg,dest,num,inst) do {    \
674                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
675                 (dest)->opcode = mini_type_to_stind ((cfg), header->locals [(num)]); \
676                 (dest)->ssa_op = MONO_SSA_STORE;        \
677                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
678                 (dest)->inst_i1 = (inst);       \
679                 (dest)->klass = (dest)->inst_i0->klass; \
680         } while (0)
681
682 #define NEW_ARGSTORE(cfg,dest,num,inst) do {    \
683                 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
684                 MONO_INST_NEW ((cfg), (dest), OP_NOP);  \
685                 (dest)->opcode = mini_type_to_stind ((cfg), param_types [(num)]); \
686                 (dest)->ssa_op = MONO_SSA_STORE;        \
687                 (dest)->inst_i0 = arg_array [(num)];    \
688                 (dest)->inst_i1 = (inst);       \
689                 (dest)->klass = (dest)->inst_i0->klass; \
690         } while (0)
691
692 #define NEW_MEMCPY(cfg,dest,dst,src,memcpy_size,memcpy_align) do { \
693                 MONO_INST_NEW (cfg, dest, OP_MEMCPY); \
694         (dest)->inst_left = (dst); \
695                 (dest)->inst_right = (src); \
696         (dest)->backend.memcpy_args = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoMemcpyArgs)); \
697                 (dest)->backend.memcpy_args->size = (memcpy_size); \
698                 (dest)->backend.memcpy_args->align = (memcpy_align); \
699     } while (0)
700
701 #define NEW_MEMSET(cfg,dest,dst,imm,memcpy_size,memcpy_align) do { \
702                 MONO_INST_NEW (cfg, dest, OP_MEMSET); \
703         (dest)->inst_left = (dst); \
704                 (dest)->inst_imm = (imm); \
705         (dest)->backend.memcpy_args = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoMemcpyArgs)); \
706                 (dest)->backend.memcpy_args->size = (memcpy_size); \
707                 (dest)->backend.memcpy_args->align = (memcpy_align); \
708     } while (0)
709
710 #define NEW_DUMMY_USE(cfg,dest,load) do { \
711                 MONO_INST_NEW ((cfg), (dest), OP_DUMMY_USE);    \
712                 (dest)->inst_left = (load); \
713     } while (0)
714
715 #define NEW_DUMMY_STORE(cfg,dest,num) do { \
716                 MONO_INST_NEW ((cfg), (dest), OP_DUMMY_STORE);  \
717                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
718                 (dest)->klass = (dest)->inst_i0->klass; \
719         } while (0)
720
721 #define ADD_BINOP(op) do {      \
722                 MONO_INST_NEW (cfg, ins, (op)); \
723                 sp -= 2;        \
724                 ins->inst_i0 = sp [0];  \
725                 ins->inst_i1 = sp [1];  \
726                 *sp++ = ins;    \
727                 type_from_op (ins);     \
728                 CHECK_TYPE (ins);       \
729                 /* Have to insert a widening op */               \
730                 /* FIXME: Need to add many more cases */ \
731                 if (ins->inst_i0->type == STACK_PTR && ins->inst_i1->type == STACK_I4) { \
732                         MonoInst *widen;  \
733                         MONO_INST_NEW (cfg, widen, CEE_CONV_I); \
734             widen->inst_i0 = ins->inst_i1; \
735                         ins->inst_i1 = widen; \
736                 } \
737         } while (0)
738
739 #define ADD_UNOP(op) do {       \
740                 MONO_INST_NEW (cfg, ins, (op)); \
741                 sp--;   \
742                 ins->inst_i0 = sp [0];  \
743                 *sp++ = ins;    \
744                 type_from_op (ins);     \
745                 CHECK_TYPE (ins);       \
746         } while (0)
747
748 #define ADD_BINCOND(next_block) do {    \
749                 MonoInst *cmp;  \
750                 sp -= 2;                \
751                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
752                 cmp->inst_i0 = sp [0];  \
753                 cmp->inst_i1 = sp [1];  \
754                 cmp->cil_code = ins->cil_code;  \
755                 type_from_op (cmp);     \
756                 CHECK_TYPE (cmp);       \
757                 ins->inst_i0 = cmp;     \
758                 MONO_ADD_INS (bblock, ins);     \
759                 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);      \
760                 GET_BBLOCK (cfg, tblock, target);               \
761                 link_bblock (cfg, bblock, tblock);      \
762                 ins->inst_true_bb = tblock;     \
763                 CHECK_BBLOCK (target, ip, tblock);      \
764                 if ((next_block)) {     \
765                         link_bblock (cfg, bblock, (next_block));        \
766                         ins->inst_false_bb = (next_block);      \
767                         start_new_bblock = 1;   \
768                 } else {        \
769                         GET_BBLOCK (cfg, tblock, ip);           \
770                         link_bblock (cfg, bblock, tblock);      \
771                         ins->inst_false_bb = tblock;    \
772                         start_new_bblock = 2;   \
773                 }       \
774         } while (0)
775
776 /* FIXME: handle float, long ... */
777 #define ADD_UNCOND(istrue) do { \
778                 MonoInst *cmp;  \
779                 sp--;           \
780                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
781                 cmp->inst_i0 = sp [0];  \
782                 switch (cmp->inst_i0->type) { \
783                 case STACK_I8: \
784                         cmp->inst_i1 = zero_int64; break; \
785                 case STACK_R8: \
786                         cmp->inst_i1 = zero_r8; break; \
787                 case STACK_PTR: \
788                 case STACK_MP: \
789                         cmp->inst_i1 = zero_ptr; break; \
790                 case STACK_OBJ: \
791                         cmp->inst_i1 = zero_obj; break; \
792                 default: \
793                         cmp->inst_i1 = zero_int32;  \
794                 }  \
795                 cmp->cil_code = ins->cil_code;  \
796                 type_from_op (cmp);     \
797                 CHECK_TYPE (cmp);       \
798                 ins->inst_i0 = cmp;     \
799                 ins->opcode = (istrue)? CEE_BNE_UN: CEE_BEQ;    \
800                 MONO_ADD_INS (bblock, ins);     \
801                 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);      \
802                 GET_BBLOCK (cfg, tblock, target);               \
803                 link_bblock (cfg, bblock, tblock);      \
804                 ins->inst_true_bb = tblock;     \
805                 CHECK_BBLOCK (target, ip, tblock);      \
806                 GET_BBLOCK (cfg, tblock, ip);           \
807                 link_bblock (cfg, bblock, tblock);      \
808                 ins->inst_false_bb = tblock;    \
809                 start_new_bblock = 2;   \
810         } while (0)
811
812 #define NEW_LDELEMA(cfg,dest,sp,k) do { \
813                 MONO_INST_NEW ((cfg), (dest), CEE_LDELEMA);     \
814                 (dest)->inst_left = (sp) [0];   \
815                 (dest)->inst_right = (sp) [1];  \
816                 (dest)->type = STACK_MP;        \
817                 (dest)->klass = (k);    \
818                 (cfg)->flags |= MONO_CFG_HAS_LDELEMA; \
819         } while (0)
820
821 #define NEW_GROUP(cfg,dest,el1,el2) do {        \
822                 MONO_INST_NEW ((cfg), (dest), OP_GROUP);        \
823                 (dest)->inst_left = (el1);      \
824                 (dest)->inst_right = (el2);     \
825         } while (0)
826
827 #if 0
828 static gint
829 compare_bblock (gconstpointer a, gconstpointer b)
830 {
831         const MonoBasicBlock *b1 = a;
832         const MonoBasicBlock *b2 = b;
833
834         return b2->cil_code - b1->cil_code;
835 }
836 #endif
837
838 /* *
839  * link_bblock: Links two basic blocks
840  *
841  * links two basic blocks in the control flow graph, the 'from'
842  * argument is the starting block and the 'to' argument is the block
843  * the control flow ends to after 'from'.
844  */
845 static void
846 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
847 {
848         MonoBasicBlock **newa;
849         int i, found;
850
851 #if 0
852         if (from->cil_code) {
853                 if (to->cil_code)
854                         g_print ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
855                 else
856                         g_print ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
857         } else {
858                 if (to->cil_code)
859                         g_print ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
860                 else
861                         g_print ("edge from entry to exit\n");
862         }
863 #endif
864         found = FALSE;
865         for (i = 0; i < from->out_count; ++i) {
866                 if (to == from->out_bb [i]) {
867                         found = TRUE;
868                         break;
869                 }
870         }
871         if (!found) {
872                 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
873                 for (i = 0; i < from->out_count; ++i) {
874                         newa [i] = from->out_bb [i];
875                 }
876                 newa [i] = to;
877                 from->out_count++;
878                 from->out_bb = newa;
879         }
880
881         found = FALSE;
882         for (i = 0; i < to->in_count; ++i) {
883                 if (from == to->in_bb [i]) {
884                         found = TRUE;
885                         break;
886                 }
887         }
888         if (!found) {
889                 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
890                 for (i = 0; i < to->in_count; ++i) {
891                         newa [i] = to->in_bb [i];
892                 }
893                 newa [i] = from;
894                 to->in_count++;
895                 to->in_bb = newa;
896         }
897 }
898
899 /**
900  * mono_unlink_bblock:
901  *
902  *   Unlink two basic blocks.
903  */
904 static void
905 mono_unlink_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
906 {
907         int i, pos;
908         gboolean found;
909
910         found = FALSE;
911         for (i = 0; i < from->out_count; ++i) {
912                 if (to == from->out_bb [i]) {
913                         found = TRUE;
914                         break;
915                 }
916         }
917         if (found) {
918                 pos = 0;
919                 for (i = 0; i < from->out_count; ++i) {
920                         if (from->out_bb [i] != to)
921                                 from->out_bb [pos ++] = from->out_bb [i];
922                 }
923                 g_assert (pos == from->out_count - 1);
924                 from->out_count--;
925         }
926
927         found = FALSE;
928         for (i = 0; i < to->in_count; ++i) {
929                 if (from == to->in_bb [i]) {
930                         found = TRUE;
931                         break;
932                 }
933         }
934         if (found) {
935                 pos = 0;
936                 for (i = 0; i < to->in_count; ++i) {
937                         if (to->in_bb [i] != from)
938                                 to->in_bb [pos ++] = to->in_bb [i];
939                 }
940                 g_assert (pos == to->in_count - 1);
941                 to->in_count--;
942         }
943 }
944
945 /**
946  * mono_find_block_region:
947  *
948  *   We mark each basic block with a region ID. We use that to avoid BB
949  *   optimizations when blocks are in different regions.
950  *
951  * Returns:
952  *   A region token that encodes where this region is, and information
953  *   about the clause owner for this block.
954  *
955  *   The region encodes the try/catch/filter clause that owns this block
956  *   as well as the type.  -1 is a special value that represents a block
957  *   that is in none of try/catch/filter.
958  */
959 static int
960 mono_find_block_region (MonoCompile *cfg, int offset)
961 {
962         MonoMethod *method = cfg->method;
963         MonoMethodHeader *header = mono_method_get_header (method);
964         MonoExceptionClause *clause;
965         int i;
966
967         /* first search for handlers and filters */
968         for (i = 0; i < header->num_clauses; ++i) {
969                 clause = &header->clauses [i];
970                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
971                     (offset < (clause->handler_offset)))
972                         return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
973                            
974                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
975                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
976                                 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
977                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
978                                 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
979                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
980                                 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
981                 }
982         }
983
984         /* search the try blocks */
985         for (i = 0; i < header->num_clauses; ++i) {
986                 clause = &header->clauses [i];
987                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
988                         return ((i + 1) << 8) | clause->flags;
989         }
990
991         return -1;
992 }
993
994 static GList*
995 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
996 {
997         MonoMethod *method = cfg->method;
998         MonoMethodHeader *header = mono_method_get_header (method);
999         MonoExceptionClause *clause;
1000         MonoBasicBlock *handler;
1001         int i;
1002         GList *res = NULL;
1003
1004         for (i = 0; i < header->num_clauses; ++i) {
1005                 clause = &header->clauses [i];
1006                 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) && 
1007                     (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
1008                         if (clause->flags == type) {
1009                                 handler = cfg->cil_offset_to_bb [clause->handler_offset];
1010                                 g_assert (handler);
1011                                 res = g_list_append (res, handler);
1012                         }
1013                 }
1014         }
1015         return res;
1016 }
1017
1018 MonoInst *
1019 mono_find_spvar_for_region (MonoCompile *cfg, int region)
1020 {
1021         return g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
1022 }
1023
1024 static void
1025 mono_create_spvar_for_region (MonoCompile *cfg, int region)
1026 {
1027         MonoInst *var;
1028
1029         var = g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
1030         if (var)
1031                 return;
1032
1033         var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1034         /* prevent it from being register allocated */
1035         var->flags |= MONO_INST_INDIRECT;
1036
1037         g_hash_table_insert (cfg->spvars, GINT_TO_POINTER (region), var);
1038 }
1039
1040 static MonoInst *
1041 mono_find_exvar_for_offset (MonoCompile *cfg, int offset)
1042 {
1043         return g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
1044 }
1045
1046 static MonoInst*
1047 mono_create_exvar_for_offset (MonoCompile *cfg, int offset)
1048 {
1049         MonoInst *var;
1050
1051         var = g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
1052         if (var)
1053                 return var;
1054
1055         var = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
1056         /* prevent it from being register allocated */
1057         var->flags |= MONO_INST_INDIRECT;
1058
1059         g_hash_table_insert (cfg->exvars, GINT_TO_POINTER (offset), var);
1060
1061         return var;
1062 }
1063
1064 static void
1065 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
1066 {
1067         int i;
1068
1069         array [*dfn] = start;
1070         /*g_print ("visit %d at %p (BB%ld)\n", *dfn, start->cil_code, start->block_num);*/
1071         for (i = 0; i < start->out_count; ++i) {
1072                 if (start->out_bb [i]->dfn)
1073                         continue;
1074                 (*dfn)++;
1075                 start->out_bb [i]->dfn = *dfn;
1076                 start->out_bb [i]->df_parent = start;
1077                 array [*dfn] = start->out_bb [i];
1078                 df_visit (start->out_bb [i], dfn, array);
1079         }
1080 }
1081
1082 static MonoBasicBlock*
1083 find_previous (MonoBasicBlock **bblocks, guint32 n_bblocks, MonoBasicBlock *start, const guchar *code)
1084 {
1085         MonoBasicBlock *best = start;
1086         int i;
1087
1088         for (i = 0; i < n_bblocks; ++i) {
1089                 if (bblocks [i]) {
1090                         MonoBasicBlock *bb = bblocks [i];
1091
1092                         if (bb->cil_code && bb->cil_code < code && bb->cil_code > best->cil_code)
1093                                 best = bb;
1094                 }
1095         }
1096
1097         return best;
1098 }
1099
1100 static void
1101 split_bblock (MonoCompile *cfg, MonoBasicBlock *first, MonoBasicBlock *second) {
1102         int i, j;
1103         MonoInst *inst;
1104         MonoBasicBlock *bb;
1105
1106         if (!MONO_INST_LIST_EMPTY (&second->ins_list))
1107                 return;
1108         
1109         /* 
1110          * FIXME: take into account all the details:
1111          * second may have been the target of more than one bblock
1112          */
1113         second->out_count = first->out_count;
1114         second->out_bb = first->out_bb;
1115
1116         for (i = 0; i < first->out_count; ++i) {
1117                 bb = first->out_bb [i];
1118                 for (j = 0; j < bb->in_count; ++j) {
1119                         if (bb->in_bb [j] == first)
1120                                 bb->in_bb [j] = second;
1121                 }
1122         }
1123
1124         first->out_count = 0;
1125         first->out_bb = NULL;
1126         link_bblock (cfg, first, second);
1127
1128         /*g_print ("start search at %p for %p\n", first->cil_code, second->cil_code);*/
1129         MONO_BB_FOR_EACH_INS (first, inst) {
1130                 MonoInst *inst_next;
1131
1132                 /*char *code = mono_disasm_code_one (NULL, cfg->method, inst->next->cil_code, NULL);
1133                 g_print ("found %p: %s", inst->next->cil_code, code);
1134                 g_free (code);*/
1135                 if (inst->cil_code >= second->cil_code)
1136                         continue;
1137
1138                 inst_next = mono_inst_list_next (&inst->node, &first->ins_list);
1139                 if (!inst_next)
1140                         break;
1141
1142                 if (inst_next->cil_code < second->cil_code)
1143                         continue;
1144                         
1145                 second->ins_list.next = inst->node.next;
1146                 second->ins_list.prev = first->ins_list.prev;
1147                 inst->node.next = &first->ins_list;
1148                 first->ins_list.prev = &inst->node;
1149
1150                 second->next_bb = first->next_bb;
1151                 first->next_bb = second;
1152                 return;
1153         }
1154         if (MONO_INST_LIST_EMPTY (&second->ins_list)) {
1155                 g_warning ("bblock split failed in %s::%s\n", cfg->method->klass->name, cfg->method->name);
1156                 //G_BREAKPOINT ();
1157         }
1158 }
1159
1160 static guint32
1161 reverse_branch_op (guint32 opcode)
1162 {
1163         static const int reverse_map [] = {
1164                 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
1165                 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
1166         };
1167         static const int reverse_fmap [] = {
1168                 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
1169                 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
1170         };
1171         static const int reverse_lmap [] = {
1172                 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
1173                 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
1174         };
1175         static const int reverse_imap [] = {
1176                 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
1177                 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
1178         };
1179                                 
1180         if (opcode >= CEE_BEQ && opcode <= CEE_BLT_UN) {
1181                 opcode = reverse_map [opcode - CEE_BEQ];
1182         } else if (opcode >= OP_FBEQ && opcode <= OP_FBLT_UN) {
1183                 opcode = reverse_fmap [opcode - OP_FBEQ];
1184         } else if (opcode >= OP_LBEQ && opcode <= OP_LBLT_UN) {
1185                 opcode = reverse_lmap [opcode - OP_LBEQ];
1186         } else if (opcode >= OP_IBEQ && opcode <= OP_IBLT_UN) {
1187                 opcode = reverse_imap [opcode - OP_IBEQ];
1188         } else
1189                 g_assert_not_reached ();
1190
1191         return opcode;
1192 }
1193
1194 #ifdef MONO_ARCH_SOFT_FLOAT
1195 static int
1196 condbr_to_fp_br (int opcode)
1197 {
1198         switch (opcode) {
1199         case CEE_BEQ: return OP_FBEQ;
1200         case CEE_BGE: return OP_FBGE;
1201         case CEE_BGT: return OP_FBGT;
1202         case CEE_BLE: return OP_FBLE;
1203         case CEE_BLT: return OP_FBLT;
1204         case CEE_BNE_UN: return OP_FBNE_UN;
1205         case CEE_BGE_UN: return OP_FBGE_UN;
1206         case CEE_BGT_UN: return OP_FBGT_UN;
1207         case CEE_BLE_UN: return OP_FBLE_UN;
1208         case CEE_BLT_UN: return OP_FBLT_UN;
1209         }
1210         g_assert_not_reached ();
1211         return 0;
1212 }
1213 #endif
1214
1215 /*
1216  * Returns the type used in the eval stack when @type is loaded.
1217  * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
1218  */
1219 static void
1220 type_to_eval_stack_type (MonoCompile *cfg, MonoType *type, MonoInst *inst)
1221 {
1222         MonoClass *klass;
1223
1224         inst->klass = klass = mono_class_from_mono_type (type);
1225         if (type->byref) {
1226                 inst->type = STACK_MP;
1227                 return;
1228         }
1229
1230 handle_enum:
1231         switch (type->type) {
1232         case MONO_TYPE_VOID:
1233                 inst->type = STACK_INV;
1234                 return;
1235         case MONO_TYPE_I1:
1236         case MONO_TYPE_U1:
1237         case MONO_TYPE_BOOLEAN:
1238         case MONO_TYPE_I2:
1239         case MONO_TYPE_U2:
1240         case MONO_TYPE_CHAR:
1241         case MONO_TYPE_I4:
1242         case MONO_TYPE_U4:
1243                 inst->type = STACK_I4;
1244                 return;
1245         case MONO_TYPE_I:
1246         case MONO_TYPE_U:
1247         case MONO_TYPE_PTR:
1248         case MONO_TYPE_FNPTR:
1249                 inst->type = STACK_PTR;
1250                 return;
1251         case MONO_TYPE_CLASS:
1252         case MONO_TYPE_STRING:
1253         case MONO_TYPE_OBJECT:
1254         case MONO_TYPE_SZARRAY:
1255         case MONO_TYPE_ARRAY:    
1256                 inst->type = STACK_OBJ;
1257                 return;
1258         case MONO_TYPE_I8:
1259         case MONO_TYPE_U8:
1260                 inst->type = STACK_I8;
1261                 return;
1262         case MONO_TYPE_R4:
1263         case MONO_TYPE_R8:
1264                 inst->type = STACK_R8;
1265                 return;
1266         case MONO_TYPE_VALUETYPE:
1267                 if (type->data.klass->enumtype) {
1268                         type = type->data.klass->enum_basetype;
1269                         goto handle_enum;
1270                 } else {
1271                         inst->klass = klass;
1272                         inst->type = STACK_VTYPE;
1273                         return;
1274                 }
1275         case MONO_TYPE_TYPEDBYREF:
1276                 inst->klass = mono_defaults.typed_reference_class;
1277                 inst->type = STACK_VTYPE;
1278                 return;
1279         case MONO_TYPE_GENERICINST:
1280                 type = &type->data.generic_class->container_class->byval_arg;
1281                 goto handle_enum;
1282         case MONO_TYPE_VAR :
1283         case MONO_TYPE_MVAR :
1284                 /* FIXME: all the arguments must be references for now,
1285                  * later look inside cfg and see if the arg num is
1286                  * really a reference
1287                  */
1288                 g_assert (cfg->generic_sharing_context);
1289                 inst->type = STACK_OBJ;
1290                 return;
1291         default:
1292                 g_error ("unknown type 0x%02x in eval stack type", type->type);
1293         }
1294 }
1295
1296 /*
1297  * The following tables are used to quickly validate the IL code in type_from_op ().
1298  */
1299 static const char
1300 bin_num_table [STACK_MAX] [STACK_MAX] = {
1301         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1302         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
1303         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1304         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
1305         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8,  STACK_INV, STACK_INV, STACK_INV},
1306         {STACK_INV, STACK_MP,  STACK_INV, STACK_MP,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
1307         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1308         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1309 };
1310
1311 static const char 
1312 neg_table [] = {
1313         STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV
1314 };
1315
1316 /* reduce the size of this table */
1317 static const char
1318 bin_int_table [STACK_MAX] [STACK_MAX] = {
1319         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1320         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1321         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1322         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1323         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1324         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1325         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1326         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1327 };
1328
1329 static const char
1330 bin_comp_table [STACK_MAX] [STACK_MAX] = {
1331 /*      Inv i  L  p  F  &  O  vt */
1332         {0},
1333         {0, 1, 0, 1, 0, 0, 0, 0}, /* i, int32 */
1334         {0, 0, 1, 0, 0, 0, 0, 0}, /* L, int64 */
1335         {0, 1, 0, 1, 0, 2, 4, 0}, /* p, ptr */
1336         {0, 0, 0, 0, 1, 0, 0, 0}, /* F, R8 */
1337         {0, 0, 0, 2, 0, 1, 0, 0}, /* &, managed pointer */
1338         {0, 0, 0, 4, 0, 0, 3, 0}, /* O, reference */
1339         {0, 0, 0, 0, 0, 0, 0, 0}, /* vt value type */
1340 };
1341
1342 /* reduce the size of this table */
1343 static const char
1344 shift_table [STACK_MAX] [STACK_MAX] = {
1345         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1346         {STACK_INV, STACK_I4,  STACK_INV, STACK_I4,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1347         {STACK_INV, STACK_I8,  STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1348         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1349         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1350         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1351         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1352         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1353 };
1354
1355 /*
1356  * Tables to map from the non-specific opcode to the matching
1357  * type-specific opcode.
1358  */
1359 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
1360 static const guint16
1361 binops_op_map [STACK_MAX] = {
1362         0, 0, OP_LADD-CEE_ADD, OP_PADD-CEE_ADD, OP_FADD-CEE_ADD, OP_PADD-CEE_ADD
1363 };
1364
1365 /* handles from CEE_NEG to CEE_CONV_U8 */
1366 static const guint16
1367 unops_op_map [STACK_MAX] = {
1368         0, 0, OP_LNEG-CEE_NEG, OP_PNEG-CEE_NEG, OP_FNEG-CEE_NEG, OP_PNEG-CEE_NEG
1369 };
1370
1371 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
1372 static const guint16
1373 ovfops_op_map [STACK_MAX] = {
1374         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
1375 };
1376
1377 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
1378 static const guint16
1379 ovf2ops_op_map [STACK_MAX] = {
1380         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
1381 };
1382
1383 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
1384 static const guint16
1385 ovf3ops_op_map [STACK_MAX] = {
1386         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
1387 };
1388
1389 /* handles from CEE_CEQ to CEE_CLT_UN */
1390 static const guint16
1391 ceqops_op_map [STACK_MAX] = {
1392         0, 0, OP_LCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, OP_FCEQ-OP_CEQ, OP_LCEQ-OP_CEQ
1393 };
1394
1395 /*
1396  * Sets ins->type (the type on the eval stack) according to the
1397  * type of the opcode and the arguments to it.
1398  * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
1399  *
1400  * FIXME: this function sets ins->type unconditionally in some cases, but
1401  * it should set it to invalid for some types (a conv.x on an object)
1402  */
1403 static void
1404 type_from_op (MonoInst *ins) {
1405         switch (ins->opcode) {
1406         /* binops */
1407         case CEE_ADD:
1408         case CEE_SUB:
1409         case CEE_MUL:
1410         case CEE_DIV:
1411         case CEE_REM:
1412                 /* FIXME: check unverifiable args for STACK_MP */
1413                 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1414                 ins->opcode += binops_op_map [ins->type];
1415                 return;
1416         case CEE_DIV_UN:
1417         case CEE_REM_UN:
1418         case CEE_AND:
1419         case CEE_OR:
1420         case CEE_XOR:
1421                 ins->type = bin_int_table [ins->inst_i0->type] [ins->inst_i1->type];
1422                 ins->opcode += binops_op_map [ins->type];
1423                 return;
1424         case CEE_SHL:
1425         case CEE_SHR:
1426         case CEE_SHR_UN:
1427                 ins->type = shift_table [ins->inst_i0->type] [ins->inst_i1->type];
1428                 ins->opcode += binops_op_map [ins->type];
1429                 return;
1430         case OP_COMPARE:
1431         case OP_LCOMPARE:
1432                 /* FIXME: handle some specifics with ins->next->type */
1433                 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1434                 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))))
1435                         ins->opcode = OP_LCOMPARE;
1436                 return;
1437         case OP_CEQ:
1438                 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1439                 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1440                 return;
1441                 
1442         case OP_CGT:
1443         case OP_CGT_UN:
1444         case OP_CLT:
1445         case OP_CLT_UN:
1446                 ins->type = (bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] & 1) ? STACK_I4: STACK_INV;
1447                 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1448                 return;
1449         /* unops */
1450         case CEE_NEG:
1451                 ins->type = neg_table [ins->inst_i0->type];
1452                 ins->opcode += unops_op_map [ins->type];
1453                 return;
1454         case CEE_NOT:
1455                 if (ins->inst_i0->type >= STACK_I4 && ins->inst_i0->type <= STACK_PTR)
1456                         ins->type = ins->inst_i0->type;
1457                 else
1458                         ins->type = STACK_INV;
1459                 ins->opcode += unops_op_map [ins->type];
1460                 return;
1461         case CEE_CONV_I1:
1462         case CEE_CONV_I2:
1463         case CEE_CONV_I4:
1464         case CEE_CONV_U4:
1465                 ins->type = STACK_I4;
1466                 ins->opcode += unops_op_map [ins->inst_i0->type];
1467                 return;
1468         case CEE_CONV_R_UN:
1469                 ins->type = STACK_R8;
1470                 switch (ins->inst_i0->type) {
1471                 case STACK_I4:
1472                 case STACK_PTR:
1473                         break;
1474                 case STACK_I8:
1475                         ins->opcode = OP_LCONV_TO_R_UN; 
1476                         break;
1477                 }
1478                 return;
1479         case CEE_CONV_OVF_I1:
1480         case CEE_CONV_OVF_U1:
1481         case CEE_CONV_OVF_I2:
1482         case CEE_CONV_OVF_U2:
1483         case CEE_CONV_OVF_I4:
1484         case CEE_CONV_OVF_U4:
1485                 ins->type = STACK_I4;
1486                 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1487                 return;
1488         case CEE_CONV_OVF_I_UN:
1489         case CEE_CONV_OVF_U_UN:
1490                 ins->type = STACK_PTR;
1491                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1492                 return;
1493         case CEE_CONV_OVF_I1_UN:
1494         case CEE_CONV_OVF_I2_UN:
1495         case CEE_CONV_OVF_I4_UN:
1496         case CEE_CONV_OVF_U1_UN:
1497         case CEE_CONV_OVF_U2_UN:
1498         case CEE_CONV_OVF_U4_UN:
1499                 ins->type = STACK_I4;
1500                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1501                 return;
1502         case CEE_CONV_U:
1503                 ins->type = STACK_PTR;
1504                 switch (ins->inst_i0->type) {
1505                 case STACK_I4:
1506                         break;
1507                 case STACK_PTR:
1508                 case STACK_MP:
1509 #if SIZEOF_VOID_P == 8
1510                         ins->opcode = OP_LCONV_TO_U;
1511 #endif
1512                         break;
1513                 case STACK_I8:
1514                         ins->opcode = OP_LCONV_TO_U;
1515                         break;
1516                 case STACK_R8:
1517                         ins->opcode = OP_FCONV_TO_U;
1518                         break;
1519                 }
1520                 return;
1521         case CEE_CONV_I8:
1522         case CEE_CONV_U8:
1523                 ins->type = STACK_I8;
1524                 ins->opcode += unops_op_map [ins->inst_i0->type];
1525                 return;
1526         case CEE_CONV_OVF_I8:
1527         case CEE_CONV_OVF_U8:
1528                 ins->type = STACK_I8;
1529                 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1530                 return;
1531         case CEE_CONV_OVF_U8_UN:
1532         case CEE_CONV_OVF_I8_UN:
1533                 ins->type = STACK_I8;
1534                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1535                 return;
1536         case CEE_CONV_R4:
1537         case CEE_CONV_R8:
1538                 ins->type = STACK_R8;
1539                 ins->opcode += unops_op_map [ins->inst_i0->type];
1540                 return;
1541         case OP_CKFINITE:
1542                 ins->type = STACK_R8;           
1543                 return;
1544         case CEE_CONV_U2:
1545         case CEE_CONV_U1:
1546                 ins->type = STACK_I4;
1547                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1548                 break;
1549         case CEE_CONV_I:
1550         case CEE_CONV_OVF_I:
1551         case CEE_CONV_OVF_U:
1552                 ins->type = STACK_PTR;
1553                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1554                 return;
1555         case CEE_ADD_OVF:
1556         case CEE_ADD_OVF_UN:
1557         case CEE_MUL_OVF:
1558         case CEE_MUL_OVF_UN:
1559         case CEE_SUB_OVF:
1560         case CEE_SUB_OVF_UN:
1561                 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1562                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1563                 if (ins->type == STACK_R8)
1564                         ins->type = STACK_INV;
1565                 return;
1566         default:
1567                 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1568                 break;
1569         }
1570 }
1571
1572 static const char 
1573 ldind_type [] = {
1574         STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_R8, STACK_OBJ
1575 };
1576
1577 /* map ldelem.x to the matching ldind.x opcode */
1578 static const guchar
1579 ldelem_to_ldind [] = {
1580         CEE_LDIND_I1,
1581         CEE_LDIND_U1,
1582         CEE_LDIND_I2,
1583         CEE_LDIND_U2,
1584         CEE_LDIND_I4,
1585         CEE_LDIND_U4,
1586         CEE_LDIND_I8,
1587         CEE_LDIND_I,
1588         CEE_LDIND_R4,
1589         CEE_LDIND_R8,
1590         CEE_LDIND_REF
1591 };
1592
1593 /* map stelem.x to the matching stind.x opcode */
1594 static const guchar
1595 stelem_to_stind [] = {
1596         CEE_STIND_I,
1597         CEE_STIND_I1,
1598         CEE_STIND_I2,
1599         CEE_STIND_I4,
1600         CEE_STIND_I8,
1601         CEE_STIND_R4,
1602         CEE_STIND_R8,
1603         CEE_STIND_REF
1604 };
1605
1606
1607 #ifdef MONO_ARCH_SOFT_FLOAT
1608 static void
1609 handle_store_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, MonoInst *val, const unsigned char *ip)
1610 {
1611         MonoInst *iargs [2];
1612         iargs [0] = val;
1613         iargs [1] = ptr;
1614
1615         mono_emit_jit_icall (cfg, bblock, mono_fstore_r4, iargs, ip);
1616 }
1617
1618 static int
1619 handle_load_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, const unsigned char *ip)
1620 {
1621         MonoInst *iargs [1];
1622         iargs [0] = ptr;
1623
1624         return mono_emit_jit_icall (cfg, bblock, mono_fload_r4, iargs, ip);
1625 }
1626
1627 #define LDLOC_SOFT_FLOAT(cfg,ins,idx,ip) do {\
1628                 if (header->locals [(idx)]->type == MONO_TYPE_R4 && !header->locals [(idx)]->byref) {   \
1629                         int temp;       \
1630                         NEW_LOCLOADA (cfg, (ins), (idx));       \
1631                         temp = handle_load_float (cfg, bblock, (ins), (ip));    \
1632                         NEW_TEMPLOAD (cfg, (ins), temp);        \
1633                 }       \
1634         } while (0)
1635 #define STLOC_SOFT_FLOAT(cfg,ins,idx,ip) do {\
1636                 if (header->locals [(idx)]->type == MONO_TYPE_R4 && !header->locals [(idx)]->byref) {   \
1637                         NEW_LOCLOADA (cfg, (ins), (idx));       \
1638                         handle_store_float (cfg, bblock, (ins), *sp, (ip));     \
1639                         MONO_INST_NEW (cfg, (ins), OP_NOP);     \
1640                 }       \
1641         } while (0)
1642 #define LDARG_SOFT_FLOAT(cfg,ins,idx,ip) do {\
1643                 if (param_types [(idx)]->type == MONO_TYPE_R4 && !param_types [(idx)]->byref) { \
1644                         int temp;       \
1645                         NEW_ARGLOADA (cfg, (ins), (idx));       \
1646                         temp = handle_load_float (cfg, bblock, (ins), (ip));    \
1647                         NEW_TEMPLOAD (cfg, (ins), temp);        \
1648                 }       \
1649         } while (0)
1650 #define STARG_SOFT_FLOAT(cfg,ins,idx,ip) do {\
1651                 if (param_types [(idx)]->type == MONO_TYPE_R4 && !param_types [(idx)]->byref) { \
1652                         NEW_ARGLOADA (cfg, (ins), (idx));       \
1653                         handle_store_float (cfg, bblock, (ins), *sp, (ip));     \
1654                         MONO_INST_NEW (cfg, (ins), OP_NOP);     \
1655                 }       \
1656         } while (0)
1657
1658 #define NEW_TEMPLOAD_SOFT_FLOAT(cfg,bblock,ins,num,ip) do {             \
1659         if ((ins)->opcode == CEE_LDIND_R4) {                                            \
1660             int idx = (num);                                                                            \
1661             int temp;                                                                                   \
1662             NEW_TEMPLOADA (cfg, (ins), (idx));                                                  \
1663                 temp = handle_load_float (cfg, (bblock), (ins), ip);            \
1664                 NEW_TEMPLOAD (cfg, (ins), (temp));                                                      \
1665         }                                                                                                                               \
1666         } while (0)
1667
1668 #define NEW_TEMPSTORE_SOFT_FLOAT(cfg,bblock,ins,num,val,ip) do {                \
1669         if ((ins)->opcode == CEE_STIND_R4) {                                                            \
1670             int idx = (num);                                                                            \
1671                 NEW_TEMPLOADA (cfg, (ins), (idx)); \
1672                 handle_store_float ((cfg), (bblock), (ins), (val), (ip));       \
1673         } \
1674         } while (0)
1675
1676 #else
1677
1678 #define LDLOC_SOFT_FLOAT(cfg,ins,idx,ip)
1679 #define STLOC_SOFT_FLOAT(cfg,ins,idx,ip)
1680 #define LDARG_SOFT_FLOAT(cfg,ins,idx,ip)
1681 #define STARG_SOFT_FLOAT(cfg,ins,idx,ip)
1682 #define NEW_TEMPLOAD_SOFT_FLOAT(cfg,bblock,ins,num,ip)
1683 #define NEW_TEMPSTORE_SOFT_FLOAT(cfg,bblock,ins,num,val,ip)
1684 #endif
1685
1686 #if 0
1687
1688 static const char
1689 param_table [STACK_MAX] [STACK_MAX] = {
1690         {0},
1691 };
1692
1693 static int
1694 check_values_to_signature (MonoInst *args, MonoType *this, MonoMethodSignature *sig)
1695 {
1696         int i;
1697
1698         if (sig->hasthis) {
1699                 switch (args->type) {
1700                 case STACK_I4:
1701                 case STACK_I8:
1702                 case STACK_R8:
1703                 case STACK_VTYPE:
1704                 case STACK_INV:
1705                         return 0;
1706                 }
1707                 args++;
1708         }
1709         for (i = 0; i < sig->param_count; ++i) {
1710                 switch (args [i].type) {
1711                 case STACK_INV:
1712                         return 0;
1713                 case STACK_MP:
1714                         if (!sig->params [i]->byref)
1715                                 return 0;
1716                         continue;
1717                 case STACK_OBJ:
1718                         if (sig->params [i]->byref)
1719                                 return 0;
1720                         switch (sig->params [i]->type) {
1721                         case MONO_TYPE_CLASS:
1722                         case MONO_TYPE_STRING:
1723                         case MONO_TYPE_OBJECT:
1724                         case MONO_TYPE_SZARRAY:
1725                         case MONO_TYPE_ARRAY:
1726                                 break;
1727                         default:
1728                                 return 0;
1729                         }
1730                         continue;
1731                 case STACK_R8:
1732                         if (sig->params [i]->byref)
1733                                 return 0;
1734                         if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1735                                 return 0;
1736                         continue;
1737                 case STACK_PTR:
1738                 case STACK_I4:
1739                 case STACK_I8:
1740                 case STACK_VTYPE:
1741                         break;
1742                 }
1743                 /*if (!param_table [args [i].type] [sig->params [i]->type])
1744                         return 0;*/
1745         }
1746         return 1;
1747 }
1748 #endif
1749
1750 static guint
1751 mini_type_to_ldind (MonoCompile* cfg, MonoType *type)
1752 {
1753         if (cfg->generic_sharing_context && !type->byref) {
1754                 /* FIXME: all the arguments must be references for now,
1755                  * later look inside cfg and see if the arg num is
1756                  * really a reference
1757                  */
1758                 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
1759                         return CEE_LDIND_REF;
1760         }
1761         return mono_type_to_ldind (type);
1762 }
1763
1764 static guint
1765 mini_type_to_stind (MonoCompile* cfg, MonoType *type)
1766 {
1767         if (cfg->generic_sharing_context && !type->byref) {
1768                 /* FIXME: all the arguments must be references for now,
1769                  * later look inside cfg and see if the arg num is
1770                  * really a reference
1771                  */
1772                 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
1773                         return CEE_STIND_REF;
1774         }
1775         return mono_type_to_stind (type);
1776 }
1777
1778 int
1779 mono_op_imm_to_op (int opcode)
1780 {
1781         switch (opcode) {
1782         case OP_ADD_IMM:
1783                 return OP_PADD;
1784         case OP_IADD_IMM:
1785                 return OP_IADD;
1786         case OP_LADD_IMM:
1787                 return OP_LADD;
1788         case OP_ISUB_IMM:
1789                 return OP_ISUB;
1790         case OP_LSUB_IMM:
1791                 return OP_LSUB;
1792         case OP_AND_IMM:
1793 #if SIZEOF_VOID_P == 4
1794                 return OP_IAND;
1795 #else
1796                 return OP_LAND;
1797 #endif
1798         case OP_IAND_IMM:
1799                 return OP_IAND;
1800         case OP_LAND_IMM:
1801                 return OP_LAND;
1802         case OP_IOR_IMM:
1803                 return OP_IOR;
1804         case OP_LOR_IMM:
1805                 return OP_LOR;
1806         case OP_IXOR_IMM:
1807                 return OP_IXOR;
1808         case OP_LXOR_IMM:
1809                 return OP_LXOR;
1810         case OP_ISHL_IMM:
1811                 return OP_ISHL;
1812         case OP_LSHL_IMM:
1813                 return OP_LSHL;
1814         case OP_ISHR_IMM:
1815                 return OP_ISHR;
1816         case OP_LSHR_IMM:
1817                 return OP_LSHR;
1818         case OP_ISHR_UN_IMM:
1819                 return OP_ISHR_UN;
1820         case OP_LSHR_UN_IMM:
1821                 return OP_LSHR_UN;
1822         case OP_IDIV_IMM:
1823                 return OP_IDIV;
1824         case OP_IDIV_UN_IMM:
1825                 return OP_IDIV_UN;
1826         case OP_IREM_UN_IMM:
1827                 return OP_IREM_UN;
1828         case OP_IREM_IMM:
1829                 return OP_IREM;
1830         case OP_DIV_IMM:
1831 #if SIZEOF_VOID_P == 4
1832                 return OP_IDIV;
1833 #else
1834                 return OP_LDIV;
1835 #endif
1836         case OP_REM_IMM:
1837 #if SIZEOF_VOID_P == 4
1838                 return OP_IREM;
1839 #else
1840                 return OP_LREM;
1841 #endif
1842         case OP_ADDCC_IMM:
1843                 return OP_ADDCC;
1844         case OP_ADC_IMM:
1845                 return OP_ADC;
1846         case OP_SUBCC_IMM:
1847                 return OP_SUBCC;
1848         case OP_SBB_IMM:
1849                 return OP_SBB;
1850         case OP_IADC_IMM:
1851                 return OP_IADC;
1852         case OP_ISBB_IMM:
1853                 return OP_ISBB;
1854         case OP_COMPARE_IMM:
1855                 return OP_COMPARE;
1856         case OP_ICOMPARE_IMM:
1857                 return OP_ICOMPARE;
1858         default:
1859                 printf ("%s\n", mono_inst_name (opcode));
1860                 g_assert_not_reached ();
1861         }
1862 }
1863
1864 /*
1865  * mono_decompose_op_imm:
1866  *
1867  *   Replace the OP_.._IMM INS with its non IMM variant.
1868  */
1869 void
1870 mono_decompose_op_imm (MonoCompile *cfg, MonoInst *ins)
1871 {
1872         MonoInst *temp;
1873
1874         MONO_INST_NEW (cfg, temp, OP_ICONST);
1875         temp->inst_c0 = ins->inst_imm;
1876         temp->dreg = mono_regstate_next_int (cfg->rs);
1877         MONO_INST_LIST_ADD_TAIL (&(temp)->node, &(ins)->node);
1878         ins->opcode = mono_op_imm_to_op (ins->opcode);
1879         ins->sreg2 = temp->dreg;
1880 }
1881
1882 /*
1883  * When we need a pointer to the current domain many times in a method, we
1884  * call mono_domain_get() once and we store the result in a local variable.
1885  * This function returns the variable that represents the MonoDomain*.
1886  */
1887 inline static MonoInst *
1888 mono_get_domainvar (MonoCompile *cfg)
1889 {
1890         if (!cfg->domainvar)
1891                 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1892         return cfg->domainvar;
1893 }
1894
1895 /*
1896  * The got_var contains the address of the Global Offset Table when AOT 
1897  * compiling.
1898  */
1899 inline static MonoInst *
1900 mono_get_got_var (MonoCompile *cfg)
1901 {
1902 #ifdef MONO_ARCH_NEED_GOT_VAR
1903         if (!cfg->compile_aot)
1904                 return NULL;
1905         if (!cfg->got_var) {
1906                 cfg->got_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1907         }
1908         return cfg->got_var;
1909 #else
1910         return NULL;
1911 #endif
1912 }
1913
1914 static MonoInst *
1915 mono_get_vtable_var (MonoCompile *cfg)
1916 {
1917         g_assert (cfg->generic_sharing_context);
1918
1919         if (!cfg->rgctx_var) {
1920                 cfg->rgctx_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1921                 /* force the var to be stack allocated */
1922                 cfg->rgctx_var->flags |= MONO_INST_INDIRECT;
1923         }
1924
1925         return cfg->rgctx_var;
1926 }
1927
1928 MonoInst*
1929 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1930 {
1931         MonoInst *inst;
1932         int num = cfg->num_varinfo;
1933
1934         if ((num + 1) >= cfg->varinfo_count) {
1935                 int orig_count = cfg->varinfo_count;
1936                 cfg->varinfo_count = (cfg->varinfo_count + 2) * 2;
1937                 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
1938                 cfg->vars = (MonoMethodVar *)g_realloc (cfg->vars, sizeof (MonoMethodVar) * cfg->varinfo_count);
1939                 memset (&cfg->vars [orig_count], 0, (cfg->varinfo_count - orig_count) * sizeof (MonoMethodVar));
1940         }
1941
1942         /*g_print ("created temp %d of type 0x%x\n", num, type->type);*/
1943         mono_jit_stats.allocate_var++;
1944
1945         MONO_INST_NEW (cfg, inst, opcode);
1946         inst->inst_c0 = num;
1947         inst->inst_vtype = type;
1948         inst->klass = mono_class_from_mono_type (type);
1949         /* if set to 1 the variable is native */
1950         inst->backend.is_pinvoke = 0;
1951
1952         cfg->varinfo [num] = inst;
1953
1954         MONO_INIT_VARINFO (&cfg->vars [num], num);
1955
1956         cfg->num_varinfo++;
1957         if (cfg->verbose_level > 2)
1958                 g_print ("created temp %d of type %s\n", num, mono_type_get_name (type));
1959         return inst;
1960 }
1961
1962 /*
1963  * Transform a MonoInst into a load from the variable of index var_index.
1964  */
1965 void
1966 mono_compile_make_var_load (MonoCompile *cfg, MonoInst *dest, gssize var_index) {
1967         memset (dest, 0, sizeof (MonoInst));
1968         dest->ssa_op = MONO_SSA_LOAD;
1969         dest->inst_i0 = cfg->varinfo [var_index];
1970         dest->opcode = mini_type_to_ldind (cfg, dest->inst_i0->inst_vtype);
1971         type_to_eval_stack_type (cfg, dest->inst_i0->inst_vtype, dest);
1972         dest->klass = dest->inst_i0->klass;
1973 }
1974
1975 /*
1976  * Create a MonoInst that is a load from the variable of index var_index.
1977  */
1978 MonoInst*
1979 mono_compile_create_var_load (MonoCompile *cfg, gssize var_index) {
1980         MonoInst *dest;
1981         NEW_TEMPLOAD (cfg,dest,var_index);
1982         return dest;
1983 }
1984
1985 /*
1986  * Create a MonoInst that is a store of the given value into the variable of index var_index.
1987  */
1988 MonoInst*
1989 mono_compile_create_var_store (MonoCompile *cfg, gssize var_index, MonoInst *value) {
1990         MonoInst *dest;
1991         NEW_TEMPSTORE (cfg, dest, var_index, value);
1992         return dest;
1993 }
1994
1995 static MonoType*
1996 type_from_stack_type (MonoInst *ins) {
1997         switch (ins->type) {
1998         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1999         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
2000         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
2001         case STACK_R8: return &mono_defaults.double_class->byval_arg;
2002         case STACK_MP:
2003                 /* 
2004                  * this if used to be commented without any specific reason, but
2005                  * it breaks #80235 when commented
2006                  */
2007                 if (ins->klass)
2008                         return &ins->klass->this_arg;
2009                 else
2010                         return &mono_defaults.object_class->this_arg;
2011         case STACK_OBJ:
2012                 /* ins->klass may not be set for ldnull.
2013                  * Also, if we have a boxed valuetype, we want an object lass,
2014                  * not the valuetype class
2015                  */
2016                 if (ins->klass && !ins->klass->valuetype)
2017                         return &ins->klass->byval_arg;
2018                 return &mono_defaults.object_class->byval_arg;
2019         case STACK_VTYPE: return &ins->klass->byval_arg;
2020         default:
2021                 g_error ("stack type %d to montype not handled\n", ins->type);
2022         }
2023         return NULL;
2024 }
2025
2026 MonoType*
2027 mono_type_from_stack_type (MonoInst *ins) {
2028         return type_from_stack_type (ins);
2029 }
2030
2031 static MonoClass*
2032 array_access_to_klass (int opcode, MonoInst *array_obj)
2033 {
2034         switch (opcode) {
2035         case CEE_LDELEM_U1:
2036                 return mono_defaults.byte_class;
2037         case CEE_LDELEM_U2:
2038                 return mono_defaults.uint16_class;
2039         case CEE_LDELEM_I:
2040         case CEE_STELEM_I:
2041                 return mono_defaults.int_class;
2042         case CEE_LDELEM_I1:
2043         case CEE_STELEM_I1:
2044                 return mono_defaults.sbyte_class;
2045         case CEE_LDELEM_I2:
2046         case CEE_STELEM_I2:
2047                 return mono_defaults.int16_class;
2048         case CEE_LDELEM_I4:
2049         case CEE_STELEM_I4:
2050                 return mono_defaults.int32_class;
2051         case CEE_LDELEM_U4:
2052                 return mono_defaults.uint32_class;
2053         case CEE_LDELEM_I8:
2054         case CEE_STELEM_I8:
2055                 return mono_defaults.int64_class;
2056         case CEE_LDELEM_R4:
2057         case CEE_STELEM_R4:
2058                 return mono_defaults.single_class;
2059         case CEE_LDELEM_R8:
2060         case CEE_STELEM_R8:
2061                 return mono_defaults.double_class;
2062         case CEE_LDELEM_REF:
2063         case CEE_STELEM_REF: {
2064                 MonoClass *klass = array_obj->klass;
2065                 /* FIXME: add assert */
2066                 if (klass && klass->rank)
2067                         return klass->element_class;
2068                 return mono_defaults.object_class;
2069         }
2070         default:
2071                 g_assert_not_reached ();
2072         }
2073         return NULL;
2074 }
2075
2076 void
2077 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
2078 {
2079         MonoInst *last = mono_inst_list_last (&bb->ins_list);
2080
2081         if (last && ((last->opcode >= CEE_BEQ &&
2082                         last->opcode <= CEE_BLT_UN) ||
2083                         last->opcode == OP_BR ||
2084                         last->opcode == OP_SWITCH)) {
2085                 MONO_INST_LIST_ADD_TAIL (&inst->node, &last->node);
2086         } else {
2087                 MONO_ADD_INS (bb, inst);
2088         }
2089 }
2090
2091 void
2092 mono_add_varcopy_to_end (MonoCompile *cfg, MonoBasicBlock *bb, int src, int dest)
2093 {
2094         MonoInst *inst, *load;
2095
2096         NEW_TEMPLOAD (cfg, load, src);
2097
2098         NEW_TEMPSTORE (cfg, inst, dest, load);
2099         /* FIXME: handle CEE_STIND_R4 */
2100         if (inst->opcode == CEE_STOBJ) {
2101                 NEW_TEMPLOADA (cfg, inst, dest);
2102                 handle_stobj (cfg, bb, inst, load, NULL, inst->klass, TRUE, FALSE, FALSE);
2103         } else {
2104                 inst->cil_code = NULL;
2105                 mono_add_ins_to_end (bb, inst);
2106         }
2107 }
2108
2109 /*
2110  * This function is called to handle items that are left on the evaluation stack
2111  * at basic block boundaries. What happens is that we save the values to local variables
2112  * and we reload them later when first entering the target basic block (with the
2113  * handle_loaded_temps () function).
2114  * It is also used to handle items on the stack in store opcodes, since it is
2115  * possible that the variable to be stored into is already on the stack, in
2116  * which case its old value should be used.
2117  * A single joint point will use the same variables (stored in the array bb->out_stack or
2118  * bb->in_stack, if the basic block is before or after the joint point).
2119  * If the stack merge fails at a join point, cfg->unverifiable is set.
2120  */
2121 static void
2122 handle_stack_args (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **sp, int count)
2123 {
2124         int i, bindex;
2125         MonoBasicBlock *outb;
2126         MonoInst *inst, **locals;
2127         gboolean found;
2128
2129         if (!count)
2130                 return;
2131         if (cfg->verbose_level > 3)
2132                 g_print ("%d item(s) on exit from B%d\n", count, bb->block_num);
2133
2134         if (!bb->out_scount) {
2135                 bb->out_scount = count;
2136                 //g_print ("bblock %d has out:", bb->block_num);
2137                 found = FALSE;
2138                 for (i = 0; i < bb->out_count; ++i) {
2139                         outb = bb->out_bb [i];
2140                         /* exception handlers are linked, but they should not be considered for stack args */
2141                         if (outb->flags & BB_EXCEPTION_HANDLER)
2142                                 continue;
2143                         //g_print (" %d", outb->block_num);
2144                         if (outb->in_stack) {
2145                                 found = TRUE;
2146                                 bb->out_stack = outb->in_stack;
2147                                 break;
2148                         }
2149                 }
2150                 //g_print ("\n");
2151                 if (!found) {
2152                         bb->out_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
2153                         for (i = 0; i < count; ++i) {
2154                                 /* 
2155                                  * try to reuse temps already allocated for this purpouse, if they occupy the same
2156                                  * stack slot and if they are of the same type.
2157                                  * This won't cause conflicts since if 'local' is used to 
2158                                  * store one of the values in the in_stack of a bblock, then
2159                                  * the same variable will be used for the same outgoing stack 
2160                                  * slot as well. 
2161                                  * This doesn't work when inlining methods, since the bblocks
2162                                  * in the inlined methods do not inherit their in_stack from
2163                                  * the bblock they are inlined to. See bug #58863 for an
2164                                  * example.
2165                                  * This hack is disabled since it also prevents proper tracking of types.
2166                                  */
2167 #if 1
2168                                 bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
2169 #else
2170                                 if (cfg->inlined_method)
2171                                         bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
2172                                 else
2173                                         bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
2174 #endif
2175                         }
2176                 }
2177         }
2178
2179         for (i = 0; i < bb->out_count; ++i) {
2180                 outb = bb->out_bb [i];
2181                 /* exception handlers are linked, but they should not be considered for stack args */
2182                 if (outb->flags & BB_EXCEPTION_HANDLER)
2183                         continue;
2184                 if (outb->in_scount) {
2185                         if (outb->in_scount != bb->out_scount) {
2186                                 cfg->unverifiable = TRUE;
2187                                 return;
2188                         }
2189                         continue; /* check they are the same locals */
2190                 }
2191                 outb->in_scount = count;
2192                 outb->in_stack = bb->out_stack;
2193         }
2194
2195         locals = bb->out_stack;
2196         for (i = 0; i < count; ++i) {
2197                 /* add store ops at the end of the bb, before the branch */
2198                 NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
2199                 if (inst->opcode == CEE_STOBJ) {
2200                         NEW_TEMPLOADA (cfg, inst, locals [i]->inst_c0);
2201                         handle_stobj (cfg, bb, inst, sp [i], sp [i]->cil_code, inst->klass, TRUE, FALSE, FALSE);
2202                 } else {
2203                         inst->cil_code = sp [i]->cil_code;
2204                         mono_add_ins_to_end (bb, inst);
2205                 }
2206                 if (cfg->verbose_level > 3)
2207                         g_print ("storing %d to temp %d\n", i, (int)locals [i]->inst_c0);
2208         }
2209
2210         /*
2211          * It is possible that the out bblocks already have in_stack assigned, and
2212          * the in_stacks differ. In this case, we will store to all the different 
2213          * in_stacks.
2214          */
2215
2216         found = TRUE;
2217         bindex = 0;
2218         while (found) {
2219                 /* Find a bblock which has a different in_stack */
2220                 found = FALSE;
2221                 while (bindex < bb->out_count) {
2222                         outb = bb->out_bb [bindex];
2223                         /* exception handlers are linked, but they should not be considered for stack args */
2224                         if (outb->flags & BB_EXCEPTION_HANDLER) {
2225                                 bindex++;
2226                                 continue;
2227                         }
2228                         if (outb->in_stack != locals) {
2229                                 /* 
2230                                  * Instead of storing sp [i] to locals [i], we need to store
2231                                  * locals [i] to <new locals>[i], since the sp [i] tree can't
2232                                  * be shared between trees.
2233                                  */
2234                                 for (i = 0; i < count; ++i)
2235                                         mono_add_varcopy_to_end (cfg, bb, locals [i]->inst_c0, outb->in_stack [i]->inst_c0);
2236                                 locals = outb->in_stack;
2237                                 found = TRUE;
2238                                 break;
2239                         }
2240                         bindex ++;
2241                 }
2242         }
2243 }
2244
2245 static int
2246 ret_type_to_call_opcode (MonoType *type, int calli, int virt, MonoGenericSharingContext *gsctx)
2247 {
2248         if (type->byref)
2249                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2250
2251 handle_enum:
2252         type = mini_get_basic_type_from_generic (gsctx, type);
2253         switch (type->type) {
2254         case MONO_TYPE_VOID:
2255                 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALLVIRT: OP_VOIDCALL;
2256         case MONO_TYPE_I1:
2257         case MONO_TYPE_U1:
2258         case MONO_TYPE_BOOLEAN:
2259         case MONO_TYPE_I2:
2260         case MONO_TYPE_U2:
2261         case MONO_TYPE_CHAR:
2262         case MONO_TYPE_I4:
2263         case MONO_TYPE_U4:
2264                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2265         case MONO_TYPE_I:
2266         case MONO_TYPE_U:
2267         case MONO_TYPE_PTR:
2268         case MONO_TYPE_FNPTR:
2269                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2270         case MONO_TYPE_CLASS:
2271         case MONO_TYPE_STRING:
2272         case MONO_TYPE_OBJECT:
2273         case MONO_TYPE_SZARRAY:
2274         case MONO_TYPE_ARRAY:    
2275                 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2276         case MONO_TYPE_I8:
2277         case MONO_TYPE_U8:
2278                 return calli? OP_LCALL_REG: virt? OP_LCALLVIRT: OP_LCALL;
2279         case MONO_TYPE_R4:
2280         case MONO_TYPE_R8:
2281                 return calli? OP_FCALL_REG: virt? OP_FCALLVIRT: OP_FCALL;
2282         case MONO_TYPE_VALUETYPE:
2283                 if (type->data.klass->enumtype) {
2284                         type = type->data.klass->enum_basetype;
2285                         goto handle_enum;
2286                 } else
2287                         return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
2288         case MONO_TYPE_TYPEDBYREF:
2289                 return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
2290         case MONO_TYPE_GENERICINST:
2291                 type = &type->data.generic_class->container_class->byval_arg;
2292                 goto handle_enum;
2293         default:
2294                 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
2295         }
2296         return -1;
2297 }
2298
2299 void
2300 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
2301 {
2302         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
2303         MonoJumpInfoBBTable *table;
2304
2305         table = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
2306         table->table = bbs;
2307         table->table_size = num_blocks;
2308         
2309         ji->ip.label = label;
2310         ji->type = MONO_PATCH_INFO_SWITCH;
2311         ji->data.table = table;
2312         ji->next = cfg->patch_info;
2313         cfg->patch_info = ji;
2314 }
2315
2316 static void
2317 mono_save_token_info (MonoCompile *cfg, MonoImage *image, guint32 token, gpointer key)
2318 {
2319         if (cfg->compile_aot) {
2320                 MonoJumpInfoToken *jump_info_token = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoToken));
2321                 jump_info_token->image = image;
2322                 jump_info_token->token = token;
2323                 g_hash_table_insert (cfg->token_info_hash, key, jump_info_token);
2324         }
2325 }
2326
2327 /*
2328  * When we add a tree of instructions, we need to ensure the instructions currently
2329  * on the stack are executed before (like, if we load a value from a local).
2330  * We ensure this by saving the currently loaded values to temps and rewriting the
2331  * instructions to load the values.
2332  * This is not done for opcodes that terminate a basic block (because it's handled already
2333  * by handle_stack_args ()) and for opcodes that can't change values, like POP.
2334  */
2335 static void
2336 handle_loaded_temps (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst **stack, MonoInst **sp)
2337 {
2338         MonoInst *load, *store, *temp, *ins;
2339
2340         while (stack < sp) {
2341                 ins = *stack;
2342                 /* handle also other constants */
2343                 if ((ins->opcode != OP_ICONST) &&
2344                     /* temps never get written to again, so we can safely avoid duplicating them */
2345                     !(ins->ssa_op == MONO_SSA_LOAD && ins->inst_i0->opcode == OP_LOCAL && ins->inst_i0->flags & MONO_INST_IS_TEMP)) {
2346                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
2347                         temp->flags |= MONO_INST_IS_TEMP;
2348                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2349                         store->cil_code = ins->cil_code;
2350                         if (store->opcode == CEE_STOBJ) {
2351                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2352                                 handle_stobj (cfg, bblock, store, ins, ins->cil_code, temp->klass, FALSE, FALSE, FALSE);
2353                         } else
2354                                 MONO_ADD_INS (bblock, store);
2355                         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2356                         load->cil_code = ins->cil_code;
2357                         *stack = load;
2358                 }
2359                 stack++;
2360         }
2361 }
2362
2363 /*
2364  * target_type_is_incompatible:
2365  * @cfg: MonoCompile context
2366  *
2367  * Check that the item @arg on the evaluation stack can be stored
2368  * in the target type (can be a local, or field, etc).
2369  * The cfg arg can be used to check if we need verification or just
2370  * validity checks.
2371  *
2372  * Returns: non-0 value if arg can't be stored on a target.
2373  */
2374 static int
2375 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
2376 {
2377         MonoType *simple_type;
2378         MonoClass *klass;
2379
2380         if (target->byref) {
2381                 /* FIXME: check that the pointed to types match */
2382                 if (arg->type == STACK_MP)
2383                         return arg->klass != mono_class_from_mono_type (target);
2384                 if (arg->type == STACK_PTR)
2385                         return 0;
2386                 return 1;
2387         }
2388         simple_type = mono_type_get_underlying_type (target);
2389         switch (simple_type->type) {
2390         case MONO_TYPE_VOID:
2391                 return 1;
2392         case MONO_TYPE_I1:
2393         case MONO_TYPE_U1:
2394         case MONO_TYPE_BOOLEAN:
2395         case MONO_TYPE_I2:
2396         case MONO_TYPE_U2:
2397         case MONO_TYPE_CHAR:
2398         case MONO_TYPE_I4:
2399         case MONO_TYPE_U4:
2400                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2401                         return 1;
2402                 return 0;
2403         case MONO_TYPE_PTR:
2404                 /* STACK_MP is needed when setting pinned locals */
2405                 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
2406                         return 1;
2407                 return 0;
2408         case MONO_TYPE_I:
2409         case MONO_TYPE_U:
2410         case MONO_TYPE_FNPTR:
2411                 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2412                         return 1;
2413                 return 0;
2414         case MONO_TYPE_OBJECT:
2415                 if (arg->type != STACK_OBJ)
2416                         return 1;
2417                 return 0;
2418         case MONO_TYPE_STRING:
2419                 if (arg->type != STACK_OBJ)
2420                         return 1;
2421                 /* ldnull has arg->klass unset */
2422                 /*if (arg->klass && arg->klass != mono_defaults.string_class) {
2423                         G_BREAKPOINT ();
2424                         return 1;
2425                 }*/
2426                 return 0;
2427         case MONO_TYPE_CLASS:
2428         case MONO_TYPE_SZARRAY:
2429         case MONO_TYPE_ARRAY:    
2430                 if (arg->type != STACK_OBJ)
2431                         return 1;
2432                 /* FIXME: check type compatibility */
2433                 return 0;
2434         case MONO_TYPE_I8:
2435         case MONO_TYPE_U8:
2436                 if (arg->type != STACK_I8)
2437                         return 1;
2438                 return 0;
2439         case MONO_TYPE_R4:
2440         case MONO_TYPE_R8:
2441                 if (arg->type != STACK_R8)
2442                         return 1;
2443                 return 0;
2444         case MONO_TYPE_VALUETYPE:
2445                 if (arg->type != STACK_VTYPE)
2446                         return 1;
2447                 klass = mono_class_from_mono_type (simple_type);
2448                 if (klass != arg->klass)
2449                         return 1;
2450                 return 0;
2451         case MONO_TYPE_TYPEDBYREF:
2452                 if (arg->type != STACK_VTYPE)
2453                         return 1;
2454                 klass = mono_class_from_mono_type (simple_type);
2455                 if (klass != arg->klass)
2456                         return 1;
2457                 return 0;
2458         case MONO_TYPE_GENERICINST:
2459                 if (mono_type_generic_inst_is_valuetype (simple_type)) {
2460                         klass = mono_class_from_mono_type (simple_type);
2461                         if (klass->enumtype)
2462                                 return target_type_is_incompatible (cfg, klass->enum_basetype, arg);
2463                         if (arg->type != STACK_VTYPE)
2464                                 return 1;
2465                         if (klass != arg->klass)
2466                                 return 1;
2467                         return 0;
2468                 } else {
2469                         if (arg->type != STACK_OBJ)
2470                                 return 1;
2471                         /* FIXME: check type compatibility */
2472                         return 0;
2473                 }
2474         case MONO_TYPE_VAR:
2475         case MONO_TYPE_MVAR:
2476                 /* FIXME: all the arguments must be references for now,
2477                  * later look inside cfg and see if the arg num is
2478                  * really a reference
2479                  */
2480                 g_assert (cfg->generic_sharing_context);
2481                 if (arg->type != STACK_OBJ)
2482                         return 1;
2483                 return 0;
2484         default:
2485                 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
2486         }
2487         return 1;
2488 }
2489
2490 /*
2491  * Prepare arguments for passing to a function call.
2492  * Return a non-zero value if the arguments can't be passed to the given
2493  * signature.
2494  * The type checks are not yet complete and some conversions may need
2495  * casts on 32 or 64 bit architectures.
2496  *
2497  * FIXME: implement this using target_type_is_incompatible ()
2498  */
2499 static int
2500 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
2501 {
2502         MonoType *simple_type;
2503         int i;
2504
2505         if (sig->hasthis) {
2506                 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
2507                         return 1;
2508                 args++;
2509         }
2510         for (i = 0; i < sig->param_count; ++i) {
2511                 if (sig->params [i]->byref) {
2512                         if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
2513                                 return 1;
2514                         continue;
2515                 }
2516                 simple_type = sig->params [i];
2517                 simple_type = mini_get_basic_type_from_generic (cfg->generic_sharing_context, simple_type);
2518 handle_enum:
2519                 switch (simple_type->type) {
2520                 case MONO_TYPE_VOID:
2521                         return 1;
2522                         continue;
2523                 case MONO_TYPE_I1:
2524                 case MONO_TYPE_U1:
2525                 case MONO_TYPE_BOOLEAN:
2526                 case MONO_TYPE_I2:
2527                 case MONO_TYPE_U2:
2528                 case MONO_TYPE_CHAR:
2529                 case MONO_TYPE_I4:
2530                 case MONO_TYPE_U4:
2531                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2532                                 return 1;
2533                         continue;
2534                 case MONO_TYPE_I:
2535                 case MONO_TYPE_U:
2536                 case MONO_TYPE_PTR:
2537                 case MONO_TYPE_FNPTR:
2538                         if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2539                                 return 1;
2540                         continue;
2541                 case MONO_TYPE_CLASS:
2542                 case MONO_TYPE_STRING:
2543                 case MONO_TYPE_OBJECT:
2544                 case MONO_TYPE_SZARRAY:
2545                 case MONO_TYPE_ARRAY:    
2546                         if (args [i]->type != STACK_OBJ)
2547                                 return 1;
2548                         continue;
2549                 case MONO_TYPE_I8:
2550                 case MONO_TYPE_U8:
2551                         if (args [i]->type != STACK_I8)
2552                                 return 1;
2553                         continue;
2554                 case MONO_TYPE_R4:
2555                 case MONO_TYPE_R8:
2556                         if (args [i]->type != STACK_R8)
2557                                 return 1;
2558                         continue;
2559                 case MONO_TYPE_VALUETYPE:
2560                         if (simple_type->data.klass->enumtype) {
2561                                 simple_type = simple_type->data.klass->enum_basetype;
2562                                 goto handle_enum;
2563                         }
2564                         if (args [i]->type != STACK_VTYPE)
2565                                 return 1;
2566                         continue;
2567                 case MONO_TYPE_TYPEDBYREF:
2568                         if (args [i]->type != STACK_VTYPE)
2569                                 return 1;
2570                         continue;
2571                 case MONO_TYPE_GENERICINST:
2572                         simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2573                         goto handle_enum;
2574
2575                 default:
2576                         g_error ("unknown type 0x%02x in check_call_signature",
2577                                  simple_type->type);
2578                 }
2579         }
2580         return 0;
2581 }
2582
2583 inline static int
2584 mono_spill_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoCallInst *call, MonoMethodSignature *sig, gboolean ret_object, 
2585                  const guint8 *ip, gboolean to_end)
2586 {
2587         MonoInst *temp, *store, *ins = (MonoInst*)call;
2588         MonoType *ret = sig->ret;
2589
2590         if (!MONO_TYPE_IS_VOID (ret) || ret_object) {
2591                 if (ret_object) {
2592                         call->inst.type = STACK_OBJ;
2593                         call->inst.opcode = OP_CALL;
2594                         temp = mono_compile_create_var (cfg, &mono_defaults.string_class->byval_arg, OP_LOCAL);
2595                 } else {
2596                         type_to_eval_stack_type (cfg, ret, ins);
2597                         temp = mono_compile_create_var (cfg, ret, OP_LOCAL);
2598                 }
2599                 
2600                 temp->flags |= MONO_INST_IS_TEMP;
2601
2602                 if (MONO_TYPE_ISSTRUCT (ret)) {
2603                         MonoInst *loada, *dummy_store;
2604
2605                         /* 
2606                          * Emit a dummy store to the local holding the result so the
2607                          * liveness info remains correct.
2608                          */
2609                         NEW_DUMMY_STORE (cfg, dummy_store, temp->inst_c0);
2610                         if (to_end)
2611                                 mono_add_ins_to_end (bblock, dummy_store);
2612                         else
2613                                 MONO_ADD_INS (bblock, dummy_store);
2614
2615                         /* we use this to allocate native sized structs */
2616                         temp->backend.is_pinvoke = sig->pinvoke;
2617
2618                         NEW_TEMPLOADA (cfg, loada, temp->inst_c0);
2619                         if (call->inst.opcode == OP_VCALL || call->inst.opcode == OP_VCALL_RGCTX)
2620                                 ins->inst_left = loada;
2621                         else
2622                                 ins->inst_right = loada; /* a virtual or indirect call */
2623
2624                         if (to_end)
2625                                 mono_add_ins_to_end (bblock, ins);
2626                         else
2627                                 MONO_ADD_INS (bblock, ins);
2628                 } else {
2629                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2630                         store->cil_code = ip;
2631                         
2632 #ifdef MONO_ARCH_SOFT_FLOAT
2633                         if (store->opcode == CEE_STIND_R4) {
2634                                 /*FIXME implement proper support for to_end*/
2635                                 g_assert (!to_end);
2636                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2637                                 handle_store_float (cfg, bblock, store, ins, ip);
2638                         } else
2639 #endif
2640                         if (to_end)
2641                                 mono_add_ins_to_end (bblock, store);
2642                         else
2643                                 MONO_ADD_INS (bblock, store);
2644                 }
2645                 return temp->inst_c0;
2646         } else {
2647                 if (to_end)
2648                         mono_add_ins_to_end (bblock, ins);
2649                 else
2650                         MONO_ADD_INS (bblock, ins);
2651                 return -1;
2652         }
2653 }
2654
2655 inline static MonoCallInst *
2656 mono_emit_call_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
2657                      MonoInst **args, int calli, int virtual, const guint8 *ip, gboolean to_end)
2658 {
2659         MonoCallInst *call;
2660         MonoInst *arg, *n;
2661
2662         MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (sig->ret, calli, virtual, cfg->generic_sharing_context));
2663
2664 #ifdef MONO_ARCH_SOFT_FLOAT
2665         /* we need to convert the r4 value to an int value */
2666         {
2667                 int i;
2668                 for (i = 0; i < sig->param_count; ++i) {
2669                         if (!sig->params [i]->byref && sig->params [i]->type == MONO_TYPE_R4) {
2670                                 MonoInst *iargs [1];
2671                                 int temp;
2672                                 iargs [0] = args [i + sig->hasthis];
2673
2674                                 temp = mono_emit_jit_icall (cfg, bblock, mono_fload_r4_arg, iargs, ip);
2675                                 NEW_TEMPLOAD (cfg, arg, temp);
2676                                 args [i + sig->hasthis] = arg;
2677                         }
2678                 }
2679         }
2680 #endif
2681
2682         call->inst.cil_code = ip;
2683         call->args = args;
2684         call->signature = sig;
2685         call = mono_arch_call_opcode (cfg, bblock, call, virtual);
2686         type_to_eval_stack_type (cfg, sig->ret, &call->inst);
2687
2688         MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (arg, n, &call->out_args, node) {
2689                 if (!arg->cil_code)
2690                         arg->cil_code = ip;
2691                 if (to_end)
2692                         mono_add_ins_to_end (bblock, arg);
2693                 else
2694                         MONO_ADD_INS (bblock, arg);
2695         }
2696         return call;
2697 }
2698
2699 inline static MonoCallInst*
2700 mono_emit_calli (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
2701                  MonoInst **args, MonoInst *addr, const guint8 *ip)
2702 {
2703         MonoCallInst *call = mono_emit_call_args (cfg, bblock, sig, args, TRUE, FALSE, ip, FALSE);
2704
2705         call->inst.inst_i0 = addr;
2706
2707         return call;
2708 }
2709
2710 inline static MonoCallInst*
2711 mono_emit_rgctx_calli (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2712         MonoInst **args, MonoInst *addr, MonoInst *rgctx_arg, const guint8 *ip)
2713 {
2714         MonoCallInst *call = mono_emit_calli (cfg, bblock, sig, args, addr, ip);
2715
2716         if (rgctx_arg) {
2717                 switch (call->inst.opcode) {
2718                 case OP_CALL_REG: call->inst.opcode = OP_CALL_REG_RGCTX; break;
2719                 case OP_VOIDCALL_REG: call->inst.opcode = OP_VOIDCALL_REG_RGCTX; break;
2720                 case OP_FCALL_REG: call->inst.opcode = OP_FCALL_REG_RGCTX; break;
2721                 case OP_LCALL_REG: call->inst.opcode = OP_LCALL_REG_RGCTX; break;
2722                 case OP_VCALL_REG: {
2723                         MonoInst *group;
2724
2725                         NEW_GROUP (cfg, group, call->inst.inst_left, NULL);
2726                         call->inst.inst_left = group;
2727                         call->inst.opcode = OP_VCALL_REG_RGCTX;
2728                         break;
2729                 }
2730                 default: g_assert_not_reached ();
2731                 }
2732
2733                 if (call->inst.opcode != OP_VCALL_REG_RGCTX) {
2734                         g_assert (!call->inst.inst_right);
2735                         call->inst.inst_right = rgctx_arg;
2736                 } else {
2737                         g_assert (!call->inst.inst_left->inst_right);
2738                         call->inst.inst_left->inst_right = rgctx_arg;
2739                 }
2740         }
2741
2742         return call;
2743 }
2744
2745 inline static int
2746 mono_emit_calli_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
2747                                                  MonoInst **args, MonoInst *addr, const guint8 *ip)
2748 {
2749         MonoCallInst *call = mono_emit_calli (cfg, bblock, sig, args, addr, ip);
2750
2751         return mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
2752 }
2753
2754 static int
2755 mono_emit_rgctx_calli_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2756         MonoInst **args, MonoInst *addr, MonoInst *rgctx_arg, const guint8 *ip)
2757 {
2758         MonoCallInst *call = mono_emit_rgctx_calli (cfg, bblock, sig, args, addr, rgctx_arg, ip);
2759
2760         return mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
2761 }
2762
2763 static MonoCallInst*
2764 mono_emit_method_call_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2765                        MonoInst **args, const guint8 *ip, MonoInst *this, gboolean to_end)
2766 {
2767         gboolean virtual = this != NULL;
2768         MonoCallInst *call;
2769
2770         call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, virtual, ip, to_end);
2771
2772         if (this && sig->hasthis && 
2773             (method->klass->marshalbyref || method->klass == mono_defaults.object_class) && 
2774             !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !MONO_CHECK_THIS (this)) {
2775                 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2776         } else {
2777                 call->method = method;
2778         }
2779         call->inst.flags |= MONO_INST_HAS_METHOD;
2780         call->inst.inst_left = this;
2781
2782         if (call->method->klass->flags & TYPE_ATTRIBUTE_INTERFACE)
2783                 /* Needed by the code generated in inssel.brg */
2784                 mono_get_got_var (cfg);
2785
2786         return call;
2787 }
2788
2789 static MonoCallInst*
2790 mono_emit_method_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2791                        MonoInst **args, const guint8 *ip, MonoInst *this)
2792 {
2793         return mono_emit_method_call_full (cfg, bblock, method, sig, args, ip, this, FALSE);
2794 }
2795
2796 inline static int
2797 mono_emit_method_call_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2798                        MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this)
2799 {
2800         MonoCallInst *call = mono_emit_method_call (cfg, bblock, method, signature, args, ip, this);
2801
2802         return mono_spill_call (cfg, bblock, call, signature, method->string_ctor, ip, FALSE);
2803 }
2804
2805 inline static int
2806 mono_emit_method_call_spilled_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2807                        MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this,
2808                        gboolean ret_object, gboolean to_end)
2809 {
2810         MonoCallInst *call = mono_emit_method_call_full (cfg, bblock, method, signature, args, ip, this, to_end);
2811
2812         return mono_spill_call (cfg, bblock, call, signature, ret_object, ip, to_end);
2813 }
2814
2815 inline static int
2816 mono_emit_native_call (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoMethodSignature *sig,
2817                        MonoInst **args, const guint8 *ip, gboolean ret_object, gboolean to_end)
2818 {
2819         MonoCallInst *call;
2820
2821         g_assert (sig);
2822
2823         call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, FALSE, ip, to_end);
2824         call->fptr = func;
2825
2826         return mono_spill_call (cfg, bblock, call, sig, ret_object, ip, to_end);
2827 }
2828
2829 inline static int
2830 mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip)
2831 {
2832         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2833         
2834         if (!info) {
2835                 g_warning ("unregistered JIT ICall");
2836                 g_assert_not_reached ();
2837         }
2838
2839         return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, args, ip, FALSE, FALSE);
2840 }
2841
2842 static MonoCallInst*
2843 mono_emit_rgctx_method_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2844                 MonoInst **args, MonoInst *rgctx_arg, MonoInst *imt_arg, const guint8 *ip, MonoInst *this)
2845 {
2846         MonoCallInst *call = mono_emit_method_call_full (cfg, bblock, method, sig, args, ip, this, FALSE);
2847
2848         g_assert (!(rgctx_arg && imt_arg));
2849
2850         if (rgctx_arg) {
2851                 switch (call->inst.opcode) {
2852                 case OP_CALL: call->inst.opcode = OP_CALL_RGCTX; break;
2853                 case OP_VOIDCALL: call->inst.opcode = OP_VOIDCALL_RGCTX; break;
2854                 case OP_FCALL: call->inst.opcode = OP_FCALL_RGCTX; break;
2855                 case OP_LCALL: call->inst.opcode = OP_LCALL_RGCTX; break;
2856                 case OP_VCALL: call->inst.opcode = OP_VCALL_RGCTX; break;
2857                 default: g_assert_not_reached ();
2858                 }
2859
2860                 if (call->inst.opcode != OP_VCALL_RGCTX) {
2861                         g_assert (!call->inst.inst_left);
2862                         call->inst.inst_left = rgctx_arg;
2863                 } else {
2864                         g_assert (!call->inst.inst_right);
2865                         call->inst.inst_right = rgctx_arg;
2866                 }
2867         } else if (imt_arg) {
2868                 switch (call->inst.opcode) {
2869                 case OP_CALLVIRT: call->inst.opcode = OP_CALLVIRT_IMT; break;
2870                 case OP_VOIDCALLVIRT: call->inst.opcode = OP_VOIDCALLVIRT_IMT; break;
2871                 case OP_FCALLVIRT: call->inst.opcode = OP_FCALLVIRT_IMT; break;
2872                 case OP_LCALLVIRT: call->inst.opcode = OP_LCALLVIRT_IMT; break;
2873                 case OP_VCALLVIRT: {
2874                         MonoInst *group;
2875
2876                         NEW_GROUP (cfg, group, call->inst.inst_left, NULL);
2877                         call->inst.inst_left = group;
2878                         call->inst.opcode = OP_VCALLVIRT_IMT;
2879                         break;
2880                 }
2881                 default: g_assert_not_reached ();
2882                 }
2883
2884                 if (call->inst.opcode != OP_VCALLVIRT_IMT) {
2885                         g_assert (!call->inst.inst_right);
2886                         call->inst.inst_right = imt_arg;
2887                 } else {
2888                         g_assert (!call->inst.inst_left->inst_right);
2889                         call->inst.inst_left->inst_right = imt_arg;
2890                 }
2891         }
2892
2893         return call;
2894 }
2895
2896 inline static int
2897 mono_emit_rgctx_method_call_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2898                 MonoMethodSignature *signature, MonoInst **args, MonoInst *rgctx_arg, MonoInst *imt_arg,
2899                 const guint8 *ip, MonoInst *this)
2900 {
2901         MonoCallInst *call = mono_emit_rgctx_method_call (cfg, bblock, method, signature, args, rgctx_arg, imt_arg, ip, this);
2902
2903         return mono_spill_call (cfg, bblock, call, signature, method->string_ctor, ip, FALSE);
2904 }
2905
2906 static void
2907 mono_emulate_opcode (MonoCompile *cfg, MonoInst *tree, MonoInst **iargs, MonoJitICallInfo *info)
2908 {
2909         MonoInst *ins, *temp = NULL, *store, *load;
2910         MonoInstList *head, *list;
2911         int nargs;
2912         MonoCallInst *call;
2913
2914         //g_print ("emulating: ");
2915         //mono_print_tree_nl (tree);
2916         MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (info->sig->ret, FALSE, FALSE, cfg->generic_sharing_context));
2917         ins = (MonoInst*)call;
2918         MONO_INST_LIST_INIT (&ins->node);
2919         
2920         call->inst.cil_code = tree->cil_code;
2921         call->args = iargs;
2922         call->signature = info->sig;
2923
2924         call = mono_arch_call_opcode (cfg, cfg->cbb, call, FALSE);
2925
2926         if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2927                 temp = mono_compile_create_var (cfg, info->sig->ret, OP_LOCAL);
2928                 temp->flags |= MONO_INST_IS_TEMP;
2929                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2930                 MONO_INST_LIST_INIT (&store->node);
2931                 /* FIXME: handle CEE_STIND_R4 */
2932                 store->cil_code = tree->cil_code;
2933         } else {
2934                 store = ins;
2935         }
2936
2937         nargs = info->sig->param_count + info->sig->hasthis;
2938
2939         if (nargs) {
2940                 MONO_INST_LIST_ADD_TAIL (&store->node,
2941                                         &call->out_args);
2942                 list = &call->out_args;
2943         } else {
2944                 list = &store->node;
2945         }
2946
2947         if (cfg->prev_ins) {
2948                 /* 
2949                  * This assumes that that in a tree, emulate_opcode is called for a
2950                  * node before it is called for its children. dec_foreach needs to
2951                  * take this into account.
2952                  */
2953                 head = &cfg->prev_ins->node;
2954         } else {
2955                 head = &cfg->cbb->ins_list;
2956         }
2957
2958         MONO_INST_LIST_SPLICE_INIT (list, head);
2959
2960         call->fptr = mono_icall_get_wrapper (info);
2961
2962         if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2963                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2964                 *tree = *load;
2965         }
2966 }
2967
2968 /*
2969  * This entry point could be used later for arbitrary method
2970  * redirection.
2971  */
2972 inline static int
2973 mini_redirect_call (int *temp, MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
2974                        MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this)
2975 {
2976
2977         if (method->klass == mono_defaults.string_class) {
2978                 /* managed string allocation support */
2979                 if (strcmp (method->name, "InternalAllocateStr") == 0) {
2980                         MonoInst *iargs [2];
2981                         MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
2982                         MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, FALSE);
2983                         if (!managed_alloc)
2984                                 return FALSE;
2985                         NEW_VTABLECONST (cfg, iargs [0], vtable);
2986                         iargs [1] = args [0];
2987                         *temp = mono_emit_method_call_spilled (cfg, bblock, managed_alloc, mono_method_signature (managed_alloc), iargs, ip, this);
2988                         return TRUE;
2989                 }
2990         }
2991         return FALSE;
2992 }
2993
2994 static MonoMethodSignature *
2995 mono_get_array_new_va_signature (int arity)
2996 {
2997         static GHashTable *sighash = NULL;
2998         MonoMethodSignature *res;
2999         int i;
3000
3001         mono_jit_lock ();
3002         if (!sighash) {
3003                 sighash = g_hash_table_new (NULL, NULL);
3004         }
3005         else if ((res = g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
3006                 mono_jit_unlock ();
3007                 return res;
3008         }
3009
3010         res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
3011
3012         res->pinvoke = 1;
3013 #ifdef MONO_ARCH_VARARG_ICALLS
3014         /* Only set this only some archs since not all backends can handle varargs+pinvoke */
3015         res->call_convention = MONO_CALL_VARARG;
3016 #endif
3017
3018 #ifdef PLATFORM_WIN32
3019         res->call_convention = MONO_CALL_C;
3020 #endif
3021
3022         res->params [0] = &mono_defaults.int_class->byval_arg;  
3023         for (i = 0; i < arity; i++)
3024                 res->params [i + 1] = &mono_defaults.int_class->byval_arg;
3025
3026         res->ret = &mono_defaults.int_class->byval_arg;
3027
3028         g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
3029         mono_jit_unlock ();
3030
3031         return res;
3032 }
3033
3034 static MonoMethod*
3035 get_memcpy_method (void)
3036 {
3037         static MonoMethod *memcpy_method = NULL;
3038         if (!memcpy_method) {
3039                 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
3040                 if (!memcpy_method)
3041                         g_error ("Old corlib found. Install a new one");
3042         }
3043         return memcpy_method;
3044 }
3045
3046 static void
3047 handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native, gboolean write_barrier) {
3048         MonoInst *iargs [3];
3049         int n;
3050         guint32 align = 0;
3051         MonoMethod *memcpy_method;
3052
3053         g_assert (klass);
3054         /*
3055          * This check breaks with spilled vars... need to handle it during verification anyway.
3056          * g_assert (klass && klass == src->klass && klass == dest->klass);
3057          */
3058
3059         if (native)
3060                 n = mono_class_native_size (klass, &align);
3061         else
3062                 n = mono_class_value_size (klass, &align);
3063
3064 #if HAVE_WRITE_BARRIERS
3065         /* if native is true there should be no references in the struct */
3066         if (write_barrier && klass->has_references && !native) {
3067                 iargs [0] = dest;
3068                 iargs [1] = src;
3069                 NEW_PCONST (cfg, iargs [2], klass);
3070
3071                 mono_emit_jit_icall (cfg, bblock, mono_value_copy, iargs, ip);
3072                 return;
3073         }
3074 #endif
3075
3076         /* FIXME: add write barrier handling */
3077         if ((cfg->opt & MONO_OPT_INTRINS) && !to_end && n <= sizeof (gpointer) * 5) {
3078                 MonoInst *inst;
3079                 if (dest->opcode == OP_LDADDR) {
3080                         /* Keep liveness info correct */
3081                         NEW_DUMMY_STORE (cfg, inst, dest->inst_i0->inst_c0);
3082                         MONO_ADD_INS (bblock, inst);
3083                 }
3084                 NEW_MEMCPY (cfg, inst, dest, src, n, align);
3085                 MONO_ADD_INS (bblock, inst);
3086                 return;
3087         }
3088         iargs [0] = dest;
3089         iargs [1] = src;
3090         NEW_ICONST (cfg, iargs [2], n);
3091
3092         memcpy_method = get_memcpy_method ();
3093         mono_emit_method_call_spilled_full (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL, FALSE, to_end);
3094 }
3095
3096 static MonoMethod*
3097 get_memset_method (void)
3098 {
3099         static MonoMethod *memset_method = NULL;
3100         if (!memset_method) {
3101                 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
3102                 if (!memset_method)
3103                         g_error ("Old corlib found. Install a new one");
3104         }
3105         return memset_method;
3106 }
3107
3108 static void
3109 handle_initobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, const guchar *ip, MonoClass *klass, MonoInst **stack_start, MonoInst **sp)
3110 {
3111         MonoInst *iargs [3];
3112         MonoInst *ins, *zero_int32;
3113         int n;
3114         guint32 align;
3115         MonoMethod *memset_method;
3116
3117         NEW_ICONST (cfg, zero_int32, 0);
3118
3119         mono_class_init (klass);
3120         n = mono_class_value_size (klass, &align);
3121         MONO_INST_NEW (cfg, ins, 0);
3122         ins->cil_code = ip;
3123         ins->inst_left = dest;
3124         ins->inst_right = zero_int32;
3125         if (n == 1) {
3126                 ins->opcode = CEE_STIND_I1;
3127                 MONO_ADD_INS (bblock, ins);
3128         } else if ((n == 2) && (align >= 2)) {
3129                 ins->opcode = CEE_STIND_I2;
3130                 MONO_ADD_INS (bblock, ins);
3131         } else if ((n == 2) && (align >= 4)) {
3132                 ins->opcode = CEE_STIND_I4;
3133                 MONO_ADD_INS (bblock, ins);
3134         } else if (n <= sizeof (gpointer) * 5) {
3135                 NEW_MEMSET (cfg, ins, dest, 0, n, align);
3136                 MONO_ADD_INS (bblock, ins);
3137         } else {
3138                 memset_method = get_memset_method ();
3139                 handle_loaded_temps (cfg, bblock, stack_start, sp);
3140                 iargs [0] = dest;
3141                 NEW_ICONST (cfg, iargs [1], 0);
3142                 NEW_ICONST (cfg, iargs [2], n);
3143                 mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
3144         }
3145 }
3146
3147 static int
3148 handle_alloc (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, gboolean for_box, const guchar *ip)
3149 {
3150         MonoInst *iargs [2];
3151         void *alloc_ftn;
3152
3153         if (cfg->opt & MONO_OPT_SHARED) {
3154                 NEW_DOMAINCONST (cfg, iargs [0]);
3155                 NEW_CLASSCONST (cfg, iargs [1], klass);
3156
3157                 alloc_ftn = mono_object_new;
3158         } else if (cfg->compile_aot && bblock->out_of_line && klass->type_token && klass->image == mono_defaults.corlib) {
3159                 /* This happens often in argument checking code, eg. throw new FooException... */
3160                 /* Avoid relocations by calling a helper function specialized to mscorlib */
3161                 NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (klass->type_token));
3162                 return mono_emit_jit_icall (cfg, bblock, mono_helper_newobj_mscorlib, iargs, ip);
3163         } else {
3164                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3165                 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, for_box);
3166                 gboolean pass_lw;
3167
3168                 if (managed_alloc) {
3169                         NEW_VTABLECONST (cfg, iargs [0], vtable);
3170                         return mono_emit_method_call_spilled (cfg, bblock, managed_alloc, mono_method_signature (managed_alloc), iargs, ip, NULL);
3171                 }
3172                 alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
3173                 if (pass_lw) {
3174                         guint32 lw = vtable->klass->instance_size;
3175                         lw = ((lw + (sizeof (gpointer) - 1)) & ~(sizeof (gpointer) - 1)) / sizeof (gpointer);
3176                         NEW_ICONST (cfg, iargs [0], lw);
3177                         NEW_VTABLECONST (cfg, iargs [1], vtable);
3178                 }
3179                 else
3180                         NEW_VTABLECONST (cfg, iargs [0], vtable);
3181         }
3182
3183         return mono_emit_jit_icall (cfg, bblock, alloc_ftn, iargs, ip);
3184 }
3185
3186 static int
3187 handle_alloc_from_inst (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, MonoInst *data_inst,
3188                 gboolean for_box, const guchar *ip)
3189 {
3190         MonoInst *iargs [2];
3191         MonoMethod *managed_alloc = NULL;
3192         void *alloc_ftn;
3193         /*
3194           FIXME: we cannot get managed_alloc here because we can't get
3195           the class's vtable (because it's not a closed class)
3196
3197         MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3198         MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, for_box);
3199         */
3200
3201         if (cfg->opt & MONO_OPT_SHARED) {
3202                 NEW_DOMAINCONST (cfg, iargs [0]);
3203                 iargs [1] = data_inst;
3204                 alloc_ftn = mono_object_new;
3205         } else {
3206                 g_assert (!cfg->compile_aot);
3207
3208                 if (managed_alloc) {
3209                         iargs [0] = data_inst;
3210                         return mono_emit_method_call_spilled (cfg, bblock, managed_alloc,
3211                                 mono_method_signature (managed_alloc), iargs, ip, NULL);
3212                 }
3213
3214                 iargs [0] = data_inst;
3215                 alloc_ftn = mono_object_new_specific;
3216         }
3217
3218         return mono_emit_jit_icall (cfg, bblock, alloc_ftn, iargs, ip);
3219 }
3220
3221 static MonoInst*
3222 handle_box_copy (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *val, const guchar *ip, MonoClass *klass, int temp)
3223 {
3224         MonoInst *dest, *vtoffset, *add, *vstore;
3225
3226         NEW_TEMPLOAD (cfg, dest, temp);
3227         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
3228         MONO_INST_NEW (cfg, add, OP_PADD);
3229         add->inst_left = dest;
3230         add->inst_right = vtoffset;
3231         add->cil_code = ip;
3232         add->klass = klass;
3233         MONO_INST_NEW (cfg, vstore, CEE_STIND_I);
3234         vstore->opcode = mini_type_to_stind (cfg, &klass->byval_arg);
3235         vstore->cil_code = ip;
3236         vstore->inst_left = add;
3237         vstore->inst_right = val;
3238
3239 #ifdef MONO_ARCH_SOFT_FLOAT
3240         if (vstore->opcode == CEE_STIND_R4) {
3241                 handle_store_float (cfg, bblock, add, val, ip);
3242         } else
3243 #endif
3244         if (vstore->opcode == CEE_STOBJ) {
3245                 handle_stobj (cfg, bblock, add, val, ip, klass, FALSE, FALSE, TRUE);
3246         } else
3247                 MONO_ADD_INS (bblock, vstore);
3248
3249         NEW_TEMPLOAD (cfg, dest, temp);
3250         return dest;
3251 }
3252
3253 static MonoInst *
3254 handle_box (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *val, const guchar *ip, MonoClass *klass)
3255 {
3256         MonoInst *dest;
3257         int temp;
3258
3259         if (mono_class_is_nullable (klass)) {
3260                 MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
3261                 temp = mono_emit_method_call_spilled (cfg, bblock, method, mono_method_signature (method), &val, ip, NULL);
3262                 NEW_TEMPLOAD (cfg, dest, temp);
3263                 return dest;
3264         }
3265
3266         temp = handle_alloc (cfg, bblock, klass, TRUE, ip);
3267
3268         return handle_box_copy (cfg, bblock, val, ip, klass, temp);
3269 }
3270
3271 static MonoInst *
3272 handle_box_from_inst (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *val, const guchar *ip,
3273                 MonoClass *klass, MonoInst *data_inst)
3274 {
3275         int temp;
3276
3277         g_assert (!mono_class_is_nullable (klass));
3278
3279         temp = handle_alloc_from_inst (cfg, bblock, klass, data_inst, TRUE, ip);
3280
3281         return handle_box_copy (cfg, bblock, val, ip, klass, temp);
3282 }
3283
3284 static MonoInst*
3285 handle_delegate_ctor (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, MonoInst *target, MonoMethod *method, unsigned char *ip)
3286 {
3287         gpointer *trampoline;
3288         MonoInst *obj, *ins, *store, *offset_ins, *method_ins, *tramp_ins;
3289         int temp;
3290
3291         temp = handle_alloc (cfg, bblock, klass, FALSE, ip);
3292
3293         /* Inline the contents of mono_delegate_ctor */
3294
3295         /* Set target field */
3296         /* Optimize away setting of NULL target */
3297         if (!(target->opcode == OP_PCONST && target->inst_p0 == 0)) {
3298                 NEW_TEMPLOAD (cfg, obj, temp);
3299                 NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, target));
3300                 MONO_INST_NEW (cfg, ins, OP_PADD);
3301                 ins->inst_left = obj;
3302                 ins->inst_right = offset_ins;
3303
3304                 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
3305                 store->inst_left = ins;
3306                 store->inst_right = target;
3307                 mono_bblock_add_inst (bblock, store);
3308         }
3309
3310         /* Set method field */
3311         NEW_TEMPLOAD (cfg, obj, temp);
3312         NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, method));
3313         MONO_INST_NEW (cfg, ins, OP_PADD);
3314         ins->inst_left = obj;
3315         ins->inst_right = offset_ins;
3316
3317         NEW_METHODCONST (cfg, method_ins, method);
3318
3319         MONO_INST_NEW (cfg, store, CEE_STIND_I);
3320         store->inst_left = ins;
3321         store->inst_right = method_ins;
3322         mono_bblock_add_inst (bblock, store);
3323
3324         /* Set invoke_impl field */
3325         NEW_TEMPLOAD (cfg, obj, temp);
3326         NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, invoke_impl));
3327         MONO_INST_NEW (cfg, ins, OP_PADD);
3328         ins->inst_left = obj;
3329         ins->inst_right = offset_ins;
3330
3331         trampoline = mono_create_delegate_trampoline (klass);
3332         NEW_AOTCONST (cfg, tramp_ins, MONO_PATCH_INFO_ABS, trampoline);
3333
3334         MONO_INST_NEW (cfg, store, CEE_STIND_I);
3335         store->inst_left = ins;
3336         store->inst_right = tramp_ins;
3337         mono_bblock_add_inst (bblock, store);
3338
3339         /* All the checks which are in mono_delegate_ctor () are done by the delegate trampoline */
3340
3341         NEW_TEMPLOAD (cfg, obj, temp);
3342
3343         return obj;
3344 }
3345
3346 static MonoJitICallInfo*
3347 mono_get_array_new_va_icall (int rank)
3348 {
3349         char icall_name [256];
3350         char *name;
3351         MonoMethodSignature *esig;
3352         MonoJitICallInfo *info;
3353
3354         /* Need to register the icall so it gets an icall wrapper */
3355         sprintf (icall_name, "ves_array_new_va_%d", rank);
3356
3357         mono_jit_lock ();
3358         info = mono_find_jit_icall_by_name (icall_name);
3359         if (info == NULL) {
3360                 esig = mono_get_array_new_va_signature (rank);
3361                 name = g_strdup (icall_name);
3362                 info = mono_register_jit_icall (mono_array_new_va, name, esig, FALSE);
3363
3364                 g_hash_table_insert (jit_icall_name_hash, name, name);
3365         }
3366         mono_jit_unlock ();
3367
3368         return info;
3369 }
3370
3371 static int
3372 handle_array_new (MonoCompile *cfg, MonoBasicBlock *bblock, int rank, MonoInst **sp, unsigned char *ip)
3373 {
3374         MonoJitICallInfo *info;
3375
3376         info = mono_get_array_new_va_icall (rank);
3377
3378         cfg->flags |= MONO_CFG_HAS_VARARGS;
3379
3380         /* FIXME: This uses info->sig, but it should use the signature of the wrapper */
3381         return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, sp, ip, TRUE, FALSE);
3382 }
3383
3384 static void
3385 mono_emit_load_got_addr (MonoCompile *cfg)
3386 {
3387         MonoInst *load, *store, *dummy_use;
3388         MonoInst *get_got;
3389
3390         if (!cfg->got_var || cfg->got_var_allocated)
3391                 return;
3392
3393         MONO_INST_NEW (cfg, get_got, OP_LOAD_GOTADDR);
3394         NEW_TEMPSTORE (cfg, store, cfg->got_var->inst_c0, get_got);
3395
3396         /* Add it to the start of the first bblock */
3397         MONO_INST_LIST_ADD (&store->node, &cfg->bb_entry->ins_list);
3398
3399         cfg->got_var_allocated = TRUE;
3400
3401         /* 
3402          * Add a dummy use to keep the got_var alive, since real uses might
3403          * only be generated in the decompose or instruction selection phases.
3404          * Add it to end_bblock, so the variable's lifetime covers the whole
3405          * method.
3406          */
3407         NEW_TEMPLOAD (cfg, load, cfg->got_var->inst_c0);
3408         NEW_DUMMY_USE (cfg, dummy_use, load);
3409         MONO_ADD_INS (cfg->bb_exit, dummy_use);
3410 }
3411
3412 #define CODE_IS_STLOC(ip) (((ip) [0] >= CEE_STLOC_0 && (ip) [0] <= CEE_STLOC_3) || ((ip) [0] == CEE_STLOC_S))
3413
3414 static gboolean
3415 mini_class_is_system_array (MonoClass *klass)
3416 {
3417         if (klass->parent == mono_defaults.array_class)
3418                 return TRUE;
3419         else
3420                 return FALSE;
3421 }
3422
3423 static gboolean
3424 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
3425 {
3426         MonoMethodHeader *header = mono_method_get_header (method);
3427         MonoMethodSignature *signature = mono_method_signature (method);
3428         MonoVTable *vtable;
3429         int i;
3430
3431         if (cfg->generic_sharing_context)
3432                 return FALSE;
3433
3434         if (method->inline_failure)
3435                 return FALSE;
3436
3437 #ifdef MONO_ARCH_HAVE_LMF_OPS
3438         if (((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3439                  (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) &&
3440             !MONO_TYPE_ISSTRUCT (signature->ret) && !mini_class_is_system_array (method->klass))
3441                 return TRUE;
3442 #endif
3443
3444         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3445             (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3446             (method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
3447             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
3448             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3449             (method->klass->marshalbyref) ||
3450             !header || header->num_clauses ||
3451             /* fixme: why cant we inline valuetype returns? */
3452             MONO_TYPE_ISSTRUCT (signature->ret))
3453                 return FALSE;
3454
3455 #ifdef MONO_ARCH_SOFT_FLOAT
3456         /* this complicates things, fix later */
3457         if (signature->ret->type == MONO_TYPE_R4)
3458                 return FALSE;
3459 #endif
3460         /* its not worth to inline methods with valuetype arguments?? */
3461         for (i = 0; i < signature->param_count; i++) {
3462                 if (MONO_TYPE_ISSTRUCT (signature->params [i])) {
3463                         return FALSE;
3464                 }
3465 #ifdef MONO_ARCH_SOFT_FLOAT
3466                 /* this complicates things, fix later */
3467                 if (!signature->params [i]->byref && signature->params [i]->type == MONO_TYPE_R4)
3468                         return FALSE;
3469 #endif
3470         }
3471
3472         /* also consider num_locals? */
3473         /* Do the size check early to avoid creating vtables */
3474         if (getenv ("MONO_INLINELIMIT")) {
3475                 if (header->code_size >= atoi (getenv ("MONO_INLINELIMIT"))) {
3476                         return FALSE;
3477                 }
3478         } else if (header->code_size >= INLINE_LENGTH_LIMIT)
3479                 return FALSE;
3480
3481         /*
3482          * if we can initialize the class of the method right away, we do,
3483          * otherwise we don't allow inlining if the class needs initialization,
3484          * since it would mean inserting a call to mono_runtime_class_init()
3485          * inside the inlined code
3486          */
3487         if (!(cfg->opt & MONO_OPT_SHARED)) {
3488                 if (method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) {
3489                         if (cfg->run_cctors && method->klass->has_cctor) {
3490                                 if (!method->klass->runtime_info)
3491                                         /* No vtable created yet */
3492                                         return FALSE;
3493                                 vtable = mono_class_vtable (cfg->domain, method->klass);
3494                                 if (!vtable)
3495                                         return FALSE;
3496                                 /* This makes so that inline cannot trigger */
3497                                 /* .cctors: too many apps depend on them */
3498                                 /* running with a specific order... */
3499                                 if (! vtable->initialized)
3500                                         return FALSE;
3501                                 mono_runtime_class_init (vtable);
3502                         }
3503                 } else if (mono_class_needs_cctor_run (method->klass, NULL)) {
3504                         if (!method->klass->runtime_info)
3505                                 /* No vtable created yet */
3506                                 return FALSE;
3507                         vtable = mono_class_vtable (cfg->domain, method->klass);
3508                         if (!vtable)
3509                                 return FALSE;
3510                         if (!vtable->initialized)
3511                                 return FALSE;
3512                 }
3513         } else {
3514                 /* 
3515                  * If we're compiling for shared code
3516                  * the cctor will need to be run at aot method load time, for example,
3517                  * or at the end of the compilation of the inlining method.
3518                  */
3519                 if (mono_class_needs_cctor_run (method->klass, NULL) && !((method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3520                         return FALSE;
3521         }
3522         //if (!MONO_TYPE_IS_VOID (signature->ret)) return FALSE;
3523
3524         /*
3525          * CAS - do not inline methods with declarative security
3526          * Note: this has to be before any possible return TRUE;
3527          */
3528         if (mono_method_has_declsec (method))
3529                 return FALSE;
3530
3531         return TRUE;
3532 }
3533
3534 static gboolean
3535 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoVTable *vtable)
3536 {
3537         if (vtable->initialized && !cfg->compile_aot)
3538                 return FALSE;
3539
3540         if (vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)
3541                 return FALSE;
3542
3543         if (!mono_class_needs_cctor_run (vtable->klass, method))
3544                 return FALSE;
3545
3546         if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (vtable->klass == method->klass))
3547                 /* The initialization is already done before the method is called */
3548                 return FALSE;
3549
3550         return TRUE;
3551 }
3552
3553 static MonoInst*
3554 mini_get_ldelema_ins (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
3555 {
3556         int temp, rank;
3557         MonoInst *addr;
3558         MonoMethod *addr_method;
3559         int element_size;
3560
3561         rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
3562
3563         if (rank == 1) {
3564                 MONO_INST_NEW (cfg, addr, CEE_LDELEMA);
3565                 addr->inst_left = sp [0];
3566                 addr->inst_right = sp [1];
3567                 addr->type = STACK_MP;
3568                 addr->klass = cmethod->klass->element_class;
3569                 return addr;
3570         }
3571
3572         if (rank == 2 && (cfg->opt & MONO_OPT_INTRINS)) {
3573 #if defined(MONO_ARCH_EMULATE_MUL_DIV) && !defined(MONO_ARCH_NO_EMULATE_MUL)
3574                 /* OP_LDELEMA2D depends on OP_LMUL */
3575 #else
3576                 MonoInst *indexes;
3577                 NEW_GROUP (cfg, indexes, sp [1], sp [2]);
3578                 MONO_INST_NEW (cfg, addr, OP_LDELEMA2D);
3579                 addr->inst_left = sp [0];
3580                 addr->inst_right = indexes;
3581                 addr->type = STACK_MP;
3582                 addr->klass = cmethod->klass->element_class;
3583                 return addr;
3584 #endif
3585         }
3586
3587         element_size = mono_class_array_element_size (cmethod->klass->element_class);
3588         addr_method = mono_marshal_get_array_address (rank, element_size);
3589         temp = mono_emit_method_call_spilled (cfg, bblock, addr_method, addr_method->signature, sp, ip, NULL);
3590         NEW_TEMPLOAD (cfg, addr, temp);
3591         return addr;
3592
3593 }
3594
3595 static MonoJitICallInfo **emul_opcode_map = NULL;
3596
3597 MonoJitICallInfo *
3598 mono_find_jit_opcode_emulation (int opcode)
3599 {
3600         g_assert (opcode >= 0 && opcode <= OP_LAST);
3601         if  (emul_opcode_map)
3602                 return emul_opcode_map [opcode];
3603         else
3604                 return NULL;
3605 }
3606
3607 static MonoInst*
3608 mini_get_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
3609 {
3610         MonoInst *ins = NULL;
3611         
3612         static MonoClass *runtime_helpers_class = NULL;
3613         if (! runtime_helpers_class)
3614                 runtime_helpers_class = mono_class_from_name (mono_defaults.corlib,
3615                         "System.Runtime.CompilerServices", "RuntimeHelpers");
3616
3617         if (cmethod->klass == mono_defaults.string_class) {
3618                 if (strcmp (cmethod->name, "get_Chars") == 0) {
3619                         MONO_INST_NEW (cfg, ins, OP_GETCHR);
3620                         ins->inst_i0 = args [0];
3621                         ins->inst_i1 = args [1];
3622                         return ins;
3623                 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3624                         MONO_INST_NEW (cfg, ins, OP_STRLEN);
3625                         ins->inst_i0 = args [0];
3626                         return ins;
3627                 } else if (strcmp (cmethod->name, "InternalSetChar") == 0) {
3628                         MonoInst *get_addr;
3629                         MONO_INST_NEW (cfg, get_addr, OP_STR_CHAR_ADDR);
3630                         get_addr->inst_i0 = args [0];
3631                         get_addr->inst_i1 = args [1];
3632                         MONO_INST_NEW (cfg, ins, CEE_STIND_I2);
3633                         ins->inst_i0 = get_addr;
3634                         ins->inst_i1 = args [2];
3635                         return ins;
3636                 } else 
3637                         return NULL;
3638         } else if (cmethod->klass == mono_defaults.object_class) {
3639                 if (strcmp (cmethod->name, "GetType") == 0) {
3640                         MONO_INST_NEW (cfg, ins, OP_GETTYPE);
3641                         ins->inst_i0 = args [0];
3642                         return ins;
3643                 /* The OP_GETHASHCODE rule depends on OP_MUL */
3644 #if !defined(MONO_ARCH_EMULATE_MUL_DIV) && !defined(HAVE_MOVING_COLLECTOR)
3645                 } else if (strcmp (cmethod->name, "InternalGetHashCode") == 0) {
3646                         MONO_INST_NEW (cfg, ins, OP_GETHASHCODE);
3647                         ins->inst_i0 = args [0];
3648                         return ins;
3649 #endif
3650                 } else if (strcmp (cmethod->name, ".ctor") == 0) {
3651                         MONO_INST_NEW (cfg, ins, OP_NOP);
3652                         return ins;
3653                 } else
3654                         return NULL;
3655         } else if (cmethod->klass == mono_defaults.array_class) {
3656                 if (cmethod->name [0] != 'g')
3657                         return NULL;
3658
3659                 if (strcmp (cmethod->name, "get_Rank") == 0) {
3660                         MONO_INST_NEW (cfg, ins, OP_ARRAY_RANK);
3661                         ins->inst_i0 = args [0];
3662                         return ins;
3663                 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3664                         MONO_INST_NEW (cfg, ins, CEE_LDLEN);
3665                         ins->inst_i0 = args [0];
3666                         return ins;
3667                 } else
3668                         return NULL;
3669         } else if (cmethod->klass == runtime_helpers_class) {
3670                 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0) {
3671                         NEW_ICONST (cfg, ins, G_STRUCT_OFFSET (MonoString, chars));
3672                         return ins;
3673                 } else
3674                         return NULL;
3675         } else if (cmethod->klass == mono_defaults.thread_class) {
3676                 if (strcmp (cmethod->name, "get_CurrentThread") == 0 && (ins = mono_arch_get_thread_intrinsic (cfg)))
3677                         return ins;
3678                 if (strcmp (cmethod->name, "MemoryBarrier") == 0) {
3679                         MONO_INST_NEW (cfg, ins, OP_MEMORY_BARRIER);
3680                         return ins;
3681                 }
3682         } else if (mini_class_is_system_array (cmethod->klass) &&
3683                         strcmp (cmethod->name, "GetGenericValueImpl") == 0) {
3684                 MonoInst *sp [2];
3685                 MonoInst *ldelem, *store, *load;
3686                 MonoClass *eklass = mono_class_from_mono_type (fsig->params [1]);
3687                 int n;
3688                 n = mini_type_to_stind (cfg, &eklass->byval_arg);
3689                 if (n == CEE_STOBJ)
3690                         return NULL;
3691                 sp [0] = args [0];
3692                 sp [1] = args [1];
3693                 NEW_LDELEMA (cfg, ldelem, sp, eklass);
3694                 ldelem->flags |= MONO_INST_NORANGECHECK;
3695                 MONO_INST_NEW (cfg, store, n);
3696                 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, &eklass->byval_arg));
3697                 type_to_eval_stack_type (cfg, &eklass->byval_arg, load);
3698                 load->inst_left = ldelem;
3699                 store->inst_left = args [2];
3700                 store->inst_right = load;
3701                 return store;
3702         } else if (cmethod->klass == mono_defaults.math_class) {
3703                 /* 
3704                  * There is general branches code for Min/Max, but it does not work for 
3705                  * all inputs:
3706                  * http://everything2.com/?node_id=1051618
3707                  */
3708         } else if (cmethod->klass->image == mono_defaults.corlib &&
3709                            (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
3710                            (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
3711                 ins = NULL;
3712
3713 #if SIZEOF_VOID_P == 8
3714                 if (strcmp (cmethod->name, "Read") == 0 && (fsig->params [0]->type == MONO_TYPE_I8)) {
3715                         /* 64 bit reads are already atomic */
3716                         MONO_INST_NEW (cfg, ins, CEE_LDIND_I8);
3717                         ins->inst_i0 = args [0];
3718                 }
3719 #endif
3720
3721 #ifdef MONO_ARCH_HAVE_ATOMIC_ADD
3722                 if (strcmp (cmethod->name, "Increment") == 0) {
3723                         MonoInst *ins_iconst;
3724                         guint32 opcode;
3725
3726                         if (fsig->params [0]->type == MONO_TYPE_I4)
3727                                 opcode = OP_ATOMIC_ADD_NEW_I4;
3728                         else if (fsig->params [0]->type == MONO_TYPE_I8)
3729                                 opcode = OP_ATOMIC_ADD_NEW_I8;
3730                         else
3731                                 g_assert_not_reached ();
3732
3733 #if SIZEOF_VOID_P == 4
3734                         if (opcode == OP_ATOMIC_ADD_NEW_I8)
3735                                 return NULL;
3736 #endif
3737
3738                         MONO_INST_NEW (cfg, ins, opcode);
3739                         MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
3740                         ins_iconst->inst_c0 = 1;
3741
3742                         ins->inst_i0 = args [0];
3743                         ins->inst_i1 = ins_iconst;
3744                 } else if (strcmp (cmethod->name, "Decrement") == 0) {
3745                         MonoInst *ins_iconst;
3746                         guint32 opcode;
3747
3748                         if (fsig->params [0]->type == MONO_TYPE_I4)
3749                                 opcode = OP_ATOMIC_ADD_NEW_I4;
3750                         else if (fsig->params [0]->type == MONO_TYPE_I8)
3751                                 opcode = OP_ATOMIC_ADD_NEW_I8;
3752                         else
3753                                 g_assert_not_reached ();
3754
3755 #if SIZEOF_VOID_P == 4
3756                         if (opcode == OP_ATOMIC_ADD_NEW_I8)
3757                                 return NULL;
3758 #endif
3759
3760                         MONO_INST_NEW (cfg, ins, opcode);
3761                         MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
3762                         ins_iconst->inst_c0 = -1;
3763
3764                         ins->inst_i0 = args [0];
3765                         ins->inst_i1 = ins_iconst;
3766                 } else if (strcmp (cmethod->name, "Add") == 0) {
3767                         guint32 opcode;
3768
3769                         if (fsig->params [0]->type == MONO_TYPE_I4)
3770                                 opcode = OP_ATOMIC_ADD_NEW_I4;
3771                         else if (fsig->params [0]->type == MONO_TYPE_I8)
3772                                 opcode = OP_ATOMIC_ADD_NEW_I8;
3773                         else
3774                                 g_assert_not_reached ();
3775
3776 #if SIZEOF_VOID_P == 4
3777                         if (opcode == OP_ATOMIC_ADD_NEW_I8)
3778                                 return NULL;
3779 #endif
3780                         
3781                         MONO_INST_NEW (cfg, ins, opcode);
3782
3783                         ins->inst_i0 = args [0];
3784                         ins->inst_i1 = args [1];
3785                 }
3786 #endif /* MONO_ARCH_HAVE_ATOMIC_ADD */
3787
3788 #ifdef MONO_ARCH_HAVE_ATOMIC_EXCHANGE
3789                 if (strcmp (cmethod->name, "Exchange") == 0) {
3790                         guint32 opcode;
3791
3792                         if (fsig->params [0]->type == MONO_TYPE_I4)
3793                                 opcode = OP_ATOMIC_EXCHANGE_I4;
3794 #if SIZEOF_VOID_P == 8
3795                         else if ((fsig->params [0]->type == MONO_TYPE_I8) ||
3796                                          (fsig->params [0]->type == MONO_TYPE_I) ||
3797                                          (fsig->params [0]->type == MONO_TYPE_OBJECT))
3798                                 opcode = OP_ATOMIC_EXCHANGE_I8;
3799 #else
3800                         else if ((fsig->params [0]->type == MONO_TYPE_I) ||
3801                                          (fsig->params [0]->type == MONO_TYPE_OBJECT))
3802                                 opcode = OP_ATOMIC_EXCHANGE_I4;
3803 #endif
3804                         else
3805                                 return NULL;
3806
3807 #if SIZEOF_VOID_P == 4
3808                         if (opcode == OP_ATOMIC_EXCHANGE_I8)
3809                                 return NULL;
3810 #endif
3811
3812                         MONO_INST_NEW (cfg, ins, opcode);
3813
3814                         ins->inst_i0 = args [0];
3815                         ins->inst_i1 = args [1];
3816                 }
3817 #endif /* MONO_ARCH_HAVE_ATOMIC_EXCHANGE */
3818
3819 #ifdef MONO_ARCH_HAVE_ATOMIC_CAS_IMM
3820                 /* 
3821                  * Can't implement CompareExchange methods this way since they have
3822                  * three arguments. We can implement one of the common cases, where the new
3823                  * value is a constant.
3824                  */
3825                 if ((strcmp (cmethod->name, "CompareExchange") == 0)) {
3826                         if (fsig->params [1]->type == MONO_TYPE_I4 && args [2]->opcode == OP_ICONST) {
3827                                 MONO_INST_NEW (cfg, ins, OP_ATOMIC_CAS_IMM_I4);
3828                                 ins->inst_i0 = args [0];
3829                                 ins->inst_i1 = args [1];
3830                                 ins->backend.data = GINT_TO_POINTER (args [2]->inst_c0);
3831                         }
3832                         /* The I8 case is hard to detect, since the arg might be a conv.i8 (iconst) tree */
3833                 }
3834 #endif /* MONO_ARCH_HAVE_ATOMIC_CAS_IMM */
3835
3836                 if (ins)
3837                         return ins;
3838         } else if (cmethod->klass->image == mono_defaults.corlib) {
3839                 if (cmethod->name [0] == 'B' && strcmp (cmethod->name, "Break") == 0
3840                                 && strcmp (cmethod->klass->name, "Debugger") == 0) {
3841                         MONO_INST_NEW (cfg, ins, OP_BREAK);
3842                         return ins;
3843                 }
3844                 if (cmethod->name [0] == 'g' && strcmp (cmethod->name, "get_IsRunningOnWindows") == 0
3845                                 && strcmp (cmethod->klass->name, "Environment") == 0) {
3846 #ifdef PLATFORM_WIN32
3847                         NEW_ICONST (cfg, ins, 1);
3848 #else
3849                         NEW_ICONST (cfg, ins, 0);
3850 #endif
3851                         return ins;
3852                 }
3853         }
3854
3855         return mono_arch_get_inst_for_method (cfg, cmethod, fsig, args);
3856 }
3857
3858 static void
3859 mono_save_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, MonoInst **sp, MonoInst **args)
3860 {
3861         MonoInst *store, *temp;
3862         int i;
3863
3864         g_assert (!MONO_TYPE_ISSTRUCT (sig->ret));
3865
3866         if (!sig->hasthis && sig->param_count == 0) 
3867                 return;
3868
3869         if (sig->hasthis) {
3870                 if (sp [0]->opcode == OP_ICONST) {
3871                         *args++ = sp [0];
3872                 } else {
3873                         temp = mono_compile_create_var (cfg, type_from_stack_type (*sp), OP_LOCAL);
3874                         *args++ = temp;
3875                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3876                         /* FIXME: handle CEE_STIND_R4 */
3877                         store->cil_code = sp [0]->cil_code;
3878                         MONO_ADD_INS (bblock, store);
3879                 }
3880                 sp++;
3881         }
3882
3883         for (i = 0; i < sig->param_count; ++i) {
3884                 if (sp [0]->opcode == OP_ICONST) {
3885                         *args++ = sp [0];
3886                 } else {
3887                         temp = mono_compile_create_var (cfg, sig->params [i], OP_LOCAL);
3888                         *args++ = temp;
3889                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3890                         store->cil_code = sp [0]->cil_code;
3891                         /* FIXME: handle CEE_STIND_R4 */
3892                         if (store->opcode == CEE_STOBJ) {
3893                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
3894                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, temp->klass, FALSE, FALSE, FALSE);
3895 #ifdef MONO_ARCH_SOFT_FLOAT
3896                         } else if (store->opcode == CEE_STIND_R4) {
3897                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
3898                                 handle_store_float (cfg, bblock, store, *sp, sp [0]->cil_code);
3899 #endif
3900                         } else {
3901                                 MONO_ADD_INS (bblock, store);
3902                         } 
3903                 }
3904                 sp++;
3905         }
3906 }
3907 #define MONO_INLINE_CALLED_LIMITED_METHODS 0
3908 #define MONO_INLINE_CALLER_LIMITED_METHODS 0
3909
3910 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
3911 static char*
3912 mono_inline_called_method_name_limit = NULL;
3913 static gboolean check_inline_called_method_name_limit (MonoMethod *called_method) {
3914         char *called_method_name = mono_method_full_name (called_method, TRUE);
3915         int strncmp_result;
3916         
3917         if (mono_inline_called_method_name_limit == NULL) {
3918                 char *limit_string = getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
3919                 if (limit_string != NULL) {
3920                         mono_inline_called_method_name_limit = limit_string;
3921                 } else {
3922                         mono_inline_called_method_name_limit = (char *) "";
3923                 }
3924         }
3925         
3926         strncmp_result = strncmp (called_method_name, mono_inline_called_method_name_limit, strlen (mono_inline_called_method_name_limit));
3927         g_free (called_method_name);
3928         
3929         //return (strncmp_result <= 0);
3930         return (strncmp_result == 0);
3931 }
3932 #endif
3933
3934 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
3935 static char*
3936 mono_inline_caller_method_name_limit = NULL;
3937 static gboolean check_inline_caller_method_name_limit (MonoMethod *caller_method) {
3938         char *caller_method_name = mono_method_full_name (caller_method, TRUE);
3939         int strncmp_result;
3940         
3941         if (mono_inline_caller_method_name_limit == NULL) {
3942                 char *limit_string = getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
3943                 if (limit_string != NULL) {
3944                         mono_inline_caller_method_name_limit = limit_string;
3945                 } else {
3946                         mono_inline_caller_method_name_limit = (char *) "";
3947                 }
3948         }
3949         
3950         strncmp_result = strncmp (caller_method_name, mono_inline_caller_method_name_limit, strlen (mono_inline_caller_method_name_limit));
3951         g_free (caller_method_name);
3952         
3953         //return (strncmp_result <= 0);
3954         return (strncmp_result == 0);
3955 }
3956 #endif
3957
3958 static int
3959 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoBasicBlock *bblock, MonoInst **sp,
3960                 guchar *ip, guint real_offset, GList *dont_inline, MonoBasicBlock **last_b, gboolean inline_allways)
3961 {
3962         MonoInst *ins, *rvar = NULL;
3963         MonoMethodHeader *cheader;
3964         MonoBasicBlock *ebblock, *sbblock;
3965         int i, costs, new_locals_offset;
3966         MonoMethod *prev_inlined_method;
3967         MonoBasicBlock **prev_cil_offset_to_bb;
3968         unsigned char* prev_cil_start;
3969         guint32 prev_cil_offset_to_bb_len;
3970
3971         g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
3972
3973 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
3974         if ((! inline_allways) && ! check_inline_called_method_name_limit (cmethod))
3975                 return 0;
3976 #endif
3977 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
3978         if ((! inline_allways) && ! check_inline_caller_method_name_limit (cfg->method))
3979                 return 0;
3980 #endif
3981
3982         if (bblock->out_of_line && !inline_allways)
3983                 return 0;
3984
3985         if (cfg->verbose_level > 2)
3986                 g_print ("INLINE START %p %s -> %s\n", cmethod,  mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
3987
3988         if (!cmethod->inline_info) {
3989                 mono_jit_stats.inlineable_methods++;
3990                 cmethod->inline_info = 1;
3991         }
3992         /* allocate space to store the return value */
3993         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
3994                 rvar =  mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
3995         }
3996
3997         /* allocate local variables */
3998         cheader = mono_method_get_header (cmethod);
3999         new_locals_offset = cfg->num_varinfo;
4000         for (i = 0; i < cheader->num_locals; ++i)
4001                 mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
4002
4003         /* allocate starte and end blocks */
4004         NEW_BBLOCK (cfg, sbblock);
4005         sbblock->block_num = cfg->num_bblocks++;
4006         sbblock->real_offset = real_offset;
4007
4008         NEW_BBLOCK (cfg, ebblock);
4009         ebblock->block_num = cfg->num_bblocks++;
4010         ebblock->real_offset = real_offset;
4011
4012         prev_inlined_method = cfg->inlined_method;
4013         cfg->inlined_method = cmethod;
4014         prev_cil_offset_to_bb = cfg->cil_offset_to_bb;
4015         prev_cil_offset_to_bb_len = cfg->cil_offset_to_bb_len;
4016         prev_cil_start = cfg->cil_start;
4017
4018         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, new_locals_offset, rvar, dont_inline, sp, real_offset, *ip == CEE_CALLVIRT);
4019
4020         cfg->inlined_method = prev_inlined_method;
4021         cfg->cil_offset_to_bb = prev_cil_offset_to_bb;
4022         cfg->cil_offset_to_bb_len = prev_cil_offset_to_bb_len;
4023         cfg->cil_start = prev_cil_start;
4024
4025         if ((costs >= 0 && costs < 60) || inline_allways) {
4026                 if (cfg->verbose_level > 2)
4027                         g_print ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
4028                 
4029                 mono_jit_stats.inlined_methods++;
4030
4031                 /* always add some code to avoid block split failures */
4032                 MONO_INST_NEW (cfg, ins, OP_NOP);
4033                 MONO_ADD_INS (bblock, ins);
4034                 ins->cil_code = ip;
4035
4036                 bblock->next_bb = sbblock;
4037                 link_bblock (cfg, bblock, sbblock);
4038
4039                 if (rvar) {
4040                         NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
4041                         NEW_TEMPLOAD_SOFT_FLOAT (cfg, ebblock, ins, rvar->inst_c0, ip);
4042                         *sp++ = ins;
4043                 }
4044                 *last_b = ebblock;
4045                 return costs + 1;
4046         } else {
4047                 if (cfg->verbose_level > 2)
4048                         g_print ("INLINE ABORTED %s\n", mono_method_full_name (cmethod, TRUE));
4049                 cfg->exception_type = MONO_EXCEPTION_NONE;
4050                 mono_loader_clear_error ();
4051                 cmethod->inline_failure = TRUE;
4052         }
4053         return 0;
4054 }
4055
4056 /*
4057  * Some of these comments may well be out-of-date.
4058  * Design decisions: we do a single pass over the IL code (and we do bblock 
4059  * splitting/merging in the few cases when it's required: a back jump to an IL
4060  * address that was not already seen as bblock starting point).
4061  * Code is validated as we go (full verification is still better left to metadata/verify.c).
4062  * Complex operations are decomposed in simpler ones right away. We need to let the 
4063  * arch-specific code peek and poke inside this process somehow (except when the 
4064  * optimizations can take advantage of the full semantic info of coarse opcodes).
4065  * All the opcodes of the form opcode.s are 'normalized' to opcode.
4066  * MonoInst->opcode initially is the IL opcode or some simplification of that 
4067  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
4068  * opcode with value bigger than OP_LAST.
4069  * At this point the IR can be handed over to an interpreter, a dumb code generator
4070  * or to the optimizing code generator that will translate it to SSA form.
4071  *
4072  * Profiling directed optimizations.
4073  * We may compile by default with few or no optimizations and instrument the code
4074  * or the user may indicate what methods to optimize the most either in a config file
4075  * or through repeated runs where the compiler applies offline the optimizations to 
4076  * each method and then decides if it was worth it.
4077  *
4078  */
4079
4080 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
4081 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
4082 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
4083 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
4084 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
4085 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
4086 #define CHECK_UNVERIFIABLE(cfg) if (cfg->unverifiable) UNVERIFIED
4087 #define CHECK_TYPELOAD(klass) if (!(klass) || (klass)->exception_type) {cfg->exception_ptr = klass; goto load_error;}
4088
4089 /* offset from br.s -> br like opcodes */
4090 #define BIG_BRANCH_OFFSET 13
4091
4092 static inline gboolean
4093 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
4094 {
4095         MonoBasicBlock *b = cfg->cil_offset_to_bb [ip - cfg->cil_start];
4096         
4097         return b == NULL || b == bb;
4098 }
4099
4100 static int
4101 get_basic_blocks (MonoCompile *cfg, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
4102 {
4103         unsigned char *ip = start;
4104         unsigned char *target;
4105         int i;
4106         guint cli_addr;
4107         MonoBasicBlock *bblock;
4108         const MonoOpcode *opcode;
4109
4110         while (ip < end) {
4111                 cli_addr = ip - start;
4112                 i = mono_opcode_value ((const guint8 **)&ip, end);
4113                 if (i < 0)
4114                         UNVERIFIED;
4115                 opcode = &mono_opcodes [i];
4116                 switch (opcode->argument) {
4117                 case MonoInlineNone:
4118                         ip++; 
4119                         break;
4120                 case MonoInlineString:
4121                 case MonoInlineType:
4122                 case MonoInlineField:
4123                 case MonoInlineMethod:
4124                 case MonoInlineTok:
4125                 case MonoInlineSig:
4126                 case MonoShortInlineR:
4127                 case MonoInlineI:
4128                         ip += 5;
4129                         break;
4130                 case MonoInlineVar:
4131                         ip += 3;
4132                         break;
4133                 case MonoShortInlineVar:
4134                 case MonoShortInlineI:
4135                         ip += 2;
4136                         break;
4137                 case MonoShortInlineBrTarget:
4138                         target = start + cli_addr + 2 + (signed char)ip [1];
4139                         GET_BBLOCK (cfg, bblock, target);
4140                         ip += 2;
4141                         if (ip < end)
4142                                 GET_BBLOCK (cfg, bblock, ip);
4143                         break;
4144                 case MonoInlineBrTarget:
4145                         target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
4146                         GET_BBLOCK (cfg, bblock, target);
4147                         ip += 5;
4148                         if (ip < end)
4149                                 GET_BBLOCK (cfg, bblock, ip);
4150                         break;
4151                 case MonoInlineSwitch: {
4152                         guint32 n = read32 (ip + 1);
4153                         guint32 j;
4154                         ip += 5;
4155                         cli_addr += 5 + 4 * n;
4156                         target = start + cli_addr;
4157                         GET_BBLOCK (cfg, bblock, target);
4158                         
4159                         for (j = 0; j < n; ++j) {
4160                                 target = start + cli_addr + (gint32)read32 (ip);
4161                                 GET_BBLOCK (cfg, bblock, target);
4162                                 ip += 4;
4163                         }
4164                         break;
4165                 }
4166                 case MonoInlineR:
4167                 case MonoInlineI8:
4168                         ip += 9;
4169                         break;
4170                 default:
4171                         g_assert_not_reached ();
4172                 }
4173
4174                 if (i == CEE_THROW) {
4175                         unsigned char *bb_start = ip - 1;
4176                         
4177                         /* Find the start of the bblock containing the throw */
4178                         bblock = NULL;
4179                         while ((bb_start >= start) && !bblock) {
4180                                 bblock = cfg->cil_offset_to_bb [(bb_start) - start];
4181                                 bb_start --;
4182                         }
4183                         if (bblock)
4184                                 bblock->out_of_line = 1;
4185                 }
4186         }
4187         return 0;
4188 unverified:
4189         *pos = ip;
4190         return 1;
4191 }
4192
4193 static MonoInst*
4194 emit_tree (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ins, const guint8* ip_next)
4195 {
4196         MonoInst *store, *temp, *load;
4197         
4198         if (ip_in_bb (cfg, bblock, ip_next) &&
4199                 (CODE_IS_STLOC (ip_next) || *ip_next == CEE_RET))
4200                         return ins;
4201         
4202         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
4203         temp->flags |= MONO_INST_IS_TEMP;
4204         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
4205         /* FIXME: handle CEE_STIND_R4 */
4206         store->cil_code = ins->cil_code;
4207         MONO_ADD_INS (bblock, store);
4208         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
4209         load->cil_code = ins->cil_code;
4210         return load;
4211 }
4212
4213 static inline MonoMethod *
4214 mini_get_method_allow_open (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
4215 {
4216         MonoMethod *method;
4217
4218         if (m->wrapper_type != MONO_WRAPPER_NONE)
4219                 return mono_method_get_wrapper_data (m, token);
4220
4221         method = mono_get_method_full (m->klass->image, token, klass, context);
4222
4223         return method;
4224 }
4225
4226 static inline MonoMethod *
4227 mini_get_method (MonoCompile *cfg, MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
4228 {
4229         MonoMethod *method = mini_get_method_allow_open (m, token, klass, context);
4230
4231         if (method && cfg && !cfg->generic_sharing_context && mono_class_is_open_constructed_type (&method->klass->byval_arg))
4232                 return NULL;
4233
4234         return method;
4235 }
4236
4237 static inline MonoClass*
4238 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
4239 {
4240         MonoClass *klass;
4241
4242         if (method->wrapper_type != MONO_WRAPPER_NONE)
4243                 klass = mono_method_get_wrapper_data (method, token);
4244         else
4245                 klass = mono_class_get_full (method->klass->image, token, context);
4246         if (klass)
4247                 mono_class_init (klass);
4248         return klass;
4249 }
4250
4251 /*
4252  * Returns TRUE if the JIT should abort inlining because "callee"
4253  * is influenced by security attributes.
4254  */
4255 static
4256 gboolean check_linkdemand (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee, MonoBasicBlock *bblock, unsigned char *ip)
4257 {
4258         guint32 result;
4259         
4260         if ((cfg->method != caller) && mono_method_has_declsec (callee)) {
4261                 return TRUE;
4262         }
4263         
4264         result = mono_declsec_linkdemand (cfg->domain, caller, callee);
4265         if (result == MONO_JIT_SECURITY_OK)
4266                 return FALSE;
4267
4268         if (result == MONO_JIT_LINKDEMAND_ECMA) {
4269                 /* Generate code to throw a SecurityException before the actual call/link */
4270                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4271                 MonoInst *args [2];
4272
4273                 NEW_ICONST (cfg, args [0], 4);
4274                 NEW_METHODCONST (cfg, args [1], caller);
4275                 mono_emit_method_call_spilled (cfg, bblock, secman->linkdemandsecurityexception, mono_method_signature (secman->linkdemandsecurityexception), args, ip, NULL);
4276         } else if (cfg->exception_type == MONO_EXCEPTION_NONE) {
4277                  /* don't hide previous results */
4278                 cfg->exception_type = MONO_EXCEPTION_SECURITY_LINKDEMAND;
4279                 cfg->exception_data = result;
4280                 return TRUE;
4281         }
4282         
4283         return FALSE;
4284 }
4285
4286 static MonoMethod*
4287 method_access_exception (void)
4288 {
4289         static MonoMethod *method = NULL;
4290
4291         if (!method) {
4292                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4293                 method = mono_class_get_method_from_name (secman->securitymanager,
4294                                                           "MethodAccessException", 2);
4295         }
4296         g_assert (method);
4297         return method;
4298 }
4299
4300 static void
4301 emit_throw_method_access_exception (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee,
4302                                     MonoBasicBlock *bblock, unsigned char *ip)
4303 {
4304         MonoMethod *thrower = method_access_exception ();
4305         MonoInst *args [2];
4306
4307         NEW_METHODCONST (cfg, args [0], caller);
4308         NEW_METHODCONST (cfg, args [1], callee);
4309         mono_emit_method_call_spilled (cfg, bblock, thrower,
4310                 mono_method_signature (thrower), args, ip, NULL);
4311 }
4312
4313 static MonoMethod*
4314 verification_exception (void)
4315 {
4316         static MonoMethod *method = NULL;
4317
4318         if (!method) {
4319                 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4320                 method = mono_class_get_method_from_name (secman->securitymanager,
4321                                                           "VerificationException", 0);
4322         }
4323         g_assert (method);
4324         return method;
4325 }
4326
4327 static void
4328 emit_throw_verification_exception (MonoCompile *cfg, MonoBasicBlock *bblock, unsigned char *ip)
4329 {
4330         MonoMethod *thrower = verification_exception ();
4331
4332         mono_emit_method_call_spilled (cfg, bblock, thrower,
4333                 mono_method_signature (thrower),
4334                 NULL, ip, NULL);
4335 }
4336
4337 static void
4338 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee,
4339                                          MonoBasicBlock *bblock, unsigned char *ip)
4340 {
4341         MonoSecurityCoreCLRLevel caller_level = mono_security_core_clr_method_level (caller, TRUE);
4342         MonoSecurityCoreCLRLevel callee_level = mono_security_core_clr_method_level (callee, TRUE);
4343         gboolean is_safe = TRUE;
4344
4345         if (!(caller_level >= callee_level ||
4346                         caller_level == MONO_SECURITY_CORE_CLR_SAFE_CRITICAL ||
4347                         callee_level == MONO_SECURITY_CORE_CLR_SAFE_CRITICAL)) {
4348                 is_safe = FALSE;
4349         }
4350
4351         if (!is_safe)
4352                 emit_throw_method_access_exception (cfg, caller, callee, bblock, ip);
4353 }
4354
4355 static gboolean
4356 method_is_safe (MonoMethod *method)
4357 {
4358         /*
4359         if (strcmp (method->name, "unsafeMethod") == 0)
4360                 return FALSE;
4361         */
4362         return TRUE;
4363 }
4364
4365 /*
4366  * Check that the IL instructions at ip are the array initialization
4367  * sequence and return the pointer to the data and the size.
4368  */
4369 static const char*
4370 initialize_array_data (MonoMethod *method, gboolean aot, unsigned char *ip, MonoInst *newarr, int *out_size)
4371 {
4372         /*
4373          * newarr[System.Int32]
4374          * dup
4375          * ldtoken field valuetype ...
4376          * call void class [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
4377          */
4378         if (ip [0] == CEE_DUP && ip [1] == CEE_LDTOKEN && ip [5] == 0x4 && ip [6] == CEE_CALL) {
4379                 MonoClass *klass = newarr->inst_newa_class;
4380                 guint32 field_token = read32 (ip + 2);
4381                 guint32 field_index = field_token & 0xffffff;
4382                 guint32 token = read32 (ip + 7);
4383                 guint32 rva;
4384                 const char *data_ptr;
4385                 int size = 0;
4386                 MonoMethod *cmethod;
4387                 MonoClass *dummy_class;
4388                 MonoClassField *field = mono_field_from_token (method->klass->image, field_token, &dummy_class, NULL);
4389                 int dummy_align;
4390
4391                 if (!field)
4392                         return NULL;
4393
4394                 if (newarr->inst_newa_len->opcode != OP_ICONST)
4395                         return NULL;
4396                 cmethod = mini_get_method (NULL, method, token, NULL, NULL);
4397                 if (!cmethod)
4398                         return NULL;
4399                 if (strcmp (cmethod->name, "InitializeArray") || strcmp (cmethod->klass->name, "RuntimeHelpers") || cmethod->klass->image != mono_defaults.corlib)
4400                         return NULL;
4401                 switch (mono_type_get_underlying_type (&klass->byval_arg)->type) {
4402                 case MONO_TYPE_BOOLEAN:
4403                 case MONO_TYPE_I1:
4404                 case MONO_TYPE_U1:
4405                         size = 1; break;
4406                 /* we need to swap on big endian, so punt. Should we handle R4 and R8 as well? */
4407 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
4408                 case MONO_TYPE_CHAR:
4409                 case MONO_TYPE_I2:
4410                 case MONO_TYPE_U2:
4411                         size = 2; break;
4412                 case MONO_TYPE_I4:
4413                 case MONO_TYPE_U4:
4414                 case MONO_TYPE_R4:
4415                         size = 4; break;
4416                 case MONO_TYPE_R8:
4417 #ifdef ARM_FPU_FPA
4418                         return NULL; /* stupid ARM FP swapped format */
4419 #endif
4420                 case MONO_TYPE_I8:
4421                 case MONO_TYPE_U8:
4422                         size = 8; break;
4423 #endif
4424                 default:
4425                         return NULL;
4426                 }
4427                 size *= newarr->inst_newa_len->inst_c0;
4428                 if (size > mono_type_size (field->type, &dummy_align))
4429                     return NULL;
4430                 *out_size = size;
4431                 /*g_print ("optimized in %s: size: %d, numelems: %d\n", method->name, size, newarr->inst_newa_len->inst_c0);*/
4432                 field_index = read32 (ip + 2) & 0xffffff;
4433                 mono_metadata_field_info (method->klass->image, field_index - 1, NULL, &rva, NULL);
4434                 data_ptr = mono_image_rva_map (method->klass->image, rva);
4435                 /*g_print ("field: 0x%08x, rva: %d, rva_ptr: %p\n", read32 (ip + 2), rva, data_ptr);*/
4436                 /* for aot code we do the lookup on load */
4437                 if (aot && data_ptr)
4438                         return GUINT_TO_POINTER (rva);
4439                 return data_ptr;
4440         }
4441         return NULL;
4442 }
4443
4444 static void
4445 set_exception_type_from_invalid_il (MonoCompile *cfg, MonoMethod *method, unsigned char *ip)
4446 {
4447         char *method_fname = mono_method_full_name (method, TRUE);
4448         char *method_code;
4449
4450         if (mono_method_get_header (method)->code_size == 0)
4451                 method_code = g_strdup ("method body is empty.");
4452         else
4453                 method_code = mono_disasm_code_one (NULL, method, ip, NULL);
4454         cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
4455         cfg->exception_message = g_strdup_printf ("Invalid IL code in %s: %s\n", method_fname, method_code);
4456         g_free (method_fname);
4457         g_free (method_code);
4458 }
4459
4460 static MonoInst*
4461 get_runtime_generic_context (MonoCompile *cfg, MonoMethod *method, int context_used, MonoInst *this, unsigned char *ip)
4462 {
4463         g_assert (!method->klass->valuetype);
4464
4465         if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD) {
4466                 MonoInst *mrgctx_loc, *mrgctx_var;
4467
4468                 g_assert (!this);
4469                 g_assert (method->is_inflated && mono_method_get_context (method)->method_inst);
4470
4471                 mrgctx_loc = mono_get_vtable_var (cfg);
4472                 NEW_TEMPLOAD (cfg, mrgctx_var, mrgctx_loc->inst_c0);
4473
4474                 return mrgctx_var;
4475         } else if (method->flags & METHOD_ATTRIBUTE_STATIC) {
4476                 MonoInst *vtable_loc, *vtable_var;
4477
4478                 g_assert (!this);
4479
4480                 vtable_loc = mono_get_vtable_var (cfg);
4481                 NEW_TEMPLOAD (cfg, vtable_var, vtable_loc->inst_c0);
4482
4483                 if (method->is_inflated && mono_method_get_context (method)->method_inst) {
4484                         MonoInst *mrgctx_var = vtable_var;
4485
4486                         g_assert (G_STRUCT_OFFSET (MonoMethodRuntimeGenericContext, class_vtable) == 0);
4487
4488                         MONO_INST_NEW (cfg, vtable_var, CEE_LDIND_I);
4489                         vtable_var->cil_code = ip;
4490                         vtable_var->inst_left = mrgctx_var;
4491                         vtable_var->type = STACK_PTR;
4492                 }
4493
4494                 return vtable_var;
4495         } else {
4496                 MonoInst *vtable;
4497
4498                 g_assert (this);
4499
4500                 MONO_INST_NEW (cfg, vtable, CEE_LDIND_I);
4501                 vtable->inst_left = this;
4502                 vtable->type = STACK_PTR;
4503
4504                 return vtable;
4505         }
4506 }
4507
4508 static gpointer
4509 create_rgctx_lazy_fetch_trampoline (guint32 offset)
4510 {
4511         static gboolean inited = FALSE;
4512         static int num_trampolines = 0;
4513
4514         gpointer tramp, ptr;
4515
4516         mono_jit_lock ();
4517         if (rgctx_lazy_fetch_trampoline_hash)
4518                 tramp = g_hash_table_lookup (rgctx_lazy_fetch_trampoline_hash, GUINT_TO_POINTER (offset));
4519         else
4520                 tramp = NULL;
4521         mono_jit_unlock ();
4522         if (tramp)
4523                 return tramp;
4524
4525         tramp = mono_arch_create_rgctx_lazy_fetch_trampoline (offset);
4526         ptr = mono_create_ftnptr (mono_get_root_domain (), tramp);
4527
4528         mono_jit_lock ();
4529         if (!rgctx_lazy_fetch_trampoline_hash)
4530                 rgctx_lazy_fetch_trampoline_hash = g_hash_table_new (NULL, NULL);
4531         g_hash_table_insert (rgctx_lazy_fetch_trampoline_hash, GUINT_TO_POINTER (offset), ptr);
4532         mono_jit_unlock ();
4533
4534         if (!inited) {
4535                 mono_counters_register ("RGCTX num lazy fetch trampolines",
4536                                 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &num_trampolines);
4537                 inited = TRUE;
4538         }
4539         num_trampolines++;
4540
4541         return ptr;
4542 }
4543
4544 static MonoInst*
4545 get_runtime_generic_context_other_table_ptr (MonoCompile *cfg, MonoBasicBlock *bblock,
4546         MonoInst *rgc_ptr, guint32 slot, const unsigned char *ip)
4547 {
4548         MonoMethodSignature *sig = helper_sig_rgctx_lazy_fetch_trampoline;
4549         guint8 *tramp = create_rgctx_lazy_fetch_trampoline (slot);
4550         int temp;
4551         MonoInst *field;
4552
4553         temp = mono_emit_native_call (cfg, bblock, tramp, sig, &rgc_ptr, ip, FALSE, FALSE);
4554
4555         NEW_TEMPLOAD (cfg, field, temp);
4556
4557         return field;
4558 }
4559
4560 static MonoInst*
4561 get_runtime_generic_context_ptr (MonoCompile *cfg, MonoMethod *method, int context_used, MonoBasicBlock *bblock,
4562         MonoClass *klass, MonoGenericContext *generic_context, MonoInst *rgctx, int rgctx_type, unsigned char *ip)
4563 {
4564         guint32 slot = mono_method_lookup_or_register_other_info (method,
4565                 context_used & MONO_GENERIC_CONTEXT_USED_METHOD, &klass->byval_arg, rgctx_type, generic_context);
4566
4567         return get_runtime_generic_context_other_table_ptr (cfg, bblock, rgctx, slot, ip);
4568 }
4569
4570 static MonoInst*
4571 get_runtime_generic_context_method (MonoCompile *cfg, MonoMethod *method, int context_used, MonoBasicBlock *bblock,
4572         MonoMethod *cmethod, MonoGenericContext *generic_context, MonoInst *rgctx, int rgctx_type, const unsigned char *ip)
4573 {
4574         guint32 slot = mono_method_lookup_or_register_other_info (method,
4575                 context_used & MONO_GENERIC_CONTEXT_USED_METHOD, cmethod, rgctx_type, generic_context);
4576
4577         return get_runtime_generic_context_other_table_ptr (cfg, bblock, rgctx, slot, ip);
4578 }
4579
4580 static MonoInst*
4581 get_runtime_generic_context_field (MonoCompile *cfg, MonoMethod *method, int context_used, MonoBasicBlock *bblock,
4582         MonoClassField *field, MonoGenericContext *generic_context, MonoInst *rgctx, int rgctx_type,
4583         const unsigned char *ip)
4584 {
4585         guint32 slot = mono_method_lookup_or_register_other_info (method,
4586                 context_used & MONO_GENERIC_CONTEXT_USED_METHOD, field, rgctx_type, generic_context);
4587
4588         return get_runtime_generic_context_other_table_ptr (cfg, bblock, rgctx, slot, ip);
4589 }
4590
4591 static MonoInst*
4592 get_runtime_generic_context_method_rgctx (MonoCompile *cfg, MonoMethod *method, int context_used, MonoBasicBlock *bblock,
4593         MonoMethod *rgctx_method, MonoGenericContext *generic_context, MonoInst *rgctx, const unsigned char *ip)
4594 {
4595         guint32 slot = mono_method_lookup_or_register_other_info (method,
4596                 context_used & MONO_GENERIC_CONTEXT_USED_METHOD, rgctx_method,
4597                 MONO_RGCTX_INFO_METHOD_RGCTX, generic_context);
4598
4599         return get_runtime_generic_context_other_table_ptr (cfg, bblock, rgctx, slot, ip);
4600 }
4601
4602 static gboolean
4603 generic_class_is_reference_type (MonoCompile *cfg, MonoClass *klass)
4604 {
4605         MonoType *type;
4606
4607         if (cfg->generic_sharing_context)
4608                 type = mini_get_basic_type_from_generic (cfg->generic_sharing_context, &klass->byval_arg);
4609         else
4610                 type = &klass->byval_arg;
4611         return MONO_TYPE_IS_REFERENCE (type);
4612 }
4613
4614 /**
4615  * Handles unbox of a Nullable<T>, returning a temp variable where the
4616  * result is stored.  If a rgctx is passed, then shared generic code
4617  * is generated.
4618  */
4619 static int
4620 handle_unbox_nullable (MonoCompile* cfg, MonoMethod *caller_method, int context_used, MonoBasicBlock* bblock,
4621         MonoInst* val, const guchar *ip, MonoClass* klass, MonoGenericContext *generic_context, MonoInst *rgctx)
4622 {
4623         MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
4624         MonoMethodSignature *signature = mono_method_signature (method);
4625
4626         if (rgctx) {
4627                 MonoInst *addr = get_runtime_generic_context_method (cfg, caller_method, context_used, bblock, method,
4628                         generic_context, rgctx, MONO_RGCTX_INFO_GENERIC_METHOD_CODE, ip);
4629
4630                 return mono_emit_rgctx_calli_spilled (cfg, bblock, signature, &val, addr, NULL, ip);
4631         } else {
4632                 return mono_emit_method_call_spilled (cfg, bblock, method, signature, &val, ip, NULL);
4633         }
4634 }
4635
4636 static MonoInst*
4637 handle_box_nullable_from_inst (MonoCompile *cfg, MonoMethod *caller_method, int context_used, MonoBasicBlock *bblock,
4638         MonoInst *val, const guchar *ip, MonoClass *klass, MonoGenericContext *generic_context, MonoInst *rgctx)
4639 {
4640         MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
4641         MonoInst *dest, *method_addr;
4642         int temp;
4643
4644         g_assert (mono_class_is_nullable (klass));
4645
4646         method_addr = get_runtime_generic_context_method (cfg, caller_method, context_used, bblock, method,
4647                         generic_context, rgctx, MONO_RGCTX_INFO_GENERIC_METHOD_CODE, ip);
4648         temp = mono_emit_rgctx_calli_spilled (cfg, bblock, mono_method_signature (method), &val,
4649                         method_addr, NULL, ip);
4650         NEW_TEMPLOAD (cfg, dest, temp);
4651         return dest;
4652 }
4653
4654 static MonoObject*
4655 mono_object_castclass (MonoObject *obj, MonoClass *klass)
4656 {
4657         if (!obj)
4658                 return NULL;
4659
4660         if (mono_object_isinst (obj, klass))
4661                 return obj;
4662
4663         mono_raise_exception (mono_exception_from_name (mono_defaults.corlib,
4664                                         "System", "InvalidCastException"));
4665
4666         return NULL;
4667 }
4668
4669 static int
4670 emit_castclass (MonoClass *klass, guint32 token, int context_used, gboolean inst_is_castclass, MonoCompile *cfg,
4671                 MonoMethod *method, MonoInst **arg_array, MonoType **param_types, GList *dont_inline,
4672                 unsigned char *end, MonoMethodHeader *header, MonoGenericContext *generic_context,
4673                 MonoBasicBlock **_bblock, unsigned char **_ip, MonoInst ***_sp, int *_inline_costs, guint *_real_offset)
4674 {
4675         MonoBasicBlock *bblock = *_bblock;
4676         unsigned char *ip = *_ip;
4677         MonoInst **sp = *_sp;
4678         int inline_costs = *_inline_costs;
4679         guint real_offset = *_real_offset;
4680         int return_value = 0;
4681
4682         if (context_used) {
4683                 MonoInst *rgctx, *args [2];
4684                 int temp;
4685
4686                 g_assert (!method->klass->valuetype);
4687
4688                 /* obj */
4689                 args [0] = *sp;
4690
4691                 /* klass */
4692                 GET_RGCTX (rgctx, context_used);
4693                 args [1] = get_runtime_generic_context_ptr (cfg, method, context_used, bblock, klass,
4694                                 generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
4695
4696                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_castclass, args, ip);
4697                 NEW_TEMPLOAD (cfg, *sp, temp);
4698
4699                 sp++;
4700                 ip += 5;
4701                 inline_costs += 2;
4702         } else if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4703
4704                 MonoMethod *mono_castclass;
4705                 MonoInst *iargs [1];
4706                 MonoBasicBlock *ebblock;
4707                 int costs;
4708                 int temp;
4709
4710                 mono_castclass = mono_marshal_get_castclass (klass);
4711                 iargs [0] = sp [0];
4712
4713                 costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), bblock,
4714                                 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
4715
4716                 g_assert (costs > 0);
4717
4718                 ip += 5;
4719                 real_offset += 5;
4720
4721                 GET_BBLOCK (cfg, bblock, ip);
4722                 ebblock->next_bb = bblock;
4723                 link_bblock (cfg, ebblock, bblock);
4724
4725                 temp = iargs [0]->inst_i0->inst_c0;
4726                 NEW_TEMPLOAD (cfg, *sp, temp);
4727
4728                 sp++;
4729                 bblock = ebblock;
4730                 inline_costs += costs;
4731         } else {
4732                 MonoInst *ins;
4733
4734                 /* Needed by the code generated in inssel.brg */
4735                 mono_get_got_var (cfg);
4736
4737                 MONO_INST_NEW (cfg, ins, CEE_CASTCLASS);
4738                 ins->type = STACK_OBJ;
4739                 ins->inst_left = *sp;
4740                 ins->klass = klass;
4741                 ins->inst_newa_class = klass;
4742                 if (inst_is_castclass)
4743                         ins->backend.record_cast_details = debug_options.better_cast_details;
4744                 if (inst_is_castclass)
4745                         *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
4746                 else
4747                         *sp++ = ins;
4748                 ip += 5;
4749         }
4750
4751 do_return:
4752         *_bblock = bblock;
4753         *_ip = ip;
4754         *_sp = sp;
4755         *_inline_costs = inline_costs;
4756         *_real_offset = real_offset;
4757         return return_value;
4758 exception_exit:
4759         return_value = -2;
4760         goto do_return;
4761 unverified:
4762         return_value = -1;
4763         goto do_return;
4764 }
4765
4766 static int
4767 emit_unbox (MonoClass *klass, guint32 token, int context_used,
4768                 MonoCompile *cfg, MonoMethod *method, MonoInst **arg_array, MonoType **param_types, GList *dont_inline,
4769                 unsigned char *end, MonoMethodHeader *header, MonoGenericContext *generic_context,
4770                 MonoBasicBlock **_bblock, unsigned char **_ip, MonoInst ***_sp, int *_inline_costs, guint *_real_offset)
4771 {
4772         MonoBasicBlock *bblock = *_bblock;
4773         unsigned char *ip = *_ip;
4774         MonoInst **sp = *_sp;
4775         int inline_costs = *_inline_costs;
4776         guint real_offset = *_real_offset;
4777         int return_value = 0;
4778
4779         MonoInst *add, *vtoffset, *ins;
4780
4781         /* Needed by the code generated in inssel.brg */
4782         mono_get_got_var (cfg);
4783
4784         if (context_used) {
4785                 MonoInst *rgctx, *element_class;
4786
4787                 /* This assertion is from the unboxcast insn */
4788                 g_assert (klass->rank == 0);
4789
4790                 GET_RGCTX (rgctx, context_used);
4791                 element_class = get_runtime_generic_context_ptr (cfg, method, context_used, bblock,
4792                                 klass->element_class, generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
4793
4794                 MONO_INST_NEW (cfg, ins, OP_UNBOXCAST_REG);
4795                 ins->type = STACK_OBJ;
4796                 ins->inst_left = *sp;
4797                 ins->inst_right = element_class;
4798                 ins->klass = klass;
4799                 ins->cil_code = ip;
4800         } else {
4801                 MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
4802                 ins->type = STACK_OBJ;
4803                 ins->inst_left = *sp;
4804                 ins->klass = klass;
4805                 ins->inst_newa_class = klass;
4806                 ins->cil_code = ip;
4807         }
4808
4809         MONO_INST_NEW (cfg, add, OP_PADD);
4810         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
4811         add->inst_left = ins;
4812         add->inst_right = vtoffset;
4813         add->type = STACK_MP;
4814         add->klass = klass;
4815         *sp = add;
4816
4817 do_return:
4818         *_bblock = bblock;
4819         *_ip = ip;
4820         *_sp = sp;
4821         *_inline_costs = inline_costs;
4822         *_real_offset = real_offset;
4823         return return_value;
4824 exception_exit:
4825         return_value = -2;
4826         goto do_return;
4827 }
4828
4829 static gboolean
4830 mini_assembly_can_skip_verification (MonoDomain *domain, MonoMethod *method)
4831 {
4832         MonoAssembly *assembly = method->klass->image->assembly;
4833         if (method->wrapper_type != MONO_WRAPPER_NONE)
4834                 return FALSE;
4835         if (assembly->in_gac || assembly->image == mono_defaults.corlib)
4836                 return FALSE;
4837         if (mono_security_get_mode () != MONO_SECURITY_MODE_NONE)
4838                 return FALSE;
4839         return mono_assembly_has_skip_verification (assembly);
4840 }
4841
4842 /*
4843  * mini_method_verify:
4844  * 
4845  * Verify the method using the new verfier.
4846  * 
4847  * Returns true if the method is invalid. 
4848  */
4849 static gboolean
4850 mini_method_verify (MonoCompile *cfg, MonoMethod *method)
4851 {
4852         GSList *tmp, *res;
4853         gboolean is_fulltrust;
4854         MonoLoaderError *error;
4855
4856         if (method->verification_success)
4857                 return FALSE;
4858
4859         is_fulltrust = mono_verifier_is_method_full_trust (method);
4860
4861         if (!mono_verifier_is_enabled_for_method (method))
4862                 return FALSE;
4863
4864         res = mono_method_verify_with_current_settings (method, cfg->skip_visibility);
4865
4866         if ((error = mono_loader_get_last_error ())) {
4867                 cfg->exception_type = error->exception_type;
4868                 if (res)
4869                         mono_free_verify_list (res);
4870                 return TRUE;
4871         }
4872
4873         if (res) { 
4874                 for (tmp = res; tmp; tmp = tmp->next) {
4875                         MonoVerifyInfoExtended *info = (MonoVerifyInfoExtended *)tmp->data;
4876                         if (info->info.status == MONO_VERIFY_ERROR) {
4877                                 cfg->exception_type = info->exception_type;
4878                                 cfg->exception_message = g_strdup (info->info.message);
4879                                 mono_free_verify_list (res);
4880                                 return TRUE;
4881                         }
4882                         if (info->info.status == MONO_VERIFY_NOT_VERIFIABLE && !is_fulltrust) {
4883                                 cfg->exception_type = info->exception_type;
4884                                 cfg->exception_message = g_strdup (info->info.message);
4885                                 mono_free_verify_list (res);
4886                                 return TRUE;
4887                         }
4888                 }
4889                 mono_free_verify_list (res);
4890         }
4891         method->verification_success = 1;
4892         return FALSE;
4893 }
4894
4895 /*
4896  * mono_method_to_ir: translates IL into basic blocks containing trees
4897  */
4898 static int
4899 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
4900                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
4901                    guint inline_offset, gboolean is_virtual_call)
4902 {
4903         MonoInst *zero_int32, *zero_int64, *zero_ptr, *zero_obj, *zero_r8;
4904         MonoInst *ins, **sp, **stack_start;
4905         MonoBasicBlock *bblock, *tblock = NULL, *init_localsbb = NULL;
4906         MonoMethod *cmethod, *method_definition;
4907         MonoInst **arg_array;
4908         MonoMethodHeader *header;
4909         MonoImage *image;
4910         guint32 token, ins_flag;
4911         MonoClass *klass;
4912         MonoClass *constrained_call = NULL;
4913         unsigned char *ip, *end, *target, *err_pos;
4914         static double r8_0 = 0.0;
4915         MonoMethodSignature *sig;
4916         MonoGenericContext *generic_context = NULL;
4917         MonoGenericContainer *generic_container = NULL;
4918         MonoType **param_types;
4919         GList *bb_recheck = NULL, *tmp;
4920         int i, n, start_new_bblock, ialign;
4921         int num_calls = 0, inline_costs = 0;
4922         int breakpoint_id = 0;
4923         guint32 align;
4924         guint real_offset, num_args;
4925         MonoBoolean security, pinvoke;
4926         MonoSecurityManager* secman = NULL;
4927         MonoDeclSecurityActions actions;
4928         GSList *class_inits = NULL;
4929         gboolean dont_verify, dont_verify_stloc, readonly = FALSE;
4930         int context_used;
4931
4932         /* serialization and xdomain stuff may need access to private fields and methods */
4933         dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
4934         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
4935         dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
4936         dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
4937         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP;
4938         dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP_INVOKE;
4939
4940         /* turn off visibility checks for smcs */
4941         dont_verify |= mono_security_get_mode () == MONO_SECURITY_MODE_SMCS_HACK;
4942
4943         /* still some type unsafety issues in marshal wrappers... (unknown is PtrToStructure) */
4944         dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
4945         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
4946         dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
4947
4948         image = method->klass->image;
4949         header = mono_method_get_header (method);
4950         generic_container = mono_method_get_generic_container (method);
4951         sig = mono_method_signature (method);
4952         num_args = sig->hasthis + sig->param_count;
4953         ip = (unsigned char*)header->code;
4954         cfg->cil_start = ip;
4955         end = ip + header->code_size;
4956         mono_jit_stats.cil_code_size += header->code_size;
4957
4958         method_definition = method;
4959         while (method_definition->is_inflated) {
4960                 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
4961                 method_definition = imethod->declaring;
4962         }
4963
4964         /* SkipVerification is not allowed if core-clr is enabled */
4965         if (!dont_verify && mini_assembly_can_skip_verification (cfg->domain, method)) {
4966                 dont_verify = TRUE;
4967                 dont_verify_stloc = TRUE;
4968         }
4969
4970         if (!dont_verify && mini_method_verify (cfg, method_definition))
4971                 goto exception_exit;
4972
4973         if (sig->is_inflated)
4974                 generic_context = mono_method_get_context (method);
4975         else if (generic_container)
4976                 generic_context = &generic_container->context;
4977
4978         if (!cfg->generic_sharing_context)
4979                 g_assert (!sig->has_type_parameters);
4980
4981         if (sig->generic_param_count && method->wrapper_type == MONO_WRAPPER_NONE) {
4982                 g_assert (method->is_inflated);
4983                 g_assert (mono_method_get_context (method)->method_inst);
4984         }
4985         if (method->is_inflated && mono_method_get_context (method)->method_inst)
4986                 g_assert (sig->generic_param_count);
4987
4988         if (cfg->method == method)
4989                 real_offset = 0;
4990         else
4991                 real_offset = inline_offset;
4992
4993         cfg->cil_offset_to_bb = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * header->code_size);
4994         cfg->cil_offset_to_bb_len = header->code_size;
4995
4996         if (cfg->verbose_level > 2)
4997                 g_print ("method to IR %s\n", mono_method_full_name (method, TRUE));
4998
4999         dont_inline = g_list_prepend (dont_inline, method);
5000         if (cfg->method == method) {
5001
5002                 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
5003                         cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
5004
5005                 /* ENTRY BLOCK */
5006                 NEW_BBLOCK (cfg, start_bblock);
5007                 cfg->bb_entry = start_bblock;
5008                 start_bblock->cil_code = NULL;
5009                 start_bblock->cil_length = 0;
5010                 start_bblock->block_num = cfg->num_bblocks++;
5011
5012                 /* EXIT BLOCK */
5013                 NEW_BBLOCK (cfg, end_bblock);
5014                 cfg->bb_exit = end_bblock;
5015                 end_bblock->cil_code = NULL;
5016                 end_bblock->cil_length = 0;
5017                 end_bblock->block_num = cfg->num_bblocks++;
5018                 g_assert (cfg->num_bblocks == 2);
5019
5020                 arg_array = alloca (sizeof (MonoInst *) * num_args);
5021                 for (i = num_args - 1; i >= 0; i--)
5022                         arg_array [i] = cfg->varinfo [i];
5023
5024                 if (header->num_clauses) {
5025                         cfg->spvars = g_hash_table_new (NULL, NULL);
5026                         cfg->exvars = g_hash_table_new (NULL, NULL);
5027                 }
5028                 /* handle exception clauses */
5029                 for (i = 0; i < header->num_clauses; ++i) {
5030                         MonoBasicBlock *try_bb;
5031                         MonoExceptionClause *clause = &header->clauses [i];
5032
5033                         GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
5034                         try_bb->real_offset = clause->try_offset;
5035                         GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
5036                         tblock->real_offset = clause->handler_offset;
5037                         tblock->flags |= BB_EXCEPTION_HANDLER;
5038
5039                         link_bblock (cfg, try_bb, tblock);
5040
5041                         if (*(ip + clause->handler_offset) == CEE_POP)
5042                                 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
5043
5044                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
5045                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
5046                             clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
5047                                 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
5048                                 MONO_ADD_INS (tblock, ins);
5049
5050                                 /* todo: is a fault block unsafe to optimize? */
5051                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
5052                                         tblock->flags |= BB_EXCEPTION_UNSAFE;
5053                         }
5054
5055
5056                         /*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);
5057                           while (p < end) {
5058                           g_print ("%s", mono_disasm_code_one (NULL, method, p, &p));
5059                           }*/
5060                         /* catch and filter blocks get the exception object on the stack */
5061                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
5062                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
5063                                 MonoInst *load, *dummy_use;
5064
5065                                 /* mostly like handle_stack_args (), but just sets the input args */
5066                                 /* g_print ("handling clause at IL_%04x\n", clause->handler_offset); */
5067                                 tblock->in_scount = 1;
5068                                 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
5069                                 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
5070
5071                                 /* 
5072                                  * Add a dummy use for the exvar so its liveness info will be
5073                                  * correct.
5074                                  */
5075                                 NEW_TEMPLOAD (cfg, load, tblock->in_stack [0]->inst_c0);
5076                                 NEW_DUMMY_USE (cfg, dummy_use, load);
5077                                 MONO_ADD_INS (tblock, dummy_use);
5078                                 
5079                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
5080                                         GET_BBLOCK (cfg, tblock, ip + clause->data.filter_offset);
5081                                         tblock->real_offset = clause->data.filter_offset;
5082                                         tblock->in_scount = 1;
5083                                         tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
5084                                         /* The filter block shares the exvar with the handler block */
5085                                         tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
5086                                         MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
5087                                         MONO_ADD_INS (tblock, ins);
5088                                 }
5089                         }
5090
5091                         if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER &&
5092                                         clause->data.catch_class &&
5093                                         cfg->generic_sharing_context &&
5094                                         mono_class_check_context_used (clause->data.catch_class)) {
5095                                 if (mono_method_get_context (method)->method_inst)
5096                                         GENERIC_SHARING_FAILURE (CEE_NOP);
5097
5098                                 /*
5099                                  * In shared generic code with catch
5100                                  * clauses containing type variables
5101                                  * the exception handling code has to
5102                                  * be able to get to the rgctx.
5103                                  * Therefore we have to make sure that
5104                                  * the vtable/mrgctx argument (for
5105                                  * static or generic methods) or the
5106                                  * "this" argument (for non-static
5107                                  * methods) are live.
5108                                  */
5109                                 if ((method->flags & METHOD_ATTRIBUTE_STATIC) ||
5110                                                 mini_method_get_context (method)->method_inst) {
5111                                         mono_get_vtable_var (cfg);
5112                                 } else {
5113                                         MonoInst *this, *dummy_use;
5114                                         MonoType *this_type;
5115
5116                                         if (method->klass->valuetype)
5117                                                 this_type = &method->klass->this_arg;
5118                                         else
5119                                                 this_type = &method->klass->byval_arg;
5120
5121                                         if (arg_array [0]->opcode == OP_ICONST) {
5122                                                 this = arg_array [0];
5123                                         } else {
5124                                                 this = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));
5125                                                 this->ssa_op = MONO_SSA_LOAD;
5126                                                 this->inst_i0 = arg_array [0];
5127                                                 this->opcode = mini_type_to_ldind ((cfg), this->inst_i0->inst_vtype);
5128                                                 type_to_eval_stack_type ((cfg), this_type, this);
5129                                                 this->klass = this->inst_i0->klass;
5130                                         }
5131
5132                                         NEW_DUMMY_USE (cfg, dummy_use, this);
5133                                         MONO_ADD_INS (tblock, dummy_use);
5134                                 }
5135                         }
5136                 }
5137         } else {
5138                 arg_array = alloca (sizeof (MonoInst *) * num_args);
5139                 mono_save_args (cfg, start_bblock, sig, inline_args, arg_array);
5140         }
5141
5142         /* FIRST CODE BLOCK */
5143         NEW_BBLOCK (cfg, bblock);
5144         bblock->cil_code = ip;
5145
5146         ADD_BBLOCK (cfg, bblock);
5147
5148         if (cfg->method == method) {
5149                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
5150                 if (breakpoint_id && (mono_debug_format != MONO_DEBUG_FORMAT_DEBUGGER)) {
5151                         MONO_INST_NEW (cfg, ins, OP_BREAK);
5152                         MONO_ADD_INS (bblock, ins);
5153                 }
5154         }
5155
5156         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS)
5157                 secman = mono_security_manager_get_methods ();
5158
5159         security = (secman && mono_method_has_declsec (method));
5160         /* at this point having security doesn't mean we have any code to generate */
5161         if (security && (cfg->method == method)) {
5162                 /* Only Demand, NonCasDemand and DemandChoice requires code generation.
5163                  * And we do not want to enter the next section (with allocation) if we
5164                  * have nothing to generate */
5165                 security = mono_declsec_get_demands (method, &actions);
5166         }
5167
5168         /* we must Demand SecurityPermission.Unmanaged before P/Invoking */
5169         pinvoke = (secman && (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE));
5170         if (pinvoke) {
5171                 MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
5172                 if (wrapped && (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5173                         MonoCustomAttrInfo* custom = mono_custom_attrs_from_method (wrapped);
5174
5175                         /* unless the method or it's class has the [SuppressUnmanagedCodeSecurity] attribute */
5176                         if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
5177                                 pinvoke = FALSE;
5178                         }
5179                         if (custom)
5180                                 mono_custom_attrs_free (custom);
5181
5182                         if (pinvoke) {
5183                                 custom = mono_custom_attrs_from_class (wrapped->klass);
5184                                 if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
5185                                         pinvoke = FALSE;
5186                                 }
5187                                 if (custom)
5188                                         mono_custom_attrs_free (custom);
5189                         }
5190                 } else {
5191                         /* not a P/Invoke after all */
5192                         pinvoke = FALSE;
5193                 }
5194         }
5195         
5196         if ((header->init_locals || (cfg->method == method && (cfg->opt & MONO_OPT_SHARED))) || cfg->compile_aot || security || pinvoke) {
5197                 /* we use a separate basic block for the initialization code */
5198                 NEW_BBLOCK (cfg, init_localsbb);
5199                 cfg->bb_init = init_localsbb;
5200                 init_localsbb->real_offset = real_offset;
5201                 start_bblock->next_bb = init_localsbb;
5202                 init_localsbb->next_bb = bblock;
5203                 link_bblock (cfg, start_bblock, init_localsbb);
5204                 link_bblock (cfg, init_localsbb, bblock);
5205                 init_localsbb->block_num = cfg->num_bblocks++;
5206         } else {
5207                 start_bblock->next_bb = bblock;
5208                 link_bblock (cfg, start_bblock, bblock);
5209         }
5210
5211         /* at this point we know, if security is TRUE, that some code needs to be generated */
5212         if (security && (cfg->method == method)) {
5213                 MonoInst *args [2];
5214
5215                 mono_jit_stats.cas_demand_generation++;
5216
5217                 if (actions.demand.blob) {
5218                         /* Add code for SecurityAction.Demand */
5219                         NEW_DECLSECCONST (cfg, args[0], image, actions.demand);
5220                         NEW_ICONST (cfg, args [1], actions.demand.size);
5221                         /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
5222                         mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
5223                 }
5224                 if (actions.noncasdemand.blob) {
5225                         /* CLR 1.x uses a .noncasdemand (but 2.x doesn't) */
5226                         /* For Mono we re-route non-CAS Demand to Demand (as the managed code must deal with it anyway) */
5227                         NEW_DECLSECCONST (cfg, args[0], image, actions.noncasdemand);
5228                         NEW_ICONST (cfg, args [1], actions.noncasdemand.size);
5229                         /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
5230                         mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
5231                 }
5232                 if (actions.demandchoice.blob) {
5233                         /* New in 2.0, Demand must succeed for one of the permissions (i.e. not all) */
5234                         NEW_DECLSECCONST (cfg, args[0], image, actions.demandchoice);
5235                         NEW_ICONST (cfg, args [1], actions.demandchoice.size);
5236                         /* Calls static void SecurityManager.InternalDemandChoice (byte* permissions, int size); */
5237                         mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandchoice, mono_method_signature (secman->demandchoice), args, ip, NULL);
5238                 }
5239         }
5240
5241         /* we must Demand SecurityPermission.Unmanaged before p/invoking */
5242         if (pinvoke) {
5243                 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandunmanaged, mono_method_signature (secman->demandunmanaged), NULL, ip, NULL);
5244         }
5245
5246         if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
5247                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
5248                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
5249                         if (wrapped && (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5250                                 if (!(method->klass && method->klass->image &&
5251                                                 mono_security_core_clr_is_platform_image (method->klass->image))) {
5252                                         emit_throw_method_access_exception (cfg, method, wrapped, bblock, ip);
5253                                 }
5254                         }
5255                 }
5256                 if (!method_is_safe (method))
5257                         emit_throw_verification_exception (cfg, bblock, ip);
5258         }
5259
5260         if (header->code_size == 0)
5261                 UNVERIFIED;
5262
5263         if (get_basic_blocks (cfg, header, real_offset, ip, end, &err_pos)) {
5264                 ip = err_pos;
5265                 UNVERIFIED;
5266         }
5267
5268         if (cfg->method == method)
5269                 mono_debug_init_method (cfg, bblock, breakpoint_id);
5270
5271         param_types = mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
5272         if (sig->hasthis)
5273                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
5274         for (n = 0; n < sig->param_count; ++n)
5275                 param_types [n + sig->hasthis] = sig->params [n];
5276         for (n = 0; n < header->num_locals; ++n) {
5277                 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
5278                         UNVERIFIED;
5279         }
5280         class_inits = NULL;
5281
5282         /* do this somewhere outside - not here */
5283         NEW_ICONST (cfg, zero_int32, 0);
5284         NEW_ICONST (cfg, zero_int64, 0);
5285         zero_int64->type = STACK_I8;
5286         NEW_PCONST (cfg, zero_ptr, 0);
5287         NEW_PCONST (cfg, zero_obj, 0);
5288         zero_obj->type = STACK_OBJ;
5289
5290         MONO_INST_NEW (cfg, zero_r8, OP_R8CONST);
5291         zero_r8->type = STACK_R8;
5292         zero_r8->inst_p0 = &r8_0;
5293
5294         /* add a check for this != NULL to inlined methods */
5295         if (is_virtual_call) {
5296                 MONO_INST_NEW (cfg, ins, OP_CHECK_THIS);
5297                 NEW_ARGLOAD (cfg, ins->inst_left, 0);
5298                 ins->cil_code = ip;
5299                 MONO_ADD_INS (bblock, ins);
5300         }
5301
5302         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
5303         stack_start = sp = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
5304
5305         ins_flag = 0;
5306         start_new_bblock = 0;
5307         while (ip < end) {
5308
5309                 if (cfg->method == method)
5310                         real_offset = ip - header->code;
5311                 else
5312                         real_offset = inline_offset;
5313                 cfg->ip = ip;
5314
5315                 context_used = 0;
5316
5317                 if (start_new_bblock) {
5318                         bblock->cil_length = ip - bblock->cil_code;
5319                         if (start_new_bblock == 2) {
5320                                 g_assert (ip == tblock->cil_code);
5321                         } else {
5322                                 GET_BBLOCK (cfg, tblock, ip);
5323                         }
5324                         bblock->next_bb = tblock;
5325                         bblock = tblock;
5326                         start_new_bblock = 0;
5327                         for (i = 0; i < bblock->in_scount; ++i) {
5328                                 if (cfg->verbose_level > 3)
5329                                         g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);                                           
5330                                 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
5331                                 *sp++ = ins;
5332                         }
5333                         g_slist_free (class_inits);
5334                         class_inits = NULL;
5335                 } else {
5336                         if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != bblock)) {
5337                                 link_bblock (cfg, bblock, tblock);
5338                                 if (sp != stack_start) {
5339                                         handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5340                                         sp = stack_start;
5341                                         CHECK_UNVERIFIABLE (cfg);
5342                                 }
5343                                 bblock->next_bb = tblock;
5344                                 bblock = tblock;
5345                                 for (i = 0; i < bblock->in_scount; ++i) {
5346                                         if (cfg->verbose_level > 3)
5347                                                 g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);                                           
5348                                         NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
5349                                         *sp++ = ins;
5350                                 }
5351                                 g_slist_free (class_inits);
5352                                 class_inits = NULL;
5353                         }
5354                 }
5355
5356                 bblock->real_offset = real_offset;
5357
5358                 if ((cfg->method == method) && cfg->coverage_info) {
5359                         MonoInst *store, *one;
5360                         guint32 cil_offset = ip - header->code;
5361                         cfg->coverage_info->data [cil_offset].cil_code = ip;
5362
5363                         /* TODO: Use an increment here */
5364                         NEW_ICONST (cfg, one, 1);
5365                         one->cil_code = ip;
5366
5367                         NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
5368                         ins->cil_code = ip;
5369
5370                         MONO_INST_NEW (cfg, store, CEE_STIND_I);
5371                         store->inst_left = ins;
5372                         store->inst_right = one;
5373
5374                         MONO_ADD_INS (bblock, store);
5375                 }
5376
5377                 if (cfg->verbose_level > 3)
5378                         g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
5379
5380                 switch (*ip) {
5381                 case CEE_NOP:
5382                         MONO_INST_NEW (cfg, ins, OP_NOP);
5383                         ip++;
5384                         MONO_ADD_INS (bblock, ins);
5385                         break;
5386                 case CEE_BREAK:
5387                         MONO_INST_NEW (cfg, ins, OP_BREAK);
5388                         ip++;
5389                         MONO_ADD_INS (bblock, ins);
5390                         break;
5391                 case CEE_LDARG_0:
5392                 case CEE_LDARG_1:
5393                 case CEE_LDARG_2:
5394                 case CEE_LDARG_3:
5395                         CHECK_STACK_OVF (1);
5396                         n = (*ip)-CEE_LDARG_0;
5397                         CHECK_ARG (n);
5398                         NEW_ARGLOAD (cfg, ins, n);
5399                         LDARG_SOFT_FLOAT (cfg, ins, n, ip);
5400                         ip++;
5401                         *sp++ = ins;
5402                         break;
5403                 case CEE_LDLOC_0:
5404                 case CEE_LDLOC_1:
5405                 case CEE_LDLOC_2:
5406                 case CEE_LDLOC_3:
5407                         CHECK_STACK_OVF (1);
5408                         n = (*ip)-CEE_LDLOC_0;
5409                         CHECK_LOCAL (n);
5410                         NEW_LOCLOAD (cfg, ins, n);
5411                         LDLOC_SOFT_FLOAT (cfg, ins, n, ip);
5412                         ip++;
5413                         *sp++ = ins;
5414                         break;
5415                 case CEE_STLOC_0:
5416                 case CEE_STLOC_1:
5417                 case CEE_STLOC_2:
5418                 case CEE_STLOC_3:
5419                         CHECK_STACK (1);
5420                         n = (*ip)-CEE_STLOC_0;
5421                         CHECK_LOCAL (n);
5422                         --sp;
5423                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5424                         NEW_LOCSTORE (cfg, ins, n, *sp);
5425                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
5426                                 UNVERIFIED;
5427                         STLOC_SOFT_FLOAT (cfg, ins, n, ip);
5428                         if (ins->opcode == CEE_STOBJ) {
5429                                 NEW_LOCLOADA (cfg, ins, n);
5430                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5431                         } else
5432                                 MONO_ADD_INS (bblock, ins);
5433                         ++ip;
5434                         inline_costs += 1;
5435                         break;
5436                 case CEE_LDARG_S:
5437                         CHECK_OPSIZE (2);
5438                         CHECK_STACK_OVF (1);
5439                         CHECK_ARG (ip [1]);
5440                         NEW_ARGLOAD (cfg, ins, ip [1]);
5441                         LDARG_SOFT_FLOAT (cfg, ins, ip [1], ip);
5442                         *sp++ = ins;
5443                         ip += 2;
5444                         break;
5445                 case CEE_LDARGA_S:
5446                         CHECK_OPSIZE (2);
5447                         CHECK_STACK_OVF (1);
5448                         CHECK_ARG (ip [1]);
5449                         NEW_ARGLOADA (cfg, ins, ip [1]);
5450                         *sp++ = ins;
5451                         ip += 2;
5452                         break;
5453                 case CEE_STARG_S:
5454                         CHECK_OPSIZE (2);
5455                         CHECK_STACK (1);
5456                         --sp;
5457                         CHECK_ARG (ip [1]);
5458                         NEW_ARGSTORE (cfg, ins, ip [1], *sp);
5459                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5460                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
5461                                 UNVERIFIED;
5462                         STARG_SOFT_FLOAT (cfg, ins, ip [1], ip);
5463                         if (ins->opcode == CEE_STOBJ) {
5464                                 NEW_ARGLOADA (cfg, ins, ip [1]);
5465                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5466                         } else
5467                                 MONO_ADD_INS (bblock, ins);
5468                         ip += 2;
5469                         break;
5470                 case CEE_LDLOC_S:
5471                         CHECK_OPSIZE (2);
5472                         CHECK_STACK_OVF (1);
5473                         CHECK_LOCAL (ip [1]);
5474                         NEW_LOCLOAD (cfg, ins, ip [1]);
5475                         LDLOC_SOFT_FLOAT (cfg, ins, ip [1], ip);
5476                         *sp++ = ins;
5477                         ip += 2;
5478                         break;
5479                 case CEE_LDLOCA_S:
5480                         CHECK_OPSIZE (2);
5481                         CHECK_STACK_OVF (1);
5482                         CHECK_LOCAL (ip [1]);
5483                         NEW_LOCLOADA (cfg, ins, ip [1]);
5484                         *sp++ = ins;
5485                         ip += 2;
5486                         break;
5487                 case CEE_STLOC_S:
5488                         CHECK_OPSIZE (2);
5489                         CHECK_STACK (1);
5490                         --sp;
5491                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5492                         CHECK_LOCAL (ip [1]);
5493                         NEW_LOCSTORE (cfg, ins, ip [1], *sp);
5494                         if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
5495                                 UNVERIFIED;
5496                         STLOC_SOFT_FLOAT (cfg, ins, ip [1], ip);
5497                         if (ins->opcode == CEE_STOBJ) {
5498                                 NEW_LOCLOADA (cfg, ins, ip [1]);
5499                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5500                         } else
5501                                 MONO_ADD_INS (bblock, ins);
5502                         ip += 2;
5503                         inline_costs += 1;
5504                         break;
5505                 case CEE_LDNULL:
5506                         CHECK_STACK_OVF (1);
5507                         NEW_PCONST (cfg, ins, NULL);
5508                         ins->type = STACK_OBJ;
5509                         ++ip;
5510                         *sp++ = ins;
5511                         break;
5512                 case CEE_LDC_I4_M1:
5513                         CHECK_STACK_OVF (1);
5514                         NEW_ICONST (cfg, ins, -1);
5515                         ++ip;
5516                         *sp++ = ins;
5517                         break;
5518                 case CEE_LDC_I4_0:
5519                 case CEE_LDC_I4_1:
5520                 case CEE_LDC_I4_2:
5521                 case CEE_LDC_I4_3:
5522                 case CEE_LDC_I4_4:
5523                 case CEE_LDC_I4_5:
5524                 case CEE_LDC_I4_6:
5525                 case CEE_LDC_I4_7:
5526                 case CEE_LDC_I4_8:
5527                         CHECK_STACK_OVF (1);
5528                         NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
5529                         ++ip;
5530                         *sp++ = ins;
5531                         break;
5532                 case CEE_LDC_I4_S:
5533                         CHECK_OPSIZE (2);
5534                         CHECK_STACK_OVF (1);
5535                         ++ip;
5536                         NEW_ICONST (cfg, ins, *((signed char*)ip));
5537                         ++ip;
5538                         *sp++ = ins;
5539                         break;
5540                 case CEE_LDC_I4:
5541                         CHECK_OPSIZE (5);
5542                         CHECK_STACK_OVF (1);
5543                         NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
5544                         ip += 5;
5545                         *sp++ = ins;
5546                         break;
5547                 case CEE_LDC_I8:
5548                         CHECK_OPSIZE (9);
5549                         CHECK_STACK_OVF (1);
5550                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
5551                         ins->type = STACK_I8;
5552                         ++ip;
5553                         ins->inst_l = (gint64)read64 (ip);
5554                         ip += 8;
5555                         *sp++ = ins;
5556                         break;
5557                 case CEE_LDC_R4: {
5558                         float *f;
5559                         /* we should really allocate this only late in the compilation process */
5560                         mono_domain_lock (cfg->domain);
5561                         f = mono_mempool_alloc (cfg->domain->mp, sizeof (float));
5562                         mono_domain_unlock (cfg->domain);
5563                         CHECK_OPSIZE (5);
5564                         CHECK_STACK_OVF (1);
5565                         MONO_INST_NEW (cfg, ins, OP_R4CONST);
5566                         ins->type = STACK_R8;
5567                         ++ip;
5568                         readr4 (ip, f);
5569                         ins->inst_p0 = f;
5570
5571                         ip += 4;
5572                         *sp++ = ins;                    
5573                         break;
5574                 }
5575                 case CEE_LDC_R8: {
5576                         double *d;
5577                         mono_domain_lock (cfg->domain);
5578                         d = mono_mempool_alloc (cfg->domain->mp, sizeof (double));
5579                         mono_domain_unlock (cfg->domain);
5580                         CHECK_OPSIZE (9);
5581                         CHECK_STACK_OVF (1);
5582                         MONO_INST_NEW (cfg, ins, OP_R8CONST);
5583                         ins->type = STACK_R8;
5584                         ++ip;
5585                         readr8 (ip, d);
5586                         ins->inst_p0 = d;
5587
5588                         ip += 8;
5589                         *sp++ = ins;                    
5590                         break;
5591                 }
5592                 case CEE_DUP: {
5593                         MonoInst *temp, *store;
5594                         CHECK_STACK (1);
5595                         CHECK_STACK_OVF (1);
5596                         sp--;
5597                         ins = *sp;
5598                 
5599                         /* 
5600                          * small optimization: if the loaded value was from a local already,
5601                          * just load it twice.
5602                          */
5603                         if (ins->ssa_op == MONO_SSA_LOAD && 
5604                             (ins->inst_i0->opcode == OP_LOCAL || ins->inst_i0->opcode == OP_ARG)) {
5605                                 sp++;
5606                                 MONO_INST_NEW (cfg, temp, 0);
5607                                 *temp = *ins;
5608                                 *sp++ = temp;
5609                         } else {
5610                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
5611                                 temp->flags |= MONO_INST_IS_TEMP;
5612                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
5613                                 /* FIXME: handle CEE_STIND_R4 */
5614                                 if (store->opcode == CEE_STOBJ) {
5615                                         NEW_TEMPLOADA (cfg, store, temp->inst_c0);
5616                                         handle_stobj (cfg, bblock, store, sp [0], sp [0]->cil_code, store->klass, TRUE, FALSE, FALSE);
5617                                 } else {
5618                                         MONO_ADD_INS (bblock, store);
5619                                 }
5620                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
5621                                 *sp++ = ins;
5622                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
5623                                 *sp++ = ins;
5624                         }
5625                         ++ip;
5626                         inline_costs += 2;
5627                         break;
5628                 }
5629                 case CEE_POP:
5630                         CHECK_STACK (1);
5631                         MONO_INST_NEW (cfg, ins, CEE_POP);
5632                         MONO_ADD_INS (bblock, ins);
5633                         ip++;
5634                         --sp;
5635                         ins->inst_i0 = *sp;
5636                         break;
5637                 case CEE_JMP:
5638                         CHECK_OPSIZE (5);
5639                         if (stack_start != sp)
5640                                 UNVERIFIED;
5641                         MONO_INST_NEW (cfg, ins, OP_JMP);
5642                         token = read32 (ip + 1);
5643                         /* FIXME: check the signature matches */
5644                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
5645
5646                         if (!cmethod)
5647                                 goto load_error;
5648
5649                         if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
5650                                 GENERIC_SHARING_FAILURE (CEE_JMP);
5651
5652                         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
5653                                 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
5654                                         INLINE_FAILURE;
5655                                 CHECK_CFG_EXCEPTION;
5656                         }
5657
5658                         ins->inst_p0 = cmethod;
5659                         MONO_ADD_INS (bblock, ins);
5660                         ip += 5;
5661                         start_new_bblock = 1;
5662                         break;
5663                 case CEE_CALLI:
5664                 case CEE_CALL:
5665                 case CEE_CALLVIRT: {
5666                         MonoInst *addr = NULL;
5667                         MonoMethodSignature *fsig = NULL;
5668                         int temp, array_rank = 0;
5669                         int virtual = *ip == CEE_CALLVIRT;
5670                         gboolean no_spill;
5671                         gboolean pass_imt_from_rgctx = FALSE;
5672                         MonoInst *imt_arg = NULL;
5673                         gboolean pass_vtable = FALSE;
5674                         gboolean pass_mrgctx = FALSE;
5675                         MonoInst *vtable_arg = NULL;
5676                         gboolean check_this = FALSE;
5677
5678                         CHECK_OPSIZE (5);
5679                         token = read32 (ip + 1);
5680
5681                         if (*ip == CEE_CALLI) {
5682                                 cmethod = NULL;
5683                                 CHECK_STACK (1);
5684                                 --sp;
5685                                 addr = *sp;
5686                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
5687                                         fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
5688                                 else
5689                                         fsig = mono_metadata_parse_signature (image, token);
5690
5691                                 n = fsig->param_count + fsig->hasthis;
5692                         } else {
5693                                 MonoMethod *cil_method;
5694                                 
5695                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
5696                                         cmethod =  (MonoMethod *)mono_method_get_wrapper_data (method, token);
5697                                         cil_method = cmethod;
5698                                 } else if (constrained_call) {
5699                                         cmethod = mono_get_method_constrained (image, token, constrained_call, generic_context, &cil_method);
5700                                         cil_method = cmethod;
5701                                 } else {
5702                                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
5703                                         cil_method = cmethod;
5704                                 }
5705
5706                                 if (!cmethod)
5707                                         goto load_error;
5708                                 if (!dont_verify && !cfg->skip_visibility) {
5709                                         MonoMethod *target_method = cil_method;
5710                                         if (method->is_inflated) {
5711                                                 target_method = mini_get_method_allow_open (method, token, NULL, &(mono_method_get_generic_container (method_definition)->context));
5712                                         }
5713                                         if (!mono_method_can_access_method (method_definition, target_method) &&
5714                                                 !mono_method_can_access_method (method, cil_method))
5715                                                 METHOD_ACCESS_FAILURE;
5716                                 }
5717
5718                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
5719                                         ensure_method_is_allowed_to_call_method (cfg, method, cil_method, bblock, ip);
5720
5721                                 if (!virtual && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
5722                                         /* MS.NET seems to silently convert this to a callvirt */
5723                                         virtual = 1;
5724
5725                                 if (!cmethod->klass->inited){
5726                                         if (!mono_class_init (cmethod->klass))
5727                                                 goto load_error;
5728                                 }
5729
5730                                 if (mono_method_signature (cmethod)->pinvoke) {
5731                                         MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod, check_for_pending_exc);
5732                                         fsig = mono_method_signature (wrapper);
5733                                 } else if (constrained_call) {
5734                                         fsig = mono_method_signature (cmethod);
5735                                 } else {
5736                                         fsig = mono_method_get_signature_full (cmethod, image, token, generic_context);
5737                                 }
5738
5739                                 mono_save_token_info (cfg, image, token, cmethod);
5740
5741                                 n = fsig->param_count + fsig->hasthis;
5742
5743                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
5744                                         if (check_linkdemand (cfg, method, cmethod, bblock, ip))
5745                                                 INLINE_FAILURE;
5746                                         CHECK_CFG_EXCEPTION;
5747                                 }
5748
5749                                 if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
5750                                     mini_class_is_system_array (cmethod->klass)) {
5751                                         array_rank = cmethod->klass->rank;
5752                                 }
5753
5754                                 if (cmethod->string_ctor)
5755                                         g_assert_not_reached ();
5756
5757                         }
5758
5759                         if (!cfg->generic_sharing_context && cmethod && cmethod->klass->generic_container)
5760                                 UNVERIFIED;
5761
5762                         if (!cfg->generic_sharing_context && cmethod)
5763                                 g_assert (!mono_method_check_context_used (cmethod));
5764
5765                         CHECK_STACK (n);
5766
5767                         //g_assert (!virtual || fsig->hasthis);
5768
5769                         sp -= n;
5770
5771                         if (constrained_call) {
5772                                 /*
5773                                  * We have the `constrained.' prefix opcode.
5774                                  */
5775                                 if (constrained_call->valuetype && !cmethod->klass->valuetype) {
5776                                         MonoInst *load;
5777                                         /*
5778                                          * The type parameter is instantiated as a valuetype,
5779                                          * but that type doesn't override the method we're
5780                                          * calling, so we need to box `this'.
5781                                          * sp [0] is a pointer to the data: we need the value
5782                                          * in handle_box (), so load it here.
5783                                          */
5784                                         MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, &constrained_call->byval_arg));
5785                                         type_to_eval_stack_type (cfg, &constrained_call->byval_arg, load);
5786                                         load->inst_left = sp [0];
5787                                         sp [0] = handle_box (cfg, bblock, load, ip, constrained_call);
5788                                 } else if (!constrained_call->valuetype) {
5789                                         MonoInst *ins;
5790
5791                                         /*
5792                                          * The type parameter is instantiated as a reference
5793                                          * type.  We have a managed pointer on the stack, so
5794                                          * we need to dereference it here.
5795                                          */
5796
5797                                         MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
5798                                         ins->inst_i0 = sp [0];
5799                                         ins->type = STACK_OBJ;
5800                                         ins->klass = mono_class_from_mono_type (&constrained_call->byval_arg);
5801                                         sp [0] = ins;
5802                                 } else if (cmethod->klass->valuetype)
5803                                         virtual = 0;
5804                                 constrained_call = NULL;
5805                         }
5806
5807                         if (*ip != CEE_CALLI && check_call_signature (cfg, fsig, sp))
5808                                 UNVERIFIED;
5809
5810                         if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_STATIC) &&
5811                                         (cmethod->klass->generic_class || cmethod->klass->generic_container)) {
5812                                 gboolean sharing_enabled = mono_class_generic_sharing_enabled (cmethod->klass);
5813                                 MonoGenericContext *context = mini_class_get_context (cmethod->klass);
5814                                 gboolean context_sharable = mono_generic_context_is_sharable (context, TRUE);
5815
5816                                 /*
5817                                  * Pass vtable iff target method might
5818                                  * be shared, which means that sharing
5819                                  * is enabled for its class and its
5820                                  * context is sharable (and it's not a
5821                                  * generic method).
5822                                  */
5823                                 if (sharing_enabled && context_sharable &&
5824                                                 !mini_method_get_context (cmethod)->method_inst)
5825                                         pass_vtable = TRUE;
5826                         }
5827
5828                         if (cmethod && mini_method_get_context (cmethod) &&
5829                                         mini_method_get_context (cmethod)->method_inst) {
5830                                 gboolean sharing_enabled = mono_class_generic_sharing_enabled (cmethod->klass);
5831                                 MonoGenericContext *context = mini_method_get_context (cmethod);
5832                                 gboolean context_sharable = mono_generic_context_is_sharable (context, TRUE);
5833
5834                                 g_assert (!pass_vtable);
5835
5836                                 if (sharing_enabled && context_sharable)
5837                                         pass_mrgctx = TRUE;
5838                         }
5839
5840                         if (cfg->generic_sharing_context && cmethod) {
5841                                 MonoGenericContext *cmethod_context = mono_method_get_context (cmethod);
5842
5843                                 context_used = mono_method_check_context_used (cmethod);
5844
5845                                 if (context_used && (cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE)) {
5846                                         /* Generic method interface
5847                                            calls are resolved via a
5848                                            helper function and don't
5849                                            need an imt. */
5850                                         if (!cmethod_context || !cmethod_context->method_inst)
5851                                                 pass_imt_from_rgctx = TRUE;
5852                                 }
5853
5854                                 /*
5855                                  * If a shared method calls another
5856                                  * shared method then the caller must
5857                                  * have a generic sharing context
5858                                  * because the magic trampoline
5859                                  * requires it.  FIXME: We shouldn't
5860                                  * have to force the vtable/mrgctx
5861                                  * variable here.  Instead there
5862                                  * should be a flag in the cfg to
5863                                  * request a generic sharing context.
5864                                  */
5865                                 if (context_used && method->flags & METHOD_ATTRIBUTE_STATIC)
5866                                         mono_get_vtable_var (cfg);
5867                         }
5868
5869                         if (pass_vtable) {
5870                                 if (context_used) {
5871                                         MonoInst *rgctx;
5872
5873                                         GET_RGCTX (rgctx, context_used);
5874                                         vtable_arg = get_runtime_generic_context_ptr (cfg, method, context_used,
5875                                                 bblock, cmethod->klass, generic_context, rgctx, MONO_RGCTX_INFO_VTABLE, ip);
5876                                 } else {
5877                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
5878                                         
5879                                         CHECK_TYPELOAD (cmethod->klass);
5880                                         NEW_VTABLECONST (cfg, vtable_arg, vtable);
5881                                 }
5882                         }
5883
5884                         if (pass_mrgctx) {
5885                                 g_assert (!vtable_arg);
5886
5887                                 if (context_used) {
5888                                         MonoInst *rgctx;
5889
5890                                         GET_RGCTX (rgctx, context_used);
5891                                         vtable_arg = get_runtime_generic_context_method_rgctx (cfg, method,
5892                                                 context_used, bblock, cmethod, generic_context, rgctx, ip);
5893                                 } else {
5894                                         MonoMethodRuntimeGenericContext *mrgctx;
5895
5896                                         mrgctx = mono_method_lookup_rgctx (mono_class_vtable (cfg->domain, cmethod->klass),
5897                                                 mini_method_get_context (cmethod)->method_inst);
5898
5899                                         NEW_PCONST (cfg, vtable_arg, mrgctx);
5900                                 }
5901
5902                                 if (!(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
5903                                                 (cmethod->flags & METHOD_ATTRIBUTE_FINAL)) {
5904                                         if (virtual)
5905                                                 check_this = TRUE;
5906                                         virtual = 0;
5907                                 }
5908                         }
5909
5910                         if (pass_imt_from_rgctx) {
5911                                 MonoInst *rgctx;
5912
5913                                 g_assert (!pass_vtable);
5914                                 g_assert (cmethod);
5915
5916                                 GET_RGCTX (rgctx, context_used);
5917                                 imt_arg = get_runtime_generic_context_method (cfg, method, context_used, bblock, cmethod,
5918                                                 generic_context, rgctx, MONO_RGCTX_INFO_METHOD, ip);
5919                         }
5920
5921                         if (check_this) {
5922                                 MonoInst *check;
5923
5924                                 MONO_INST_NEW (cfg, check, OP_CHECK_THIS_PASSTHROUGH);
5925                                 check->cil_code = ip;
5926                                 check->inst_left = sp [0];
5927                                 check->type = sp [0]->type;
5928                                 sp [0] = check;
5929                         }
5930
5931                         if (cmethod && virtual && 
5932                             (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) && 
5933                             !((cmethod->flags & METHOD_ATTRIBUTE_FINAL) && 
5934                               cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
5935                             mono_method_signature (cmethod)->generic_param_count) {
5936                                 MonoInst *this_temp, *this_arg_temp, *store;
5937                                 MonoInst *iargs [4];
5938
5939                                 g_assert (mono_method_signature (cmethod)->is_inflated);
5940                                 /* Prevent inlining of methods that contain indirect calls */
5941                                 INLINE_FAILURE;
5942
5943                                 this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
5944                                 NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
5945                                 MONO_ADD_INS (bblock, store);
5946
5947                                 /* FIXME: This should be a managed pointer */
5948                                 this_arg_temp = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
5949
5950                                 /* Because of the PCONST below */
5951                                 cfg->disable_aot = TRUE;
5952                                 NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
5953                                 if (context_used) {
5954                                         MonoInst *rgctx;
5955
5956                                         GET_RGCTX (rgctx, context_used);
5957                                         iargs [1] = get_runtime_generic_context_method (cfg, method, context_used,
5958                                                         bblock, cmethod,
5959                                                         generic_context, rgctx, MONO_RGCTX_INFO_METHOD, ip);
5960                                         NEW_TEMPLOADA (cfg, iargs [2], this_arg_temp->inst_c0);
5961                                         temp = mono_emit_jit_icall (cfg, bblock,
5962                                                 mono_helper_compile_generic_method_wo_context, iargs, ip);
5963                                 } else {
5964                                         NEW_METHODCONST (cfg, iargs [1], cmethod);
5965                                         NEW_PCONST (cfg, iargs [2], mono_method_get_context (cmethod));
5966                                         NEW_TEMPLOADA (cfg, iargs [3], this_arg_temp->inst_c0);
5967                                         temp = mono_emit_jit_icall (cfg, bblock, mono_helper_compile_generic_method,
5968                                                 iargs, ip);
5969                                 }
5970
5971                                 NEW_TEMPLOAD (cfg, addr, temp);
5972                                 NEW_TEMPLOAD (cfg, sp [0], this_arg_temp->inst_c0);
5973
5974                                 if ((temp = mono_emit_calli_spilled (cfg, bblock, fsig, sp, addr, ip)) != -1) {
5975                                         NEW_TEMPLOAD (cfg, *sp, temp);
5976                                         sp++;
5977                                 }
5978
5979                                 ip += 5;
5980                                 ins_flag = 0;
5981                                 break;
5982                         }
5983
5984                         /* FIXME: runtime generic context pointer for jumps? */
5985                         /* FIXME: handle this for generic sharing eventually */
5986                         if ((ins_flag & MONO_INST_TAILCALL) && !cfg->generic_sharing_context && !vtable_arg && cmethod && (*ip == CEE_CALL) &&
5987                                  (mono_metadata_signature_equal (mono_method_signature (method), mono_method_signature (cmethod)))) {
5988                                 int i;
5989
5990                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
5991                                 INLINE_FAILURE;
5992                                 /* FIXME: This assumes the two methods has the same number and type of arguments */
5993                                 /*
5994                                  * We implement tail calls by storing the actual arguments into the 
5995                                  * argument variables, then emitting a OP_JMP. Since the actual arguments
5996                                  * can refer to the arg variables, we have to spill them.
5997                                  */
5998                                 handle_loaded_temps (cfg, bblock, sp, sp + n);
5999                                 for (i = 0; i < n; ++i) {
6000                                         /* Prevent argument from being register allocated */
6001                                         arg_array [i]->flags |= MONO_INST_VOLATILE;
6002
6003                                         /* Check if argument is the same */
6004                                         /* 
6005                                          * FIXME: This loses liveness info, so it can only be done if the
6006                                          * argument is not register allocated.
6007                                          */
6008                                         NEW_ARGLOAD (cfg, ins, i);
6009                                         if ((ins->opcode == sp [i]->opcode) && (ins->inst_i0 == sp [i]->inst_i0))
6010                                                 continue;
6011
6012                                         NEW_ARGSTORE (cfg, ins, i, sp [i]);
6013                                         /* FIXME: handle CEE_STIND_R4 */
6014                                         if (ins->opcode == CEE_STOBJ) {
6015                                                 NEW_ARGLOADA (cfg, ins, i);
6016                                                 handle_stobj (cfg, bblock, ins, sp [i], sp [i]->cil_code, ins->klass, FALSE, FALSE, FALSE);
6017                                         }
6018                                         else
6019                                                 MONO_ADD_INS (bblock, ins);
6020                                 }
6021                                 MONO_INST_NEW (cfg, ins, OP_JMP);
6022                                 ins->inst_p0 = cmethod;
6023                                 ins->inst_p1 = arg_array [0];
6024                                 MONO_ADD_INS (bblock, ins);
6025                                 link_bblock (cfg, bblock, end_bblock);                  
6026                                 start_new_bblock = 1;
6027                                 /* skip CEE_RET as well */
6028                                 ip += 6;
6029                                 ins_flag = 0;
6030                                 break;
6031                         }
6032                         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_get_inst_for_method (cfg, cmethod, fsig, sp))) {
6033                                 if (MONO_TYPE_IS_VOID (fsig->ret)) {
6034                                         MONO_ADD_INS (bblock, ins);
6035                                 } else {
6036                                         type_to_eval_stack_type (cfg, fsig->ret, ins);
6037                                         *sp = ins;
6038                                         sp++;
6039                                 }
6040
6041                                 ip += 5;
6042                                 ins_flag = 0;
6043                                 break;
6044                         }
6045
6046                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6047
6048                         if ((cfg->opt & MONO_OPT_INLINE) && cmethod && //!check_this &&
6049                             (!virtual || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || (cmethod->flags & METHOD_ATTRIBUTE_FINAL)) && 
6050                             mono_method_check_inlining (cfg, cmethod) &&
6051                                  !g_list_find (dont_inline, cmethod)) {
6052                                 int costs;
6053                                 MonoBasicBlock *ebblock;
6054                                 gboolean allways = FALSE;
6055
6056                                 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
6057                                         (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
6058                                         /* Prevent inlining of methods that call wrappers */
6059                                         INLINE_FAILURE;
6060                                         cmethod = mono_marshal_get_native_wrapper (cmethod, check_for_pending_exc);
6061                                         allways = TRUE;
6062                                 }
6063
6064                                 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, allways))) {
6065                                         ip += 5;
6066                                         real_offset += 5;
6067
6068                                         GET_BBLOCK (cfg, bblock, ip);
6069                                         ebblock->next_bb = bblock;
6070                                         link_bblock (cfg, ebblock, bblock);
6071
6072                                         if (!MONO_TYPE_IS_VOID (fsig->ret))
6073                                                 sp++;
6074
6075                                         /* indicates start of a new block, and triggers a load of all 
6076                                            stack arguments at bb boundarie */
6077                                         bblock = ebblock;
6078
6079                                         inline_costs += costs;
6080                                         ins_flag = 0;
6081                                         break;
6082                                 }
6083                         }
6084                         
6085                         inline_costs += 10 * num_calls++;
6086
6087                         /* tail recursion elimination */
6088                         if ((cfg->opt & MONO_OPT_TAILC) && *ip == CEE_CALL && cmethod == method && ip [5] == CEE_RET &&
6089                                         !vtable_arg) {
6090                                 gboolean has_vtargs = FALSE;
6091                                 int i;
6092                                 
6093                                 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
6094                                 INLINE_FAILURE;
6095                                 /* keep it simple */
6096                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
6097                                         if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i])) 
6098                                                 has_vtargs = TRUE;
6099                                 }
6100
6101                                 if (!has_vtargs) {
6102                                         for (i = 0; i < n; ++i) {
6103                                                 /* FIXME: handle CEE_STIND_R4 */
6104                                                 NEW_ARGSTORE (cfg, ins, i, sp [i]);
6105                                                 MONO_ADD_INS (bblock, ins);
6106                                         }
6107                                         MONO_INST_NEW (cfg, ins, OP_BR);
6108                                         MONO_ADD_INS (bblock, ins);
6109                                         tblock = start_bblock->out_bb [0];
6110                                         link_bblock (cfg, bblock, tblock);
6111                                         ins->inst_target_bb = tblock;
6112                                         start_new_bblock = 1;
6113
6114                                         /* skip the CEE_RET, too */
6115                                         if (ip_in_bb (cfg, bblock, ip + 5))
6116                                                 ip += 6;
6117                                         else
6118                                                 ip += 5;
6119                                         ins_flag = 0;
6120                                         break;
6121                                 }
6122                         }
6123
6124                         if (ip_in_bb (cfg, bblock, ip + 5) 
6125                                 && (!MONO_TYPE_ISSTRUCT (fsig->ret))
6126                                 && (!MONO_TYPE_IS_VOID (fsig->ret) || (cmethod && cmethod->string_ctor))
6127                                 && (CODE_IS_STLOC (ip + 5) || ip [5] == CEE_POP || ip [5] == CEE_RET))
6128                                 /* No need to spill */
6129                                 no_spill = TRUE;
6130                         else
6131                                 no_spill = FALSE;
6132
6133                         /* FIXME: only do this for generic methods if
6134                            they are not shared! */
6135                         if (context_used &&
6136                                         (cmethod->klass->valuetype ||
6137                                         (cmethod->is_inflated && mono_method_get_context (cmethod)->method_inst && !pass_mrgctx) ||
6138                                         ((cmethod->flags & METHOD_ATTRIBUTE_STATIC) &&
6139                                                 mono_class_generic_sharing_enabled (cmethod->klass)) ||
6140                                         (!imt_arg && !mono_method_is_generic_sharable_impl (cmethod, TRUE) &&
6141                                                 (!virtual || cmethod->flags & METHOD_ATTRIBUTE_FINAL ||
6142                                                 !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))))) {
6143                                 MonoInst *rgctx;
6144
6145                                 INLINE_FAILURE;
6146
6147                                 g_assert (cfg->generic_sharing_context && cmethod);
6148                                 g_assert (!addr);
6149
6150                                 /*
6151                                  * We are compiling a call to
6152                                  * non-shared generic code from shared
6153                                  * code, which means that we have to
6154                                  * look up the method in the rgctx and
6155                                  * do an indirect call.
6156                                  */
6157                                 GET_RGCTX (rgctx, context_used);
6158                                 addr = get_runtime_generic_context_method (cfg, method, context_used, bblock, cmethod,
6159                                                 generic_context, rgctx, MONO_RGCTX_INFO_GENERIC_METHOD_CODE, ip);
6160
6161                         }
6162
6163                         if (addr) {
6164                                 g_assert (!imt_arg);
6165
6166                                 if (*ip == CEE_CALL) {
6167                                         g_assert (context_used);
6168                                 } else if (*ip == CEE_CALLI) {
6169                                         g_assert (!vtable_arg);
6170                                 } else {
6171                                         g_assert (cmethod->flags & METHOD_ATTRIBUTE_FINAL ||
6172                                                         !(cmethod->flags & METHOD_ATTRIBUTE_FINAL));
6173                                 }
6174
6175                                 /* Prevent inlining of methods with indirect calls */
6176                                 INLINE_FAILURE;
6177                                 if (no_spill) {
6178                                         ins = (MonoInst*)mono_emit_rgctx_calli (cfg, bblock, fsig, sp, addr, vtable_arg, ip);
6179                                         *sp++ = ins;                                    
6180                                 } else {
6181                                         temp = mono_emit_rgctx_calli_spilled (cfg, bblock, fsig, sp, addr, vtable_arg, ip);
6182                                         if (temp != -1) {
6183                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6184                                                 NEW_TEMPLOAD_SOFT_FLOAT (cfg, bblock, *sp, temp, ip);
6185                                                 sp++;
6186                                         }
6187                                 }                       
6188                         } else if (array_rank) {
6189                                 MonoInst *addr;
6190
6191                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
6192                                         if (sp [fsig->param_count]->type == STACK_OBJ) {
6193                                                 MonoInst *iargs [2];
6194                                                 MonoInst *array, *to_store, *store;
6195
6196                                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
6197                                                 
6198                                                 array = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
6199                                                 NEW_TEMPSTORE (cfg, store, array->inst_c0, sp [0]);
6200                                                 MONO_ADD_INS (bblock, store);
6201                                                 NEW_TEMPLOAD (cfg, iargs [0], array->inst_c0);
6202
6203                                                 to_store = mono_compile_create_var (cfg, type_from_stack_type (sp [fsig->param_count]), OP_LOCAL);
6204                                                 NEW_TEMPSTORE (cfg, store, to_store->inst_c0, sp [fsig->param_count]);
6205                                                 /* FIXME: handle CEE_STIND_R4 */
6206                                                 MONO_ADD_INS (bblock, store);
6207                                                 NEW_TEMPLOAD (cfg, iargs [1], to_store->inst_c0);
6208
6209                                                 /*
6210                                                  * We first save the args for the call so that the args are copied to the stack
6211                                                  * and a new instruction tree for them is created. If we don't do this,
6212                                                  * the same MonoInst is added to two different trees and this is not 
6213                                                  * allowed by burg.
6214                                                  */
6215                                                 mono_emit_jit_icall (cfg, bblock, mono_helper_stelem_ref_check, iargs, ip);
6216
6217                                                 NEW_TEMPLOAD (cfg, sp [0], array->inst_c0);
6218                                                 NEW_TEMPLOAD (cfg, sp [fsig->param_count], to_store->inst_c0);
6219                                         }
6220
6221                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, TRUE);
6222                                         NEW_INDSTORE (cfg, ins, addr, sp [fsig->param_count], fsig->params [fsig->param_count - 1]);
6223                                         /* FIXME: handle CEE_STIND_R4 */
6224                                         if (ins->opcode == CEE_STOBJ) {
6225                                                 handle_stobj (cfg, bblock, addr, sp [fsig->param_count], ip, mono_class_from_mono_type (fsig->params [fsig->param_count-1]), FALSE, FALSE, TRUE);
6226                                         } else {
6227                                                 MONO_ADD_INS (bblock, ins);
6228                                         }
6229
6230                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
6231                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
6232                                         NEW_INDLOAD (cfg, ins, addr, fsig->ret);
6233
6234                                         *sp++ = ins;
6235                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
6236                                         if (!cmethod->klass->element_class->valuetype && !readonly) {
6237                                                 MonoInst* check;
6238                                                 //* Needed by the code generated in inssel.brg * /
6239                                                 mono_get_got_var (cfg);
6240
6241                                                 MONO_INST_NEW (cfg, check, OP_CHECK_ARRAY_TYPE);
6242                                                 check->klass = cmethod->klass;
6243                                                 check->inst_left = sp [0];
6244                                                 check->type = STACK_OBJ;
6245                                                 sp [0] = check;
6246                                         }
6247
6248                                         readonly = FALSE;
6249                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
6250                                         *sp++ = addr;
6251                                 } else {
6252                                         g_assert_not_reached ();
6253                                 }
6254
6255                         } else {
6256                                 /* Prevent inlining of methods which call other methods */
6257                                 INLINE_FAILURE;
6258                                 if (mini_redirect_call (&temp, cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL)) {
6259                                         if (temp != -1) {
6260                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6261                                                 sp++;
6262                                         }
6263                                 } else if (no_spill) {
6264                                         ins = (MonoInst*)mono_emit_rgctx_method_call (cfg, bblock, cmethod, fsig, sp,
6265                                                         vtable_arg, imt_arg, ip, virtual ? sp [0] : NULL);
6266                                         *sp++ = ins;
6267                                 } else {
6268                                         if ((temp = mono_emit_rgctx_method_call_spilled (cfg, bblock, cmethod, fsig, sp,
6269                                                         vtable_arg, imt_arg, ip, virtual ? sp [0] : NULL)) != -1) {
6270                                                 MonoInst *load;
6271                                                 NEW_TEMPLOAD (cfg, load, temp);
6272
6273 #ifdef MONO_ARCH_SOFT_FLOAT
6274                                                 if (load->opcode == CEE_LDIND_R4) {
6275                                                         NEW_TEMPLOADA (cfg, load, temp);
6276                                                         temp = handle_load_float (cfg, bblock, load, ip);
6277                                                         NEW_TEMPLOAD (cfg, load, temp);
6278                                                 }
6279 #endif
6280                                                 *sp++ = load;
6281                                         }
6282                                 }
6283                         }
6284
6285                         ip += 5;
6286                         ins_flag = 0;
6287                         break;
6288                 }
6289                 case CEE_RET:
6290                         if (cfg->method != method) {
6291                                 /* return from inlined method */
6292                                 if (return_var) {
6293                                         MonoInst *store;
6294                                         CHECK_STACK (1);
6295                                         --sp;
6296                                         //g_assert (returnvar != -1);
6297                                         NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
6298                                         store->cil_code = sp [0]->cil_code;
6299                                         if (store->opcode == CEE_STOBJ) {
6300                                                 g_assert_not_reached ();
6301                                                 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
6302                                                 /* FIXME: it is possible some optimization will pass the a heap pointer for the struct address, so we'll need the write barrier */
6303                                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, return_var->klass, FALSE, FALSE, FALSE);
6304 #ifdef MONO_ARCH_SOFT_FLOAT
6305                                         } else if (store->opcode == CEE_STIND_R4) {
6306                                                 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
6307                                                 handle_store_float (cfg, bblock, store, *sp, sp [0]->cil_code);
6308 #endif
6309                                         } else
6310                                                 MONO_ADD_INS (bblock, store);
6311                                 } 
6312                         } else {
6313                                 if (cfg->ret) {
6314                                         g_assert (!return_var);
6315                                         CHECK_STACK (1);
6316                                         --sp;
6317                                         MONO_INST_NEW (cfg, ins, OP_NOP);
6318                                         ins->opcode = mini_type_to_stind (cfg, mono_method_signature (method)->ret);
6319                                         if (ins->opcode == CEE_STOBJ) {
6320                                                 NEW_RETLOADA (cfg, ins);
6321                                                 /* FIXME: it is possible some optimization will pass the a heap pointer for the struct address, so we'll need the write barrier */
6322                                                 handle_stobj (cfg, bblock, ins, *sp, ip, cfg->ret->klass, FALSE, FALSE, FALSE);
6323                                         } else {
6324                                                 ins->opcode = OP_SETRET;
6325                                                 ins->inst_i0 = *sp;;
6326                                                 ins->inst_i1 = NULL;
6327                                                 MONO_ADD_INS (bblock, ins);
6328                                         }
6329                                 }
6330                         }
6331                         if (sp != stack_start)
6332                                 UNVERIFIED;
6333                         MONO_INST_NEW (cfg, ins, OP_BR);
6334                         ip++;
6335                         ins->inst_target_bb = end_bblock;
6336                         MONO_ADD_INS (bblock, ins);
6337                         link_bblock (cfg, bblock, end_bblock);
6338                         start_new_bblock = 1;
6339                         break;
6340                 case CEE_BR_S:
6341                         CHECK_OPSIZE (2);
6342                         MONO_INST_NEW (cfg, ins, OP_BR);
6343                         ip++;
6344                         MONO_ADD_INS (bblock, ins);
6345                         target = ip + 1 + (signed char)(*ip);
6346                         ++ip;
6347                         GET_BBLOCK (cfg, tblock, target);
6348                         link_bblock (cfg, bblock, tblock);
6349                         CHECK_BBLOCK (target, ip, tblock);
6350                         ins->inst_target_bb = tblock;
6351                         if (sp != stack_start) {
6352                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6353                                 sp = stack_start;
6354                                 CHECK_UNVERIFIABLE (cfg);
6355                         }
6356                         start_new_bblock = 1;
6357                         inline_costs += BRANCH_COST;
6358                         break;
6359                 case CEE_BRFALSE_S:
6360                 case CEE_BRTRUE_S:
6361                         CHECK_OPSIZE (2);
6362                         CHECK_STACK (1);
6363                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
6364                                 UNVERIFIED;
6365                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
6366                         ip++;
6367                         target = ip + 1 + *(signed char*)ip;
6368                         ip++;
6369                         ADD_UNCOND (ins->opcode == CEE_BRTRUE);
6370                         if (sp != stack_start) {
6371                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6372                                 sp = stack_start;
6373                                 CHECK_UNVERIFIABLE (cfg);
6374                         }
6375                         inline_costs += BRANCH_COST;
6376                         break;
6377                 case CEE_BEQ_S:
6378                 case CEE_BGE_S:
6379                 case CEE_BGT_S:
6380                 case CEE_BLE_S:
6381                 case CEE_BLT_S:
6382                 case CEE_BNE_UN_S:
6383                 case CEE_BGE_UN_S:
6384                 case CEE_BGT_UN_S:
6385                 case CEE_BLE_UN_S:
6386                 case CEE_BLT_UN_S:
6387                         CHECK_OPSIZE (2);
6388                         CHECK_STACK (2);
6389                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
6390                         ip++;
6391                         target = ip + 1 + *(signed char*)ip;
6392                         ip++;
6393 #ifdef MONO_ARCH_SOFT_FLOAT
6394                         if (sp [-1]->type == STACK_R8 || sp [-2]->type == STACK_R8) {
6395                                 ins->opcode = condbr_to_fp_br (ins->opcode);
6396                                 sp -= 2;
6397                                 ins->inst_left = sp [0];
6398                                 ins->inst_right = sp [1];
6399                                 ins->type = STACK_I4;
6400                                 *sp++ = emit_tree (cfg, bblock, ins, ins->cil_code);
6401                                 MONO_INST_NEW (cfg, ins, CEE_BRTRUE);
6402                                 ADD_UNCOND (TRUE);
6403                         } else {
6404                                 ADD_BINCOND (NULL);
6405                         }
6406 #else
6407                         ADD_BINCOND (NULL);
6408 #endif
6409                         if (sp != stack_start) {
6410                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6411                                 sp = stack_start;
6412                                 CHECK_UNVERIFIABLE (cfg);
6413                         }
6414                         inline_costs += BRANCH_COST;
6415                         break;
6416                 case CEE_BR:
6417                         CHECK_OPSIZE (5);
6418                         MONO_INST_NEW (cfg, ins, OP_BR);
6419                         ip++;
6420                         MONO_ADD_INS (bblock, ins);
6421                         target = ip + 4 + (gint32)read32(ip);
6422                         ip += 4;
6423                         GET_BBLOCK (cfg, tblock, target);
6424                         link_bblock (cfg, bblock, tblock);
6425                         CHECK_BBLOCK (target, ip, tblock);
6426                         ins->inst_target_bb = tblock;
6427                         if (sp != stack_start) {
6428                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6429                                 sp = stack_start;
6430                                 CHECK_UNVERIFIABLE (cfg);
6431                         }
6432                         start_new_bblock = 1;
6433                         inline_costs += BRANCH_COST;
6434                         break;
6435                 case CEE_BRFALSE:
6436                 case CEE_BRTRUE:
6437                         CHECK_OPSIZE (5);
6438                         CHECK_STACK (1);
6439                         if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
6440                                 UNVERIFIED;
6441                         MONO_INST_NEW (cfg, ins, *ip);
6442                         ip++;
6443                         target = ip + 4 + (gint32)read32(ip);
6444                         ip += 4;
6445                         ADD_UNCOND(ins->opcode == CEE_BRTRUE);
6446                         if (sp != stack_start) {
6447                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6448                                 sp = stack_start;
6449                                 CHECK_UNVERIFIABLE (cfg);
6450                         }
6451                         inline_costs += BRANCH_COST;
6452                         break;
6453                 case CEE_BEQ:
6454                 case CEE_BGE:
6455                 case CEE_BGT:
6456                 case CEE_BLE:
6457                 case CEE_BLT:
6458                 case CEE_BNE_UN:
6459                 case CEE_BGE_UN:
6460                 case CEE_BGT_UN:
6461                 case CEE_BLE_UN:
6462                 case CEE_BLT_UN:
6463                         CHECK_OPSIZE (5);
6464                         CHECK_STACK (2);
6465                         MONO_INST_NEW (cfg, ins, *ip);
6466                         ip++;
6467                         target = ip + 4 + (gint32)read32(ip);
6468                         ip += 4;
6469 #ifdef MONO_ARCH_SOFT_FLOAT
6470                         if (sp [-1]->type == STACK_R8 || sp [-2]->type == STACK_R8) {
6471                                 ins->opcode = condbr_to_fp_br (ins->opcode);
6472                                 sp -= 2;
6473                                 ins->inst_left = sp [0];
6474                                 ins->inst_right = sp [1];
6475                                 ins->type = STACK_I4;
6476                                 *sp++ = emit_tree (cfg, bblock, ins, ins->cil_code);
6477                                 MONO_INST_NEW (cfg, ins, CEE_BRTRUE);
6478                                 ADD_UNCOND (TRUE);
6479                         } else {
6480                                 ADD_BINCOND (NULL);
6481                         }
6482 #else
6483                         ADD_BINCOND (NULL);
6484 #endif
6485                         if (sp != stack_start) {
6486                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6487                                 sp = stack_start;
6488                                 CHECK_UNVERIFIABLE (cfg);
6489                         }
6490                         inline_costs += BRANCH_COST;
6491                         break;
6492                 case CEE_SWITCH:
6493                         CHECK_OPSIZE (5);
6494                         CHECK_STACK (1);
6495                         n = read32 (ip + 1);
6496                         MONO_INST_NEW (cfg, ins, OP_SWITCH);
6497                         --sp;
6498                         ins->inst_left = *sp;
6499                         if ((ins->inst_left->type != STACK_I4) && (ins->inst_left->type != STACK_PTR)) 
6500                                 UNVERIFIED;
6501                         ip += 5;
6502                         CHECK_OPSIZE (n * sizeof (guint32));
6503                         target = ip + n * sizeof (guint32);
6504                         MONO_ADD_INS (bblock, ins);
6505                         GET_BBLOCK (cfg, tblock, target);
6506                         link_bblock (cfg, bblock, tblock);
6507                         ins->klass = GUINT_TO_POINTER (n);
6508                         ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (n + 1));
6509                         ins->inst_many_bb [n] = tblock;
6510
6511                         for (i = 0; i < n; ++i) {
6512                                 GET_BBLOCK (cfg, tblock, target + (gint32)read32(ip));
6513                                 link_bblock (cfg, bblock, tblock);
6514                                 ins->inst_many_bb [i] = tblock;
6515                                 ip += 4;
6516                         }
6517                         if (sp != stack_start) {
6518                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6519                                 sp = stack_start;
6520                                 CHECK_UNVERIFIABLE (cfg);
6521                         }
6522                         /* Needed by the code generated in inssel.brg */
6523                         mono_get_got_var (cfg);
6524                         inline_costs += (BRANCH_COST * 2);
6525                         break;
6526                 case CEE_LDIND_I1:
6527                 case CEE_LDIND_U1:
6528                 case CEE_LDIND_I2:
6529                 case CEE_LDIND_U2:
6530                 case CEE_LDIND_I4:
6531                 case CEE_LDIND_U4:
6532                 case CEE_LDIND_I8:
6533                 case CEE_LDIND_I:
6534                 case CEE_LDIND_R4:
6535                 case CEE_LDIND_R8:
6536                 case CEE_LDIND_REF:
6537                         CHECK_STACK (1);
6538                         MONO_INST_NEW (cfg, ins, *ip);
6539                         --sp;
6540                         ins->inst_i0 = *sp;
6541                         *sp++ = ins;
6542                         ins->type = ldind_type [*ip - CEE_LDIND_I1];
6543                         ins->flags |= ins_flag;
6544                         ins_flag = 0;
6545                         if (ins->type == STACK_OBJ)
6546                                 ins->klass = mono_defaults.object_class;
6547 #ifdef MONO_ARCH_SOFT_FLOAT
6548                         if (*ip == CEE_LDIND_R4) {
6549                                 int temp;
6550                                 --sp;
6551                                 temp = handle_load_float (cfg, bblock, ins->inst_i0, ip);
6552                                 NEW_TEMPLOAD (cfg, *sp, temp);
6553                                 sp++;
6554                         }
6555 #endif
6556                         ++ip;
6557                         break;
6558                 case CEE_STIND_REF:
6559                 case CEE_STIND_I1:
6560                 case CEE_STIND_I2:
6561                 case CEE_STIND_I4:
6562                 case CEE_STIND_I8:
6563                 case CEE_STIND_R4:
6564                 case CEE_STIND_R8:
6565                         CHECK_STACK (2);
6566 #ifdef MONO_ARCH_SOFT_FLOAT
6567                         if (*ip == CEE_STIND_R4) {
6568                                 sp -= 2;
6569                                 handle_store_float (cfg, bblock, sp [0], sp [1], ip);
6570                                 ip++;
6571                                 break;
6572                         }
6573 #endif
6574 #if HAVE_WRITE_BARRIERS
6575                         if (*ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !((sp [-1]->opcode == OP_PCONST) && (sp [-1]->inst_p0 == 0))) {
6576                                 /* insert call to write barrier */
6577                                 MonoMethod *write_barrier = mono_marshal_get_write_barrier ();
6578                                 sp -= 2;
6579                                 mono_emit_method_call_spilled (cfg, bblock, write_barrier, mono_method_signature (write_barrier), sp, ip, NULL);
6580                                 ip++;
6581                                 break;
6582                         }
6583 #endif
6584                         MONO_INST_NEW (cfg, ins, *ip);
6585                         ip++;
6586                         sp -= 2;
6587                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6588                         MONO_ADD_INS (bblock, ins);
6589                         ins->inst_i0 = sp [0];
6590                         ins->inst_i1 = sp [1];
6591                         ins->flags |= ins_flag;
6592                         ins_flag = 0;
6593                         inline_costs += 1;
6594                         break;
6595                 case CEE_MUL:
6596                         CHECK_STACK (2);
6597                         ADD_BINOP (*ip);
6598
6599 #ifdef MONO_ARCH_NO_EMULATE_MUL_IMM
6600                         /* FIXME: This breaks with ssapre (mono -O=ssapre loader.exe) */
6601                         if ((ins->inst_right->opcode == OP_ICONST) && !(cfg->opt & MONO_OPT_SSAPRE)) {
6602                                 switch (ins->opcode) {
6603                                 case CEE_MUL:
6604                                         ins->opcode = OP_IMUL_IMM;
6605                                         ins->inst_imm = ins->inst_right->inst_c0;
6606                                         break;
6607                                 case OP_LMUL:
6608                                         ins->opcode = OP_LMUL_IMM;
6609                                         ins->inst_imm = ins->inst_right->inst_c0;
6610                                         break;
6611                                 default:
6612                                         g_assert_not_reached ();
6613                                 }
6614                         }
6615 #endif
6616
6617                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
6618                                 --sp;
6619                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6620                         }
6621                         ip++;
6622                         break;
6623                 case CEE_ADD:
6624                 case CEE_SUB:
6625                 case CEE_DIV:
6626                 case CEE_DIV_UN:
6627                 case CEE_REM:
6628                 case CEE_REM_UN:
6629                 case CEE_AND:
6630                 case CEE_OR:
6631                 case CEE_XOR:
6632                 case CEE_SHL:
6633                 case CEE_SHR:
6634                 case CEE_SHR_UN:
6635                         CHECK_STACK (2);
6636                         ADD_BINOP (*ip);
6637                         /* special case that gives a nice speedup and happens to workaorund a ppc jit but (for the release)
6638                          * later apply the speedup to the left shift as well
6639                          * See BUG# 57957.
6640                          */
6641                         if ((ins->opcode == OP_LSHR_UN) && (ins->type == STACK_I8) 
6642                                         && (ins->inst_right->opcode == OP_ICONST) && (ins->inst_right->inst_c0 == 32)) {
6643                                 ins->opcode = OP_LONG_SHRUN_32;
6644                                 /*g_print ("applied long shr speedup to %s\n", cfg->method->name);*/
6645                                 ip++;
6646                                 break;
6647                         }
6648                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
6649                                 --sp;
6650                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6651                         }
6652                         ip++;
6653                         break;
6654                 case CEE_NEG:
6655                 case CEE_NOT:
6656                 case CEE_CONV_I1:
6657                 case CEE_CONV_I2:
6658                 case CEE_CONV_I4:
6659                 case CEE_CONV_R4:
6660                 case CEE_CONV_R8:
6661                 case CEE_CONV_U4:
6662                 case CEE_CONV_I8:
6663                 case CEE_CONV_U8:
6664                 case CEE_CONV_OVF_I8:
6665                 case CEE_CONV_OVF_U8:
6666                 case CEE_CONV_R_UN:
6667                         CHECK_STACK (1);
6668                         ADD_UNOP (*ip);
6669
6670 #ifdef MONO_ARCH_SOFT_FLOAT
6671                         /*
6672                          * Its rather hard to emit the soft float code during the decompose
6673                          * pass, so avoid it in some specific cases.
6674                          */
6675                         if (ins->opcode == OP_LCONV_TO_R4) {
6676                                 MonoInst *conv;
6677
6678                                 ins->opcode = OP_LCONV_TO_R8;
6679                                 ins->type = STACK_R8;
6680
6681                                 --sp;
6682                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6683
6684                                 MONO_INST_NEW (cfg, conv, CEE_CONV_R4);
6685                                 conv->inst_left = sp [-1];
6686                                 conv->type = STACK_R8;
6687                                 sp [-1] = ins;
6688
6689                                 ip++;
6690                                 break;
6691                         }
6692 #endif
6693
6694                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
6695                                 --sp;
6696                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6697                         }
6698                         ip++;                   
6699                         break;
6700                 case CEE_CONV_OVF_I4:
6701                 case CEE_CONV_OVF_I1:
6702                 case CEE_CONV_OVF_I2:
6703                 case CEE_CONV_OVF_I:
6704                 case CEE_CONV_OVF_U:
6705                         CHECK_STACK (1);
6706
6707                         if (sp [-1]->type == STACK_R8) {
6708                                 ADD_UNOP (CEE_CONV_OVF_I8);
6709                                 ADD_UNOP (*ip);
6710                         } else {
6711                                 ADD_UNOP (*ip);
6712                         }
6713
6714                         ip++;
6715                         break;
6716                 case CEE_CONV_OVF_U1:
6717                 case CEE_CONV_OVF_U2:
6718                 case CEE_CONV_OVF_U4:
6719                         CHECK_STACK (1);
6720
6721                         if (sp [-1]->type == STACK_R8) {
6722                                 ADD_UNOP (CEE_CONV_OVF_U8);
6723                                 ADD_UNOP (*ip);
6724                         } else {
6725                                 ADD_UNOP (*ip);
6726                         }
6727
6728                         ip++;
6729                         break;
6730                 case CEE_CONV_OVF_I1_UN:
6731                 case CEE_CONV_OVF_I2_UN:
6732                 case CEE_CONV_OVF_I4_UN:
6733                 case CEE_CONV_OVF_I8_UN:
6734                 case CEE_CONV_OVF_U1_UN:
6735                 case CEE_CONV_OVF_U2_UN:
6736                 case CEE_CONV_OVF_U4_UN:
6737                 case CEE_CONV_OVF_U8_UN:
6738                 case CEE_CONV_OVF_I_UN:
6739                 case CEE_CONV_OVF_U_UN:
6740                         CHECK_STACK (1);
6741                         ADD_UNOP (*ip);
6742                         ip++;
6743                         break;
6744                 case CEE_CPOBJ:
6745                         CHECK_OPSIZE (5);
6746                         CHECK_STACK (2);
6747                         token = read32 (ip + 1);
6748                         klass = mini_get_class (method, token, generic_context);
6749                         CHECK_TYPELOAD (klass);
6750                         sp -= 2;
6751                         if (generic_class_is_reference_type (cfg, klass)) {
6752                                 MonoInst *store, *load;
6753                                 MONO_INST_NEW (cfg, load, CEE_LDIND_REF);
6754                                 load->inst_i0 = sp [1];
6755                                 load->type = STACK_OBJ;
6756                                 load->klass = klass;
6757                                 load->flags |= ins_flag;
6758                                 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
6759                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
6760                                 MONO_ADD_INS (bblock, store);
6761                                 store->inst_i0 = sp [0];
6762                                 store->inst_i1 = load;
6763                                 store->flags |= ins_flag;
6764                         } else {
6765                                 guint32 align;
6766
6767                                 n = mono_class_value_size (klass, &align);
6768                                 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
6769                                         MonoInst *copy;
6770                                         NEW_MEMCPY (cfg, copy, sp [0], sp [1], n, align);
6771                                         MONO_ADD_INS (bblock, copy);
6772                                 } else {
6773                                         MonoMethod *memcpy_method = get_memcpy_method ();
6774                                         MonoInst *iargs [3];
6775                                         iargs [0] = sp [0];
6776                                         iargs [1] = sp [1];
6777                                         NEW_ICONST (cfg, iargs [2], n);
6778
6779                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6780                                 }
6781                         }
6782                         ins_flag = 0;
6783                         ip += 5;
6784                         break;
6785                 case CEE_LDOBJ: {
6786                         MonoInst *iargs [3];
6787                         int loc_index = -1;
6788                         int stloc_len = 0;
6789                         guint32 align;
6790
6791                         CHECK_OPSIZE (5);
6792                         CHECK_STACK (1);
6793                         --sp;
6794                         token = read32 (ip + 1);
6795                         klass = mini_get_class (method, token, generic_context);
6796                         CHECK_TYPELOAD (klass);
6797                         if (generic_class_is_reference_type (cfg, klass)) {
6798                                 MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
6799                                 ins->inst_i0 = sp [0];
6800                                 ins->type = STACK_OBJ;
6801                                 ins->klass = klass;
6802                                 ins->flags |= ins_flag;
6803                                 ins_flag = 0;
6804                                 *sp++ = ins;
6805                                 ip += 5;
6806                                 break;
6807                         }
6808
6809                         /* Optimize the common ldobj+stloc combination */
6810                         switch (ip [5]) {
6811                         case CEE_STLOC_S:
6812                                 loc_index = ip [6];
6813                                 stloc_len = 2;
6814                                 break;
6815                         case CEE_STLOC_0:
6816                         case CEE_STLOC_1:
6817                         case CEE_STLOC_2:
6818                         case CEE_STLOC_3:
6819                                 loc_index = ip [5] - CEE_STLOC_0;
6820                                 stloc_len = 1;
6821                                 break;
6822                         default:
6823                                 break;
6824                         }
6825
6826                         if ((loc_index != -1) && ip_in_bb (cfg, bblock, ip + 5)) {
6827                                 CHECK_LOCAL (loc_index);
6828                                 NEW_LOCSTORE (cfg, ins, loc_index, *sp);
6829
6830                                 /* FIXME: handle CEE_STIND_R4 */
6831                                 if (ins->opcode == CEE_STOBJ) {
6832                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6833                                         g_assert (ins->opcode == CEE_STOBJ);
6834                                         NEW_LOCLOADA (cfg, ins, loc_index);
6835                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
6836                                         ip += 5;
6837                                         ip += stloc_len;
6838                                         break;
6839                                 }
6840                         }
6841
6842                         n = mono_class_value_size (klass, &align);
6843                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
6844                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
6845                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
6846                                 MonoInst *copy;
6847                                 NEW_MEMCPY (cfg, copy, iargs [0], *sp, n, align);
6848                                 MONO_ADD_INS (bblock, copy);
6849                         } else {
6850                                 MonoMethod *memcpy_method = get_memcpy_method ();
6851                                 iargs [1] = *sp;
6852                                 NEW_ICONST (cfg, iargs [2], n);
6853
6854                                 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6855                         }
6856                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
6857                         ++sp;
6858                         ip += 5;
6859                         ins_flag = 0;
6860                         inline_costs += 1;
6861                         break;
6862                 }
6863                 case CEE_LDSTR:
6864                         CHECK_STACK_OVF (1);
6865                         CHECK_OPSIZE (5);
6866                         n = read32 (ip + 1);
6867
6868                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
6869                                 /* FIXME: moving GC */
6870                                 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
6871                                 ins->type = STACK_OBJ;
6872                                 ins->klass = mono_defaults.string_class;
6873                                 *sp = ins;
6874                         }
6875                         else if (method->wrapper_type != MONO_WRAPPER_NONE) {
6876                                 int temp;
6877                                 MonoInst *iargs [1];
6878
6879                                 NEW_PCONST (cfg, iargs [0], mono_method_get_wrapper_data (method, n));                          
6880                                 temp = mono_emit_jit_icall (cfg, bblock, mono_string_new_wrapper, iargs, ip);
6881                                 NEW_TEMPLOAD (cfg, *sp, temp);
6882
6883                         } else {
6884
6885                                 if (cfg->opt & MONO_OPT_SHARED) {
6886                                         int temp;
6887                                         MonoInst *iargs [3];
6888                                         MonoInst* domain_var;
6889                                         
6890                                         if (cfg->compile_aot) {
6891                                                 /* FIXME: bug when inlining methods from different assemblies (n is a token valid just in one). */
6892                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
6893                                         }
6894                                         /* avoid depending on undefined C behavior in sequence points */
6895                                         domain_var = mono_get_domainvar (cfg);
6896                                         NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
6897                                         NEW_IMAGECONST (cfg, iargs [1], image);
6898                                         NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
6899                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldstr, iargs, ip);
6900                                         NEW_TEMPLOAD (cfg, *sp, temp);
6901                                         mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
6902                                 } else {
6903                                         if (bblock->out_of_line) {
6904                                                 MonoInst *iargs [2];
6905                                                 int temp;
6906
6907                                                 if (cfg->method->klass->image == mono_defaults.corlib) {
6908                                                         /* 
6909                                                          * Avoid relocations and save some code size by using a 
6910                                                          * version of helper_ldstr specialized to mscorlib.
6911                                                          */
6912                                                         NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
6913                                                         temp = mono_emit_jit_icall (cfg, bblock, mono_helper_ldstr_mscorlib, iargs, ip);
6914                                                 } else {
6915                                                         /* Avoid creating the string object */
6916                                                         NEW_IMAGECONST (cfg, iargs [0], image);
6917                                                         NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
6918                                                         temp = mono_emit_jit_icall (cfg, bblock, mono_helper_ldstr, iargs, ip);
6919                                                 }
6920                                                 NEW_TEMPLOAD (cfg, *sp, temp);
6921                                         } 
6922                                         else
6923                                         if (cfg->compile_aot) {
6924                                                 NEW_LDSTRCONST (cfg, ins, image, n);
6925                                                 *sp = ins;
6926                                         } 
6927                                         else {
6928                                                 NEW_PCONST (cfg, ins, NULL);
6929                                                 ins->type = STACK_OBJ;
6930                                                 ins->inst_p0 = mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
6931                                                 ins->klass = mono_defaults.string_class;
6932                                                 *sp = ins;
6933                                         }
6934                                 }
6935                         }
6936
6937                         sp++;
6938                         ip += 5;
6939                         break;
6940                 case CEE_NEWOBJ: {
6941                         MonoInst *iargs [2];
6942                         MonoMethodSignature *fsig;
6943                         MonoInst this_ins;
6944                         int temp;
6945
6946                         CHECK_OPSIZE (5);
6947                         token = read32 (ip + 1);
6948                         cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
6949                         if (!cmethod)
6950                                 goto load_error;
6951                         fsig = mono_method_get_signature (cmethod, image, token);
6952
6953                         mono_save_token_info (cfg, image, token, cmethod);
6954
6955                         if (!mono_class_init (cmethod->klass))
6956                                 goto load_error;
6957
6958                         if (cfg->generic_sharing_context)
6959                                 context_used = mono_method_check_context_used (cmethod);
6960
6961                         if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
6962                                 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
6963                                         INLINE_FAILURE;
6964                                 CHECK_CFG_EXCEPTION;
6965                         } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
6966                                 ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
6967                         }
6968
6969                         n = fsig->param_count;
6970                         CHECK_STACK (n);
6971  
6972                         /* 
6973                          * Generate smaller code for the common newobj <exception> instruction in
6974                          * argument checking code.
6975                          */
6976                         if (bblock->out_of_line && cmethod->klass->image == mono_defaults.corlib && n <= 2 && 
6977                                 ((n < 1) || (!fsig->params [0]->byref && fsig->params [0]->type == MONO_TYPE_STRING)) && 
6978                                 ((n < 2) || (!fsig->params [1]->byref && fsig->params [1]->type == MONO_TYPE_STRING))) {
6979                                 MonoInst *iargs [3];
6980                                 int temp;
6981                                 
6982                                 sp -= n;
6983
6984                                 NEW_ICONST (cfg, iargs [0], cmethod->klass->type_token);
6985                                 switch (n) {
6986                                 case 0:
6987                                         temp = mono_emit_jit_icall (cfg, bblock, mono_create_corlib_exception_0, iargs, ip);
6988                                         break;
6989                                 case 1:
6990                                         iargs [1] = sp [0];
6991                                         temp = mono_emit_jit_icall (cfg, bblock, mono_create_corlib_exception_1, iargs, ip);
6992                                         break;
6993                                 case 2:
6994                                         iargs [1] = sp [0];
6995                                         iargs [2] = sp [1];
6996                                         temp = mono_emit_jit_icall (cfg, bblock, mono_create_corlib_exception_2, iargs, ip);
6997                                         break;
6998                                 default:
6999                                         g_assert_not_reached ();
7000                                 }
7001                                 NEW_TEMPLOAD (cfg, ins, temp);
7002                                 *sp ++ = ins;
7003
7004                                 ip += 5;
7005                                 inline_costs += 5;
7006                                 break;
7007                         }
7008
7009                         /* move the args to allow room for 'this' in the first position */
7010                         while (n--) {
7011                                 --sp;
7012                                 sp [1] = sp [0];
7013                         }
7014
7015                         /* check_call_signature () requires sp[0] to be set */
7016                         this_ins.type = STACK_OBJ;
7017                         sp [0] = &this_ins;
7018                         if (check_call_signature (cfg, fsig, sp))
7019                                 UNVERIFIED;
7020
7021                         handle_loaded_temps (cfg, bblock, stack_start, sp);
7022
7023                         if (mini_class_is_system_array (cmethod->klass)) {
7024                                 g_assert (!context_used);
7025
7026                                 NEW_METHODCONST (cfg, *sp, cmethod);
7027
7028                                 if (fsig->param_count == 2)
7029                                         /* Avoid varargs in the common case */
7030                                         temp = mono_emit_jit_icall (cfg, bblock, mono_array_new_2, sp, ip);
7031                                 else
7032                                         temp = handle_array_new (cfg, bblock, fsig->param_count, sp, ip);
7033                         } else if (cmethod->string_ctor) {
7034                                 g_assert (!context_used);
7035
7036                                 /* we simply pass a null pointer */
7037                                 NEW_PCONST (cfg, *sp, NULL); 
7038                                 /* now call the string ctor */
7039                                 temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, NULL);
7040                         } else {
7041                                 MonoInst* callvirt_this_arg = NULL;
7042                                 
7043                                 if (cmethod->klass->valuetype) {
7044                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
7045                                         temp = iargs [0]->inst_c0;
7046
7047                                         NEW_TEMPLOADA (cfg, *sp, temp);
7048
7049                                         handle_initobj (cfg, bblock, *sp, NULL, cmethod->klass, stack_start, sp);
7050
7051                                         NEW_TEMPLOADA (cfg, *sp, temp);
7052
7053                                         /* 
7054                                          * The code generated by mini_emit_virtual_call () expects
7055                                          * iargs [0] to be a boxed instance, but luckily the vcall
7056                                          * will be transformed into a normal call there.
7057                                          */
7058                                 } else if (context_used) {
7059                                         MonoInst *rgctx, *data;
7060                                         int rgctx_info;
7061
7062                                         GET_RGCTX (rgctx, context_used);
7063                                         if (cfg->opt & MONO_OPT_SHARED)
7064                                                 rgctx_info = MONO_RGCTX_INFO_KLASS;
7065                                         else
7066                                                 rgctx_info = MONO_RGCTX_INFO_VTABLE;
7067                                         data = get_runtime_generic_context_ptr (cfg, method, context_used, bblock,
7068                                                 cmethod->klass, generic_context, rgctx, rgctx_info, ip);
7069
7070                                         temp = handle_alloc_from_inst (cfg, bblock, cmethod->klass, data, FALSE, ip);
7071                                         NEW_TEMPLOAD (cfg, *sp, temp);
7072                                 } else {
7073                                         MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
7074
7075                                         CHECK_TYPELOAD (cmethod->klass);
7076                                         if (mini_field_access_needs_cctor_run (cfg, method, vtable) && !(g_slist_find (class_inits, vtable))) {
7077                                                 guint8 *tramp = mono_create_class_init_trampoline (vtable);
7078                                                 mono_emit_native_call (cfg, bblock, tramp, 
7079                                                                                            helper_sig_class_init_trampoline,
7080                                                                                            NULL, ip, FALSE, FALSE);
7081                                                 if (cfg->verbose_level > 2)
7082                                                         g_print ("class %s.%s needs init call for ctor\n", cmethod->klass->name_space, cmethod->klass->name);
7083                                                 class_inits = g_slist_prepend (class_inits, vtable);
7084                                         }
7085                                         temp = handle_alloc (cfg, bblock, cmethod->klass, FALSE, ip);
7086                                         NEW_TEMPLOAD (cfg, *sp, temp);
7087                                 }
7088
7089                                 /* Avoid virtual calls to ctors if possible */
7090                                 if (cmethod->klass->marshalbyref)
7091                                         callvirt_this_arg = sp [0];
7092                                 
7093                                 if ((cfg->opt & MONO_OPT_INLINE) && cmethod && !context_used &&
7094                                     mono_method_check_inlining (cfg, cmethod) &&
7095                                     !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE) &&
7096                                     !g_list_find (dont_inline, cmethod)) {
7097                                         int costs;
7098                                         MonoBasicBlock *ebblock;
7099                                         if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, FALSE))) {
7100
7101                                                 ip += 5;
7102                                                 real_offset += 5;
7103                                                 
7104                                                 GET_BBLOCK (cfg, bblock, ip);
7105                                                 ebblock->next_bb = bblock;
7106                                                 link_bblock (cfg, ebblock, bblock);
7107
7108                                                 NEW_TEMPLOAD (cfg, *sp, temp);
7109                                                 sp++;
7110
7111                                                 /* indicates start of a new block, and triggers a load 
7112                                                    of all stack arguments at bb boundarie */
7113                                                 bblock = ebblock;
7114
7115                                                 inline_costs += costs;
7116                                                 break;
7117                                                 
7118                                         } else {
7119                                                 /* Prevent inlining of methods which call other methods */
7120                                                 INLINE_FAILURE;
7121                                                 mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
7122                                         }
7123                                 } else if (context_used &&
7124                                                 (cmethod->klass->valuetype ||
7125                                                 !mono_method_is_generic_sharable_impl (cmethod, TRUE))) {
7126                                         MonoInst *rgctx, *cmethod_addr;
7127
7128                                         g_assert (!callvirt_this_arg);
7129
7130                                         GET_RGCTX (rgctx, context_used);
7131                                         cmethod_addr = get_runtime_generic_context_method (cfg, method, context_used,
7132                                                         bblock, cmethod,
7133                                                         generic_context, rgctx, MONO_RGCTX_INFO_GENERIC_METHOD_CODE, ip);
7134
7135                                         mono_emit_calli_spilled (cfg, bblock, fsig, sp, cmethod_addr, ip);
7136                                 } else {
7137                                         /* Prevent inlining of methods which call other methods */
7138                                         INLINE_FAILURE;
7139                                         /* now call the actual ctor */
7140                                         mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
7141                                 }
7142                         }
7143
7144                         NEW_TEMPLOAD (cfg, *sp, temp);
7145                         sp++;
7146                         
7147                         ip += 5;
7148                         inline_costs += 5;
7149                         break;
7150                 }
7151                 case CEE_ISINST:
7152                         CHECK_STACK (1);
7153                         --sp;
7154                         CHECK_OPSIZE (5);
7155                         token = read32 (ip + 1);
7156                         klass = mini_get_class (method, token, generic_context);
7157                         CHECK_TYPELOAD (klass);
7158                         if (sp [0]->type != STACK_OBJ)
7159                                 UNVERIFIED;
7160
7161                         if (cfg->generic_sharing_context)
7162                                 context_used = mono_class_check_context_used (klass);
7163
7164                         /* Needed by the code generated in inssel.brg */
7165                         if (!context_used)
7166                                 mono_get_got_var (cfg);
7167
7168                         if (context_used) {
7169                                 MonoInst *rgctx, *args [2];
7170                                 int temp;
7171
7172                                 /* obj */
7173                                 args [0] = *sp;
7174
7175                                 /* klass */
7176                                 GET_RGCTX (rgctx, context_used);
7177                                 args [1] = get_runtime_generic_context_ptr (cfg, method, context_used, bblock, klass,
7178                                         generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
7179
7180                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_isinst, args, ip);
7181                                 NEW_TEMPLOAD (cfg, *sp, temp);
7182
7183                                 sp++;
7184                                 ip += 5;
7185                                 inline_costs += 2;
7186                         } else if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
7187                         
7188                                 MonoMethod *mono_isinst;
7189                                 MonoInst *iargs [1];
7190                                 MonoBasicBlock *ebblock;
7191                                 int costs;
7192                                 int temp;
7193                                 
7194                                 mono_isinst = mono_marshal_get_isinst (klass); 
7195                                 iargs [0] = sp [0];
7196                                 
7197                                 costs = inline_method (cfg, mono_isinst, mono_method_signature (mono_isinst), bblock, 
7198                                                        iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
7199                         
7200                                 g_assert (costs > 0);
7201                                 
7202                                 ip += 5;
7203                                 real_offset += 5;
7204                         
7205                                 GET_BBLOCK (cfg, bblock, ip);
7206                                 ebblock->next_bb = bblock;
7207                                 link_bblock (cfg, ebblock, bblock);
7208
7209                                 temp = iargs [0]->inst_i0->inst_c0;
7210                                 NEW_TEMPLOAD (cfg, *sp, temp);
7211                                 
7212                                 sp++;
7213                                 bblock = ebblock;
7214                                 inline_costs += costs;
7215                         } else {
7216                                 MONO_INST_NEW (cfg, ins, *ip);
7217                                 ins->type = STACK_OBJ;
7218                                 ins->inst_left = *sp;
7219                                 ins->inst_newa_class = klass;
7220                                 ins->klass = klass;
7221                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
7222                                 ip += 5;
7223                         }
7224                         break;
7225                 case CEE_UNBOX_ANY: {
7226                         MonoInst *iargs [3];
7227                         guint32 align;
7228
7229                         CHECK_STACK (1);
7230                         --sp;
7231                         CHECK_OPSIZE (5);
7232                         token = read32 (ip + 1);
7233                         klass = mini_get_class (method, token, generic_context);
7234                         CHECK_TYPELOAD (klass);
7235
7236                         if (cfg->generic_sharing_context)
7237                                 context_used = mono_class_check_context_used (klass);
7238
7239                         if (generic_class_is_reference_type (cfg, klass)) {
7240                                 switch (emit_castclass (klass, token, context_used, FALSE,
7241                                                 cfg, method, arg_array, param_types, dont_inline, end, header,
7242                                                 generic_context, &bblock, &ip, &sp, &inline_costs, &real_offset)) {
7243                                 case 0: break;
7244                                 case -1: goto unverified;
7245                                 case -2: goto exception_exit;
7246                                 default: g_assert_not_reached ();
7247                                 }
7248                                 break;
7249                         }
7250
7251                         if (mono_class_is_nullable (klass)) {
7252                                 int v;
7253                                 MonoInst *rgctx = NULL;
7254
7255                                 if (context_used)
7256                                         GET_RGCTX (rgctx, context_used);
7257
7258                                 v = handle_unbox_nullable (cfg, method, context_used, bblock, *sp, ip, klass,
7259                                         generic_context, rgctx);
7260                                 NEW_TEMPLOAD (cfg, *sp, v);
7261                                 sp ++;
7262                                 ip += 5;
7263                                 break;
7264                         }
7265
7266                         switch (emit_unbox (klass, token, context_used,
7267                                         cfg, method, arg_array, param_types, dont_inline, end, header,
7268                                         generic_context, &bblock, &ip, &sp, &inline_costs, &real_offset)) {
7269                         case 0: break;
7270                         case -1: goto unverified;
7271                         case -2: goto exception_exit;
7272                         default: g_assert_not_reached ();
7273                         }
7274                         ip += 5;
7275                         /* LDOBJ impl */
7276                         n = mono_class_value_size (klass, &align);
7277                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
7278                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
7279                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
7280                                 MonoInst *copy;
7281                                 NEW_MEMCPY (cfg, copy, iargs [0], *sp, n, align);
7282                                 MONO_ADD_INS (bblock, copy);
7283                         } else {
7284                                 MonoMethod *memcpy_method = get_memcpy_method ();
7285                                 iargs [1] = *sp;
7286                                 NEW_ICONST (cfg, iargs [2], n);
7287
7288                                 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
7289                         }
7290                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
7291                         ++sp;
7292                         inline_costs += 2;
7293                         break;
7294                 }
7295                 case CEE_UNBOX:
7296                         CHECK_STACK (1);
7297                         --sp;
7298                         CHECK_OPSIZE (5);
7299                         token = read32 (ip + 1);
7300                         klass = mini_get_class (method, token, generic_context);
7301                         CHECK_TYPELOAD (klass);
7302
7303                         if (cfg->generic_sharing_context)
7304                                 context_used = mono_class_check_context_used (klass);
7305
7306                         if (mono_class_is_nullable (klass)) {
7307                                 int v;
7308                                 MonoInst *rgctx = NULL;
7309
7310                                 if (context_used)
7311                                         GET_RGCTX (rgctx, context_used);
7312                                 v = handle_unbox_nullable (cfg, method, context_used, bblock, *sp, ip, klass,
7313                                         generic_context, rgctx);
7314                                 NEW_TEMPLOAD (cfg, *sp, v);
7315                                 sp ++;
7316                                 ip += 5;
7317                                 break;
7318                         }
7319
7320                         switch (emit_unbox (klass, token, context_used,
7321                                         cfg, method, arg_array, param_types, dont_inline, end, header,
7322                                         generic_context, &bblock, &ip, &sp, &inline_costs, &real_offset)) {
7323                         case 0: break;
7324                         case -1: goto unverified;
7325                         case -2: goto exception_exit;
7326                         default: g_assert_not_reached ();
7327                         }
7328
7329                         sp++;
7330                         ip += 5;
7331                         inline_costs += 2;
7332                         break;
7333                 case CEE_CASTCLASS:
7334                         CHECK_STACK (1);
7335                         --sp;
7336                         CHECK_OPSIZE (5);
7337                         token = read32 (ip + 1);
7338                         klass = mini_get_class (method, token, generic_context);
7339                         CHECK_TYPELOAD (klass);
7340                         if (sp [0]->type != STACK_OBJ)
7341                                 UNVERIFIED;
7342
7343                         if (cfg->generic_sharing_context)
7344                                 context_used = mono_class_check_context_used (klass);
7345
7346                         switch (emit_castclass (klass, token, context_used, TRUE,
7347                                         cfg, method, arg_array, param_types, dont_inline, end, header,
7348                                         generic_context, &bblock, &ip, &sp, &inline_costs, &real_offset)) {
7349                         case 0: break;
7350                         case -1: goto unverified;
7351                         case -2: goto exception_exit;
7352                         default: g_assert_not_reached ();
7353                         }
7354                         break;
7355                 case CEE_THROW:
7356                         CHECK_STACK (1);
7357                         MONO_INST_NEW (cfg, ins, OP_THROW);
7358                         --sp;
7359                         ins->inst_left = *sp;
7360                         ip++;
7361                         bblock->out_of_line = TRUE;
7362                         MONO_ADD_INS (bblock, ins);
7363                         MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
7364                         ins->cil_code = ip - 1;
7365                         MONO_ADD_INS (bblock, ins);
7366                         sp = stack_start;
7367                         
7368                         link_bblock (cfg, bblock, end_bblock);
7369                         start_new_bblock = 1;
7370                         break;
7371                 case CEE_LDFLD:
7372                 case CEE_LDFLDA:
7373                 case CEE_STFLD: {
7374                         MonoInst *offset_ins;
7375                         MonoClassField *field;
7376                         MonoBasicBlock *ebblock;
7377                         int costs;
7378                         guint foffset;
7379
7380                         if (*ip == CEE_STFLD) {
7381                                 CHECK_STACK (2);
7382                                 sp -= 2;
7383                         } else {
7384                                 CHECK_STACK (1);
7385                                 --sp;
7386                         }
7387                         if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
7388                                 UNVERIFIED;
7389                         if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
7390                                 UNVERIFIED;
7391                         CHECK_OPSIZE (5);
7392                         token = read32 (ip + 1);
7393                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
7394                                 field = mono_method_get_wrapper_data (method, token);
7395                                 klass = field->parent;
7396                         } else {
7397                                 field = mono_field_from_token (image, token, &klass, generic_context);
7398                         }
7399                         if (!field)
7400                                 goto load_error;
7401                         mono_class_init (klass);
7402                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
7403                                 FIELD_ACCESS_FAILURE;
7404
7405                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
7406                         /* FIXME: mark instructions for use in SSA */
7407                         if (*ip == CEE_STFLD) {
7408                                 if (target_type_is_incompatible (cfg, field->type, sp [1]))
7409                                         UNVERIFIED;
7410                                 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
7411                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
7412                                         MonoInst *iargs [5];
7413
7414                                         iargs [0] = sp [0];
7415                                         NEW_CLASSCONST (cfg, iargs [1], klass);
7416                                         NEW_FIELDCONST (cfg, iargs [2], field);
7417                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
7418                                                     field->offset);
7419                                         iargs [4] = sp [1];
7420
7421                                         if (cfg->opt & MONO_OPT_INLINE) {
7422                                                 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), bblock, 
7423                                                                 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
7424                                                 g_assert (costs > 0);
7425                                                       
7426                                                 ip += 5;
7427                                                 real_offset += 5;
7428
7429                                                 GET_BBLOCK (cfg, bblock, ip);
7430                                                 ebblock->next_bb = bblock;
7431                                                 link_bblock (cfg, ebblock, bblock);
7432
7433                                                 /* indicates start of a new block, and triggers a load 
7434                                                    of all stack arguments at bb boundarie */
7435                                                 bblock = ebblock;
7436
7437                                                 inline_costs += costs;
7438                                                 break;
7439                                         } else {
7440                                                 mono_emit_method_call_spilled (cfg, bblock, stfld_wrapper, mono_method_signature (stfld_wrapper), iargs, ip, NULL);
7441                                         }
7442 #if HAVE_WRITE_BARRIERS
7443                                 } else if (mini_type_to_stind (cfg, field->type) == CEE_STIND_REF && !(sp [1]->opcode == OP_PCONST && sp [1]->inst_c0 == 0)) {
7444                                         /* insert call to write barrier */
7445                                         MonoMethod *write_barrier = mono_marshal_get_write_barrier ();
7446                                         MonoInst *iargs [2];
7447                                         NEW_ICONST (cfg, offset_ins, foffset);
7448                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7449                                         ins->inst_left = *sp;
7450                                         ins->inst_right = offset_ins;
7451                                         ins->type = STACK_MP;
7452                                         ins->klass = mono_defaults.object_class;
7453                                         iargs [0] = ins;
7454                                         iargs [1] = sp [1];
7455                                         mono_emit_method_call_spilled (cfg, bblock, write_barrier, mono_method_signature (write_barrier), iargs, ip, NULL);
7456 #endif
7457 #ifdef MONO_ARCH_SOFT_FLOAT
7458                                 } else if (mini_type_to_stind (cfg, field->type) == CEE_STIND_R4) {
7459                                         NEW_ICONST (cfg, offset_ins, foffset);
7460                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7461                                         ins->inst_left = *sp;
7462                                         ins->inst_right = offset_ins;
7463                                         ins->type = STACK_MP;
7464                                         ins->klass = mono_defaults.object_class;
7465                                         handle_store_float (cfg, bblock, ins, sp [1], ip);
7466 #endif
7467                                 } else {
7468                                         MonoInst *store;
7469                                         NEW_ICONST (cfg, offset_ins, foffset);
7470                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7471                                         ins->inst_left = *sp;
7472                                         ins->inst_right = offset_ins;
7473                                         ins->type = STACK_MP;
7474
7475                                         MONO_INST_NEW (cfg, store, mini_type_to_stind (cfg, field->type));
7476                                         store->inst_left = ins;
7477                                         store->inst_right = sp [1];
7478                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
7479                                         store->flags |= ins_flag;
7480                                         ins_flag = 0;
7481                                         if (store->opcode == CEE_STOBJ) {
7482                                                 handle_stobj (cfg, bblock, ins, sp [1], ip, 
7483                                                               mono_class_from_mono_type (field->type), FALSE, FALSE, TRUE);
7484                                         } else
7485                                                 MONO_ADD_INS (bblock, store);
7486                                 }
7487                         } else {
7488                                 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
7489                                         MonoMethod *wrapper = (*ip == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type); 
7490                                         MonoInst *iargs [4];
7491                                         int temp;
7492                                         
7493                                         iargs [0] = sp [0];
7494                                         NEW_CLASSCONST (cfg, iargs [1], klass);
7495                                         NEW_FIELDCONST (cfg, iargs [2], field);
7496                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
7497                                         if ((cfg->opt & MONO_OPT_INLINE) && !MONO_TYPE_ISSTRUCT (mono_method_signature (wrapper)->ret)) {
7498                                                 costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), bblock, 
7499                                                                 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
7500                                                 g_assert (costs > 0);
7501                                                       
7502                                                 ip += 5;
7503                                                 real_offset += 5;
7504
7505                                                 GET_BBLOCK (cfg, bblock, ip);
7506                                                 ebblock->next_bb = bblock;
7507                                                 link_bblock (cfg, ebblock, bblock);
7508
7509                                                 temp = iargs [0]->inst_i0->inst_c0;
7510
7511                                                 NEW_TEMPLOAD (cfg, *sp, temp);
7512                                                 sp++;
7513
7514                                                 /* indicates start of a new block, and triggers a load of
7515                                                    all stack arguments at bb boundarie */
7516                                                 bblock = ebblock;
7517                                                 
7518                                                 inline_costs += costs;
7519                                                 break;
7520                                         } else {
7521                                                 temp = mono_emit_method_call_spilled (cfg, bblock, wrapper, mono_method_signature (wrapper), iargs, ip, NULL);
7522                                                 NEW_TEMPLOAD (cfg, *sp, temp);
7523                                                 NEW_TEMPLOAD_SOFT_FLOAT (cfg, bblock, *sp, temp, ip);
7524                                                 sp++;
7525                                         }
7526                                 } else {
7527                                         NEW_ICONST (cfg, offset_ins, foffset);
7528                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7529                                         ins->inst_left = *sp;
7530                                         ins->inst_right = offset_ins;
7531                                         ins->type = STACK_MP;
7532
7533                                         if (*ip == CEE_LDFLDA) {
7534                                                 ins->klass = mono_class_from_mono_type (field->type);
7535                                                 *sp++ = ins;
7536                                         } else {
7537                                                 MonoInst *load;
7538                                                 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, field->type));
7539                                                 type_to_eval_stack_type (cfg, field->type, load);
7540                                                 load->inst_left = ins;
7541                                                 load->flags |= ins_flag;
7542                                                 ins_flag = 0;
7543 #ifdef MONO_ARCH_SOFT_FLOAT
7544                                                 if (mini_type_to_ldind (cfg, field->type) == CEE_LDIND_R4) {
7545                                                         int temp;
7546                                                         temp = handle_load_float (cfg, bblock, ins, ip);
7547                                                         NEW_TEMPLOAD (cfg, *sp, temp);
7548                                                         sp++;
7549                                                 } else
7550 #endif
7551                                                 *sp++ = load;
7552                                         }
7553                                 }
7554                         }
7555                         ip += 5;
7556                         break;
7557                 }
7558                 case CEE_LDSFLD:
7559                 case CEE_LDSFLDA:
7560                 case CEE_STSFLD: {
7561                         MonoClassField *field;
7562                         gboolean is_special_static;
7563                         gpointer addr = NULL;
7564
7565                         CHECK_OPSIZE (5);
7566                         token = read32 (ip + 1);
7567                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
7568                                 field = mono_method_get_wrapper_data (method, token);
7569                                 klass = field->parent;
7570                         }
7571                         else
7572                                 field = mono_field_from_token (image, token, &klass, generic_context);
7573                         if (!field)
7574                                 goto load_error;
7575                         mono_class_init (klass);
7576                         if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
7577                                 FIELD_ACCESS_FAILURE;
7578
7579                         /*
7580                          * We can only support shared generic static
7581                          * field access on architectures where the
7582                          * trampoline code has been extended to handle
7583                          * the generic class init.
7584                          */
7585 #ifndef MONO_ARCH_VTABLE_REG
7586                         GENERIC_SHARING_FAILURE (*ip);
7587 #endif
7588
7589                         if (cfg->generic_sharing_context)
7590                                 context_used = mono_class_check_context_used (klass);
7591
7592                         g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL));
7593
7594                         if ((*ip) == CEE_STSFLD)
7595                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
7596
7597                         is_special_static = mono_class_field_is_special_static (field);
7598
7599                         if ((cfg->opt & MONO_OPT_SHARED) ||
7600                                         (cfg->compile_aot && is_special_static) ||
7601                                         (context_used && is_special_static)) {
7602                                 int temp;
7603                                 MonoInst *iargs [2];
7604
7605                                 g_assert (field->parent);
7606                                 if ((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) {
7607                                         MonoInst *domain_var;
7608                                         /* avoid depending on undefined C behavior in sequence points */
7609                                         domain_var = mono_get_domainvar (cfg);
7610                                         NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
7611                                 } else {
7612                                         NEW_DOMAINCONST (cfg, iargs [0]);
7613                                 }
7614                                 if (context_used) {
7615                                         MonoInst *rgctx;
7616
7617                                         GET_RGCTX (rgctx, context_used);
7618                                         iargs [1] = get_runtime_generic_context_field (cfg, method, context_used,
7619                                                         bblock, field,
7620                                                         generic_context, rgctx, MONO_RGCTX_INFO_CLASS_FIELD, ip);
7621                                 } else {
7622                                         NEW_FIELDCONST (cfg, iargs [1], field);
7623                                 }
7624                                 temp = mono_emit_jit_icall (cfg, bblock, mono_class_static_field_address, iargs, ip);
7625                                 NEW_TEMPLOAD (cfg, ins, temp);
7626                         } else if (context_used) {
7627                                 MonoInst *rgctx, *static_data;
7628
7629                                 /*
7630                                 g_print ("sharing static field access in %s.%s.%s - depth %d offset %d\n",
7631                                         method->klass->name_space, method->klass->name, method->name,
7632                                         depth, field->offset);
7633                                 */
7634
7635                                 if (mono_class_needs_cctor_run (klass, method)) {
7636                                         MonoMethodSignature *sig = helper_sig_generic_class_init_trampoline;
7637                                         MonoCallInst *call;
7638                                         MonoInst *vtable, *rgctx;
7639
7640                                         GET_RGCTX (rgctx, context_used);
7641                                         vtable = get_runtime_generic_context_ptr (cfg, method, context_used, bblock, klass,
7642                                                         generic_context, rgctx, MONO_RGCTX_INFO_VTABLE, ip);
7643
7644                                         call = mono_emit_call_args (cfg, bblock, sig, NULL, FALSE, FALSE, ip, FALSE);
7645                                         call->inst.opcode = OP_TRAMPCALL_VTABLE;
7646                                         call->fptr = mono_get_trampoline_code (MONO_TRAMPOLINE_GENERIC_CLASS_INIT);
7647
7648                                         call->inst.inst_left = vtable;
7649
7650                                         mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
7651                                 }
7652
7653                                 /*
7654                                  * The pointer we're computing here is
7655                                  *
7656                                  *   super_info.static_data + field->offset
7657                                  */
7658                                 GET_RGCTX (rgctx, context_used);
7659                                 static_data = get_runtime_generic_context_ptr (cfg, method, context_used, bblock, klass,
7660                                         generic_context, rgctx, MONO_RGCTX_INFO_STATIC_DATA, ip);
7661
7662                                 if (field->offset == 0) {
7663                                         ins = static_data;
7664                                 } else {
7665                                         MonoInst *field_offset;
7666
7667                                         NEW_ICONST (cfg, field_offset, field->offset);
7668
7669                                         MONO_INST_NEW (cfg, ins, OP_PADD);
7670                                         ins->inst_left = static_data;
7671                                         ins->inst_right = field_offset;
7672                                         ins->type = STACK_PTR;
7673                                         ins->klass = klass;
7674                                 }
7675                         } else {
7676                                 MonoVTable *vtable;
7677
7678                                 vtable = mono_class_vtable (cfg->domain, klass);
7679                                 CHECK_TYPELOAD (klass);
7680                                 if (!is_special_static) {
7681                                         if (mini_field_access_needs_cctor_run (cfg, method, vtable) && !(g_slist_find (class_inits, vtable))) {
7682                                                 guint8 *tramp = mono_create_class_init_trampoline (vtable);
7683                                                 mono_emit_native_call (cfg, bblock, tramp, 
7684                                                                                            helper_sig_class_init_trampoline,
7685                                                                                            NULL, ip, FALSE, FALSE);
7686                                                 if (cfg->verbose_level > 2)
7687                                                         g_print ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, field->name);
7688                                                 class_inits = g_slist_prepend (class_inits, vtable);
7689                                         } else {
7690                                                 if (cfg->run_cctors) {
7691                                                         /* This makes so that inline cannot trigger */
7692                                                         /* .cctors: too many apps depend on them */
7693                                                         /* running with a specific order... */
7694                                                         if (! vtable->initialized)
7695                                                                 INLINE_FAILURE;
7696                                                         mono_runtime_class_init (vtable);
7697                                                 }
7698                                         }
7699                                         addr = (char*)vtable->data + field->offset;
7700
7701                                         if (cfg->compile_aot)
7702                                                 NEW_SFLDACONST (cfg, ins, field);
7703                                         else
7704                                                 NEW_PCONST (cfg, ins, addr);
7705                                 } else {
7706                                         int temp;
7707                                         MonoInst *iargs [1];
7708
7709                                         /* The special_static_fields
7710                                          * field is init'd in
7711                                          * mono_class_vtable, so it
7712                                          * needs to be called here.
7713                                          */
7714                                         if (!(cfg->opt & MONO_OPT_SHARED)) {
7715                                                 mono_class_vtable (cfg->domain, klass);
7716                                                 CHECK_TYPELOAD (klass);
7717                                         }
7718                                         mono_domain_lock (cfg->domain);
7719                                         if (cfg->domain->special_static_fields)
7720                                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
7721                                         mono_domain_unlock (cfg->domain);
7722
7723                                         /* 
7724                                          * insert call to mono_threads_get_static_data (GPOINTER_TO_UINT (addr)) 
7725                                          * This could be later optimized to do just a couple of
7726                                          * memory dereferences with constant offsets.
7727                                          */
7728                                         NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
7729                                         temp = mono_emit_jit_icall (cfg, bblock, mono_get_special_static_data, iargs, ip);
7730                                         NEW_TEMPLOAD (cfg, ins, temp);
7731                                 }
7732                         }
7733
7734                         /* FIXME: mark instructions for use in SSA */
7735                         if (*ip == CEE_LDSFLDA) {
7736                                 ins->klass = mono_class_from_mono_type (field->type);
7737                                 *sp++ = ins;
7738                         } else if (*ip == CEE_STSFLD) {
7739                                 MonoInst *store;
7740                                 CHECK_STACK (1);
7741                                 sp--;
7742                                 MONO_INST_NEW (cfg, store, mini_type_to_stind (cfg, field->type));
7743                                 store->inst_left = ins;
7744                                 store->inst_right = sp [0];
7745                                 store->flags |= ins_flag;
7746                                 ins_flag = 0;
7747
7748 #ifdef MONO_ARCH_SOFT_FLOAT
7749                                 if (store->opcode == CEE_STIND_R4)
7750                                         handle_store_float (cfg, bblock, ins, sp [0], ip);
7751                                 else
7752 #endif
7753                                 if (store->opcode == CEE_STOBJ) {
7754                                         handle_stobj (cfg, bblock, ins, sp [0], ip, mono_class_from_mono_type (field->type), FALSE, FALSE, FALSE);
7755                                 } else
7756                                         MONO_ADD_INS (bblock, store);
7757                         } else {
7758                                 gboolean is_const = FALSE;
7759                                 MonoVTable *vtable = NULL;
7760
7761                                 if (!context_used)
7762                                         vtable = mono_class_vtable (cfg->domain, klass);
7763
7764                                 CHECK_TYPELOAD (klass);
7765                                 if (!context_used && !((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) && 
7766                                     vtable->initialized && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY)) {
7767                                         gpointer addr = (char*)vtable->data + field->offset;
7768                                         int ro_type = field->type->type;
7769                                         if (ro_type == MONO_TYPE_VALUETYPE && field->type->data.klass->enumtype) {
7770                                                 ro_type = field->type->data.klass->enum_basetype->type;
7771                                         }
7772                                         /* g_print ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, field->name);*/
7773                                         is_const = TRUE;
7774                                         switch (ro_type) {
7775                                         case MONO_TYPE_BOOLEAN:
7776                                         case MONO_TYPE_U1:
7777                                                 NEW_ICONST (cfg, *sp, *((guint8 *)addr));
7778                                                 sp++;
7779                                                 break;
7780                                         case MONO_TYPE_I1:
7781                                                 NEW_ICONST (cfg, *sp, *((gint8 *)addr));
7782                                                 sp++;
7783                                                 break;                                          
7784                                         case MONO_TYPE_CHAR:
7785                                         case MONO_TYPE_U2:
7786                                                 NEW_ICONST (cfg, *sp, *((guint16 *)addr));
7787                                                 sp++;
7788                                                 break;
7789                                         case MONO_TYPE_I2:
7790                                                 NEW_ICONST (cfg, *sp, *((gint16 *)addr));
7791                                                 sp++;
7792                                                 break;
7793                                                 break;
7794                                         case MONO_TYPE_I4:
7795                                                 NEW_ICONST (cfg, *sp, *((gint32 *)addr));
7796                                                 sp++;
7797                                                 break;                                          
7798                                         case MONO_TYPE_U4:
7799                                                 NEW_ICONST (cfg, *sp, *((guint32 *)addr));
7800                                                 sp++;
7801                                                 break;
7802 #ifndef HAVE_MOVING_COLLECTOR
7803                                         case MONO_TYPE_I:
7804                                         case MONO_TYPE_U:
7805                                         case MONO_TYPE_STRING:
7806                                         case MONO_TYPE_OBJECT:
7807                                         case MONO_TYPE_CLASS:
7808                                         case MONO_TYPE_SZARRAY:
7809                                         case MONO_TYPE_PTR:
7810                                         case MONO_TYPE_FNPTR:
7811                                         case MONO_TYPE_ARRAY:
7812                                                 NEW_PCONST (cfg, *sp, *((gpointer *)addr));
7813                                                 type_to_eval_stack_type (cfg, field->type, *sp);
7814                                                 sp++;
7815                                                 break;
7816 #endif
7817                                         case MONO_TYPE_I8:
7818                                         case MONO_TYPE_U8:
7819                                                 MONO_INST_NEW (cfg, *sp, OP_I8CONST);
7820                                                 sp [0]->type = STACK_I8;
7821                                                 sp [0]->inst_l = *((gint64 *)addr);
7822                                                 sp++;
7823                                                 break;
7824                                         case MONO_TYPE_R4:
7825                                         case MONO_TYPE_R8:
7826                                         case MONO_TYPE_VALUETYPE:
7827                                         default:
7828                                                 is_const = FALSE;
7829                                                 break;
7830                                         }
7831                                 }
7832
7833                                 if (!is_const) {
7834                                         MonoInst *load;
7835                                         CHECK_STACK_OVF (1);
7836                                         MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, field->type));
7837                                         type_to_eval_stack_type (cfg, field->type, load);
7838                                         load->inst_left = ins;
7839                                         load->flags |= ins_flag;
7840 #ifdef MONO_ARCH_SOFT_FLOAT
7841                                         if (load->opcode == CEE_LDIND_R4) {
7842                                                 int temp;
7843                                                 temp = handle_load_float (cfg, bblock, ins, ip);
7844                                                 NEW_TEMPLOAD (cfg, load, temp);
7845                                         }
7846 #endif
7847                                         *sp++ = load;
7848                                         ins_flag = 0;
7849                                 }
7850                         }
7851                         ip += 5;
7852                         break;
7853                 }
7854                 case CEE_STOBJ:
7855                         CHECK_STACK (2);
7856                         sp -= 2;
7857                         CHECK_OPSIZE (5);
7858                         token = read32 (ip + 1);
7859                         klass = mini_get_class (method, token, generic_context);
7860                         CHECK_TYPELOAD (klass);
7861                         n = mini_type_to_stind (cfg, &klass->byval_arg);
7862                         /* FIXME: handle CEE_STIND_R4 */
7863                         if (n == CEE_STOBJ) {
7864                                 handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE, TRUE);
7865                         } else {
7866                                 /* FIXME: should check item at sp [1] is compatible with the type of the store. */
7867                                 MonoInst *store;
7868                                 MONO_INST_NEW (cfg, store, n);
7869                                 store->inst_left = sp [0];
7870                                 store->inst_right = sp [1];
7871                                 store->flags |= ins_flag;
7872                                 MONO_ADD_INS (bblock, store);
7873                         }
7874                         ins_flag = 0;
7875                         ip += 5;
7876                         inline_costs += 1;
7877                         break;
7878                 case CEE_BOX: {
7879                         MonoInst *val;
7880
7881                         CHECK_STACK (1);
7882                         --sp;
7883                         val = *sp;
7884                         CHECK_OPSIZE (5);
7885                         token = read32 (ip + 1);
7886                         klass = mini_get_class (method, token, generic_context);
7887                         CHECK_TYPELOAD (klass);
7888
7889                         if (cfg->generic_sharing_context)
7890                                 context_used =  mono_class_check_context_used (klass);
7891
7892                         if (generic_class_is_reference_type (cfg, klass)) {
7893                                 *sp++ = val;
7894                                 ip += 5;
7895                                 break;
7896                         }
7897                         if (klass == mono_defaults.void_class)
7898                                 UNVERIFIED;
7899                         if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
7900                                 UNVERIFIED;
7901                         /* frequent check in generic code: box (struct), brtrue */
7902                         if (!mono_class_is_nullable (klass) &&
7903                             ip + 5 < end && ip_in_bb (cfg, bblock, ip + 5) && (ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S)) {
7904                                 /*g_print ("box-brtrue opt at 0x%04x in %s\n", real_offset, method->name);*/
7905                                 MONO_INST_NEW (cfg, ins, CEE_POP);
7906                                 MONO_ADD_INS (bblock, ins);
7907                                 ins->inst_i0 = *sp;
7908                                 ip += 5;
7909                                 cfg->ip = ip;
7910                                 MONO_INST_NEW (cfg, ins, OP_BR);
7911                                 MONO_ADD_INS (bblock, ins);
7912                                 if (*ip == CEE_BRTRUE_S) {
7913                                         CHECK_OPSIZE (2);
7914                                         ip++;
7915                                         target = ip + 1 + (signed char)(*ip);
7916                                         ip++;
7917                                 } else {
7918                                         CHECK_OPSIZE (5);
7919                                         ip++;
7920                                         target = ip + 4 + (gint)(read32 (ip));
7921                                         ip += 4;
7922                                 }
7923                                 GET_BBLOCK (cfg, tblock, target);
7924                                 link_bblock (cfg, bblock, tblock);
7925                                 CHECK_BBLOCK (target, ip, tblock);
7926                                 ins->inst_target_bb = tblock;
7927                                 GET_BBLOCK (cfg, tblock, ip);
7928                                 link_bblock (cfg, bblock, tblock);
7929                                 if (sp != stack_start) {
7930                                         handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
7931                                         sp = stack_start;
7932                                         CHECK_UNVERIFIABLE (cfg);
7933                                 }
7934                                 start_new_bblock = 1;
7935                                 break;
7936                         }
7937                         if (context_used) {
7938                                 MonoInst *rgctx;
7939
7940                                 if (mono_class_is_nullable (klass)) {
7941                                         GET_RGCTX (rgctx, context_used);
7942                                         *sp++ = handle_box_nullable_from_inst (cfg, method, context_used, bblock, val,
7943                                                         ip, klass, generic_context, rgctx);
7944                                 } else {
7945                                         MonoInst *data;
7946                                         int rgctx_info;
7947
7948                                         GET_RGCTX (rgctx, context_used);
7949                                         if (cfg->opt & MONO_OPT_SHARED)
7950                                                 rgctx_info = MONO_RGCTX_INFO_KLASS;
7951                                         else
7952                                                 rgctx_info = MONO_RGCTX_INFO_VTABLE;
7953                                         data = get_runtime_generic_context_ptr (cfg, method, context_used, bblock, klass,
7954                                                         generic_context, rgctx, rgctx_info, ip);
7955
7956                                         *sp++ = handle_box_from_inst (cfg, bblock, val, ip, klass, data);
7957                                 }
7958                         } else {
7959                                 *sp++ = handle_box (cfg, bblock, val, ip, klass);
7960                         }
7961                         ip += 5;
7962                         inline_costs += 1;
7963                         break;
7964                 }
7965                 case CEE_NEWARR:
7966                         CHECK_STACK (1);
7967                         --sp;
7968
7969                         CHECK_OPSIZE (5);
7970                         token = read32 (ip + 1);
7971
7972                         /* allocate the domainvar - becaus this is used in decompose_foreach */
7973                         if (cfg->opt & MONO_OPT_SHARED) {
7974                                 mono_get_domainvar (cfg);
7975                                 /* LAME-IR: Mark it as used since otherwise it will be optimized away */
7976                                 cfg->domainvar->flags |= MONO_INST_VOLATILE;
7977                         }
7978
7979                         /* Ditto */
7980                         mono_get_got_var (cfg);
7981
7982                         klass = mini_get_class (method, token, generic_context);
7983                         CHECK_TYPELOAD (klass);
7984
7985                         if (cfg->generic_sharing_context)
7986                                 context_used = mono_class_check_context_used (klass);
7987
7988                         if (context_used) {
7989                                 MonoInst *rgctx, *args [3];
7990                                 int temp;
7991
7992                                 /* domain */
7993                                 /* FIXME: what about domain-neutral code? */
7994                                 NEW_DOMAINCONST (cfg, args [0]);
7995
7996                                 /* klass */
7997                                 GET_RGCTX (rgctx, context_used);
7998                                 args [1] = get_runtime_generic_context_ptr (cfg, method, context_used, bblock, klass,
7999                                         generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
8000
8001                                 /* array len */
8002                                 args [2] = *sp;
8003
8004                                 temp = mono_emit_jit_icall (cfg, bblock, mono_array_new, args, ip);
8005                                 NEW_TEMPLOAD (cfg, ins, temp);
8006                         } else {
8007                                 MONO_INST_NEW (cfg, ins, *ip);
8008                                 ins->inst_newa_class = klass;
8009                                 ins->inst_newa_len = *sp;
8010                                 ins->type = STACK_OBJ;
8011                                 ins->klass = mono_array_class_get (klass, 1);
8012                         }
8013
8014                         ip += 5;
8015                         *sp++ = ins;
8016                         /* 
8017                          * we store the object so calls to create the array are not interleaved
8018                          * with the arguments of other calls.
8019                          */
8020                         if (1) {
8021                                 MonoInst *store, *temp, *load;
8022                                 const char *data_ptr;
8023                                 int data_size = 0;
8024                                 --sp;
8025                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
8026                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
8027                                 store->cil_code = ins->cil_code;
8028                                 MONO_ADD_INS (bblock, store);
8029                                 /* 
8030                                  * we inline/optimize the initialization sequence if possible.
8031                                  * we should also allocate the array as not cleared, since we spend as much time clearing to 0 as initializing
8032                                  * for small sizes open code the memcpy
8033                                  * ensure the rva field is big enough
8034                                  */
8035                                 if ((cfg->opt & MONO_OPT_INTRINS) && ip + 6 < end && ip_in_bb (cfg, bblock, ip + 6) && (data_ptr = initialize_array_data (method, cfg->compile_aot, ip, ins, &data_size))) {
8036                                         MonoMethod *memcpy_method = get_memcpy_method ();
8037                                         MonoInst *data_offset, *add;
8038                                         MonoInst *iargs [3];
8039                                         NEW_ICONST (cfg, iargs [2], data_size);
8040                                         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
8041                                         load->cil_code = ins->cil_code;
8042                                         NEW_ICONST (cfg, data_offset, G_STRUCT_OFFSET (MonoArray, vector));
8043                                         MONO_INST_NEW (cfg, add, OP_PADD);
8044                                         add->inst_left = load;
8045                                         add->inst_right = data_offset;
8046                                         iargs [0] = add;
8047                                         if (cfg->compile_aot) {
8048                                                 NEW_AOTCONST_TOKEN (cfg, iargs [1], MONO_PATCH_INFO_RVA, method->klass->image, GPOINTER_TO_UINT(data_ptr), STACK_PTR, NULL);
8049                                         } else {
8050                                                 NEW_PCONST (cfg, iargs [1], (char*)data_ptr);
8051                                         }
8052                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
8053                                         ip += 11;
8054                                 }
8055                                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
8056                                 load->cil_code = ins->cil_code;
8057                                 *sp++ = load;
8058                         }
8059                         inline_costs += 1;
8060                         break;
8061                 case CEE_LDLEN:
8062                         CHECK_STACK (1);
8063                         --sp;
8064                         if (sp [0]->type != STACK_OBJ)
8065                                 UNVERIFIED;
8066                         MONO_INST_NEW (cfg, ins, *ip);
8067                         ip++;
8068                         ins->inst_left = *sp;
8069                         ins->type = STACK_PTR;
8070                         *sp++ = ins;
8071                         break;
8072                 case CEE_LDELEMA:
8073                         CHECK_STACK (2);
8074                         sp -= 2;
8075                         CHECK_OPSIZE (5);
8076                         if (sp [0]->type != STACK_OBJ)
8077                                 UNVERIFIED;
8078
8079                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
8080                         CHECK_TYPELOAD (klass);
8081                         /* we need to make sure that this array is exactly the type it needs
8082                          * to be for correctness. the wrappers are lax with their usage
8083                          * so we need to ignore them here
8084                          */
8085                         if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE && !readonly) {
8086                                 MonoInst* check;
8087
8088                                 /* Needed by the code generated in inssel.brg */
8089                                 mono_get_got_var (cfg);
8090
8091                                 MONO_INST_NEW (cfg, check, OP_CHECK_ARRAY_TYPE);
8092                                 check->klass = mono_array_class_get (klass, 1);
8093                                 check->inst_left = sp [0];
8094                                 check->type = STACK_OBJ;
8095                                 sp [0] = check;
8096                         }
8097                         
8098                         readonly = FALSE;
8099                         mono_class_init (klass);
8100                         NEW_LDELEMA (cfg, ins, sp, klass);
8101                         *sp++ = ins;
8102                         ip += 5;
8103                         break;
8104                 case CEE_LDELEM_ANY: {
8105                         MonoInst *load;
8106                         CHECK_STACK (2);
8107                         sp -= 2;
8108                         if (sp [0]->type != STACK_OBJ)
8109                                 UNVERIFIED;
8110                         CHECK_OPSIZE (5);
8111                         token = read32 (ip + 1);
8112                         klass = mini_get_class (method, token, generic_context);
8113                         CHECK_TYPELOAD (klass);
8114                         mono_class_init (klass);
8115                         NEW_LDELEMA (cfg, load, sp, klass);
8116                         MONO_INST_NEW (cfg, ins, mini_type_to_ldind (cfg, &klass->byval_arg));
8117                         ins->inst_left = load;
8118                         *sp++ = ins;
8119                         type_to_eval_stack_type (cfg, &klass->byval_arg, ins);
8120                         ip += 5;
8121                         break;
8122                 }
8123                 case CEE_LDELEM_I1:
8124                 case CEE_LDELEM_U1:
8125                 case CEE_LDELEM_I2:
8126                 case CEE_LDELEM_U2:
8127                 case CEE_LDELEM_I4:
8128                 case CEE_LDELEM_U4:
8129                 case CEE_LDELEM_I8:
8130                 case CEE_LDELEM_I:
8131                 case CEE_LDELEM_R4:
8132                 case CEE_LDELEM_R8:
8133                 case CEE_LDELEM_REF: {
8134                         MonoInst *load;
8135                         /*
8136                          * translate to:
8137                          * ldind.x (ldelema (array, index))
8138                          * ldelema does the bounds check
8139                          */
8140                         CHECK_STACK (2);
8141                         sp -= 2;
8142                         if (sp [0]->type != STACK_OBJ)
8143                                 UNVERIFIED;
8144                         klass = array_access_to_klass (*ip, sp [0]);
8145                         NEW_LDELEMA (cfg, load, sp, klass);
8146 #ifdef MONO_ARCH_SOFT_FLOAT
8147                         if (*ip == CEE_LDELEM_R4) {
8148                                 int temp;
8149                                 temp = handle_load_float (cfg, bblock, load, ip);
8150                                 NEW_TEMPLOAD (cfg, *sp, temp);
8151                                 sp++;
8152                                 ++ip;
8153                                 break;
8154                         }
8155 #endif
8156                         MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
8157                         ins->inst_left = load;
8158                         *sp++ = ins;
8159                         ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
8160                         ins->klass = klass;
8161                         ++ip;
8162                         break;
8163                 }
8164                 case CEE_STELEM_I:
8165                 case CEE_STELEM_I1:
8166                 case CEE_STELEM_I2:
8167                 case CEE_STELEM_I4:
8168                 case CEE_STELEM_I8:
8169                 case CEE_STELEM_R4:
8170                 case CEE_STELEM_R8: {
8171                         MonoInst *load;
8172                         /*
8173                          * translate to:
8174                          * stind.x (ldelema (array, index), val)
8175                          * ldelema does the bounds check
8176                          */
8177                         CHECK_STACK (3);
8178                         sp -= 3;
8179                         if (sp [0]->type != STACK_OBJ)
8180                                 UNVERIFIED;
8181                         klass = array_access_to_klass (*ip, sp [0]);
8182                         NEW_LDELEMA (cfg, load, sp, klass);
8183 #ifdef MONO_ARCH_SOFT_FLOAT
8184                         if (*ip == CEE_STELEM_R4) {
8185                                 handle_store_float (cfg, bblock, load, sp [2], ip);
8186                                 ip++;
8187                                 break;
8188                         }
8189 #endif
8190                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
8191                         ins->inst_left = load;
8192                         ins->inst_right = sp [2];
8193                         ++ip;
8194                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8195                         MONO_ADD_INS (bblock, ins);
8196                         inline_costs += 1;
8197                         break;
8198                 }
8199                 case CEE_STELEM_ANY: {
8200                         MonoInst *load;
8201                         /*
8202                          * translate to:
8203                          * stind.x (ldelema (array, index), val)
8204                          * ldelema does the bounds check
8205                          */
8206                         CHECK_STACK (3);
8207                         sp -= 3;
8208                         if (sp [0]->type != STACK_OBJ)
8209                                 UNVERIFIED;
8210                         CHECK_OPSIZE (5);
8211                         token = read32 (ip + 1);
8212                         klass = mini_get_class (method, token, generic_context);
8213                         CHECK_TYPELOAD (klass);
8214                         mono_class_init (klass);
8215                         if (generic_class_is_reference_type (cfg, klass)) {
8216                                 /* storing a NULL doesn't need any of the complex checks in stelemref */
8217                                 if (sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL) {
8218                                         MonoInst *load;
8219                                         NEW_LDELEMA (cfg, load, sp, mono_defaults.object_class);
8220                                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
8221                                         ins->inst_left = load;
8222                                         ins->inst_right = sp [2];
8223                                         MONO_ADD_INS (bblock, ins);
8224                                 } else {
8225                                         MonoMethod* helper = mono_marshal_get_stelemref ();
8226                                         MonoInst *iargs [3];
8227                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8228
8229                                         iargs [2] = sp [2];
8230                                         iargs [1] = sp [1];
8231                                         iargs [0] = sp [0];
8232
8233                                         mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
8234                                 }
8235                         } else {
8236                                 NEW_LDELEMA (cfg, load, sp, klass);
8237
8238                                 n = mini_type_to_stind (cfg, &klass->byval_arg);
8239                                 /* FIXME: CEE_STIND_R4 */
8240                                 if (n == CEE_STOBJ)
8241                                         handle_stobj (cfg, bblock, load, sp [2], ip, klass, FALSE, FALSE, TRUE);
8242                                 else {
8243                                         MONO_INST_NEW (cfg, ins, n);
8244                                         ins->inst_left = load;
8245                                         ins->inst_right = sp [2];
8246                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8247                                         MONO_ADD_INS (bblock, ins);
8248                                 }
8249                         }
8250                         ip += 5;
8251                         inline_costs += 1;
8252                         break;
8253                 }
8254                 case CEE_STELEM_REF: {
8255                         MonoInst *iargs [3];
8256                         MonoMethod* helper = mono_marshal_get_stelemref ();
8257
8258                         CHECK_STACK (3);
8259                         sp -= 3;
8260                         if (sp [0]->type != STACK_OBJ)
8261                                 UNVERIFIED;
8262                         if (sp [2]->type != STACK_OBJ)
8263                                 UNVERIFIED;
8264
8265                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8266
8267                         /* storing a NULL doesn't need any of the complex checks in stelemref */
8268                         if (sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL) {
8269                                 MonoInst *load;
8270                                 NEW_LDELEMA (cfg, load, sp, mono_defaults.object_class);
8271                                 MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
8272                                 ins->inst_left = load;
8273                                 ins->inst_right = sp [2];
8274                                 MONO_ADD_INS (bblock, ins);
8275                         } else {
8276                                 iargs [2] = sp [2];
8277                                 iargs [1] = sp [1];
8278                                 iargs [0] = sp [0];
8279                         
8280                                 mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
8281                                 inline_costs += 1;
8282                         }
8283
8284                         ++ip;
8285                         break;
8286                 }
8287                 case CEE_CKFINITE: {
8288                         MonoInst *store, *temp;
8289                         CHECK_STACK (1);
8290
8291                         /* this instr. can throw exceptions as side effect,
8292                          * so we cant eliminate dead code which contains CKFINITE opdodes.
8293                          * Spilling to memory makes sure that we always perform
8294                          * this check */
8295
8296                         
8297                         MONO_INST_NEW (cfg, ins, OP_CKFINITE);
8298                         ins->inst_left = sp [-1];
8299                         temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
8300
8301                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
8302                         MONO_ADD_INS (bblock, store);
8303
8304                         NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
8305                        
8306                         ++ip;
8307                         break;
8308                 }
8309                 case CEE_REFANYVAL:
8310                         CHECK_STACK (1);
8311                         --sp;
8312                         CHECK_OPSIZE (5);
8313                         token = read32 (ip + 1);
8314                         klass = mono_class_get_full (image, token, generic_context);
8315                         CHECK_TYPELOAD (klass);
8316                         mono_class_init (klass);
8317
8318                         if (cfg->generic_sharing_context) {
8319                                 context_used = mono_class_check_context_used (klass);
8320                                 if (context_used && cfg->compile_aot)
8321                                         GENERIC_SHARING_FAILURE (*ip);
8322                         }
8323
8324                         if (context_used) {
8325                                 MonoInst *rgctx;
8326
8327                                 MONO_INST_NEW (cfg, ins, OP_REFANYVAL_REG);
8328                                 ins->type = STACK_MP;
8329                                 ins->inst_left = *sp;
8330                                 ins->klass = klass;
8331
8332                                 GET_RGCTX (rgctx, context_used);
8333                                 ins->inst_right = get_runtime_generic_context_ptr (cfg, method, context_used,
8334                                                 bblock, klass, generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
8335                         } else {
8336                                 MONO_INST_NEW (cfg, ins, *ip);
8337                                 ins->type = STACK_MP;
8338                                 ins->inst_left = *sp;
8339                                 ins->klass = klass;
8340                                 ins->inst_newa_class = klass;
8341                         }
8342                         ip += 5;
8343                         *sp++ = ins;
8344                         break;
8345                 case CEE_MKREFANY: {
8346                         MonoInst *loc;
8347
8348                         CHECK_STACK (1);
8349                         --sp;
8350                         CHECK_OPSIZE (5);
8351                         token = read32 (ip + 1);
8352                         klass = mono_class_get_full (image, token, generic_context);
8353                         CHECK_TYPELOAD (klass);
8354                         mono_class_init (klass);
8355
8356                         if (cfg->generic_sharing_context) {
8357                                 context_used = mono_class_check_context_used (klass);
8358                                 if (context_used && cfg->compile_aot)
8359                                         GENERIC_SHARING_FAILURE (CEE_MKREFANY);
8360                         }
8361
8362                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
8363                         if (context_used) {
8364                                 MonoInst *rgctx, *klass_type, *klass_klass, *loc_load;
8365
8366                                 GET_RGCTX (rgctx, context_used);
8367                                 klass_klass = get_runtime_generic_context_ptr (cfg, method, context_used, bblock, klass,
8368                                                 generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
8369                                 GET_RGCTX (rgctx, context_used);
8370                                 klass_type = get_runtime_generic_context_ptr (cfg, method, context_used, bblock, klass,
8371                                                 generic_context, rgctx, MONO_RGCTX_INFO_TYPE, ip);
8372
8373                                 NEW_TEMPLOADA (cfg, loc_load, loc->inst_c0);
8374
8375                                 MONO_INST_NEW (cfg, ins, OP_MKREFANY_REGS);
8376                                 NEW_GROUP (cfg, ins->inst_left, klass_type, klass_klass);
8377                                 NEW_GROUP (cfg, ins->inst_right, *sp, loc_load);
8378                         } else {
8379                                 MonoInst *klassconst;
8380
8381                                 NEW_PCONST (cfg, klassconst, klass);
8382
8383                                 MONO_INST_NEW (cfg, ins, *ip);
8384                                 NEW_TEMPLOADA (cfg, ins->inst_right, loc->inst_c0);
8385                                 NEW_GROUP (cfg, ins->inst_left, *sp, klassconst);
8386                         }
8387
8388                         MONO_ADD_INS (bblock, ins);
8389
8390                         NEW_TEMPLOAD (cfg, *sp, loc->inst_c0);
8391                         ++sp;
8392                         ip += 5;
8393                         break;
8394                 }
8395                 case CEE_LDTOKEN: {
8396                         gpointer handle;
8397                         MonoClass *handle_class;
8398
8399                         CHECK_STACK_OVF (1);
8400
8401                         CHECK_OPSIZE (5);
8402                         n = read32 (ip + 1);
8403
8404                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8405                                 handle = mono_method_get_wrapper_data (method, n);
8406                                 handle_class = mono_method_get_wrapper_data (method, n + 1);
8407                                 if (handle_class == mono_defaults.typehandle_class)
8408                                         handle = &((MonoClass*)handle)->byval_arg;
8409                         }
8410                         else {
8411                                 handle = mono_ldtoken (image, n, &handle_class, generic_context);
8412                         }
8413                         if (!handle)
8414                                 goto load_error;
8415                         mono_class_init (handle_class);
8416
8417                         if (cfg->generic_sharing_context) {
8418                                 if (handle_class == mono_defaults.typehandle_class) {
8419                                         /* If we get a MONO_TYPE_CLASS
8420                                            then we need to provide the
8421                                            open type, not an
8422                                            instantiation of it. */
8423                                         if (mono_type_get_type (handle) == MONO_TYPE_CLASS)
8424                                                 context_used = 0;
8425                                         else
8426                                                 context_used = mono_class_check_context_used (mono_class_from_mono_type (handle));
8427                                 } else if (handle_class == mono_defaults.fieldhandle_class)
8428                                         context_used = mono_class_check_context_used (((MonoClassField*)handle)->parent);
8429                                 else if (handle_class == mono_defaults.methodhandle_class)
8430                                         context_used = mono_method_check_context_used (handle);
8431                                 else
8432                                         g_assert_not_reached ();
8433                         }
8434
8435                         if (cfg->opt & MONO_OPT_SHARED) {
8436                                 int temp;
8437                                 MonoInst *res, *store, *addr, *vtvar, *iargs [3];
8438                                 int method_context_used;
8439
8440                                 if (cfg->generic_sharing_context)
8441                                         method_context_used = mono_method_check_context_used (method);
8442                                 else
8443                                         method_context_used = 0;
8444
8445                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
8446
8447                                 NEW_IMAGECONST (cfg, iargs [0], image);
8448                                 NEW_ICONST (cfg, iargs [1], n);
8449                                 if (method_context_used) {
8450                                         MonoInst *rgctx;
8451
8452                                         GET_RGCTX (rgctx, method_context_used);
8453                                         iargs [2] = get_runtime_generic_context_method (cfg, method, method_context_used,
8454                                                         bblock, method,
8455                                                         generic_context, rgctx, MONO_RGCTX_INFO_METHOD, ip);
8456                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper_generic_shared,
8457                                                         iargs, ip);
8458                                 } else {
8459                                         NEW_PCONST (cfg, iargs [2], generic_context);
8460                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
8461                                 }
8462                                 NEW_TEMPLOAD (cfg, res, temp);
8463                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
8464                                 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
8465                                 MONO_ADD_INS (bblock, store);
8466                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
8467                         } else {
8468                                 if ((ip + 10 < end) && ip_in_bb (cfg, bblock, ip + 5) &&
8469                                         handle_class == mono_defaults.typehandle_class &&
8470                                         ((ip [5] == CEE_CALL) || (ip [5] == CEE_CALLVIRT)) && 
8471                                         (cmethod = mini_get_method (cfg, method, read32 (ip + 6), NULL, generic_context)) &&
8472                                         (cmethod->klass == mono_defaults.monotype_class->parent) &&
8473                                         (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
8474                                         MonoClass *tclass = mono_class_from_mono_type (handle);
8475                                         mono_class_init (tclass);
8476                                         if (context_used) {
8477                                                 MonoInst *rgctx;
8478
8479                                                 g_assert (!cfg->compile_aot);
8480
8481                                                 GET_RGCTX (rgctx, context_used);
8482                                                 ins = get_runtime_generic_context_ptr (cfg, method, context_used, bblock, tclass,
8483                                                         generic_context, rgctx, MONO_RGCTX_INFO_REFLECTION_TYPE, ip);
8484                                         } else if (cfg->compile_aot) {
8485                                                 NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n);
8486                                         } else {
8487                                                 NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
8488                                         }
8489                                         ins->type = STACK_OBJ;
8490                                         ins->klass = cmethod->klass;
8491                                         ip += 5;
8492                                 } else {
8493                                         MonoInst *store, *addr, *vtvar;
8494
8495                                         if (context_used) {
8496                                                         MonoInst *rgctx;
8497
8498                                                 g_assert (!cfg->compile_aot);
8499
8500                                                 GET_RGCTX (rgctx, context_used);
8501                                                 if (handle_class == mono_defaults.typehandle_class) {
8502                                                         ins = get_runtime_generic_context_ptr (cfg, method,
8503                                                                         context_used, bblock,
8504                                                                         mono_class_from_mono_type (handle), generic_context,
8505                                                                         rgctx, MONO_RGCTX_INFO_TYPE, ip);
8506                                                 } else if (handle_class == mono_defaults.methodhandle_class) {
8507                                                         ins = get_runtime_generic_context_method (cfg, method,
8508                                                                         context_used, bblock, handle, generic_context,
8509                                                                         rgctx, MONO_RGCTX_INFO_METHOD, ip);
8510                                                 } else if (handle_class == mono_defaults.fieldhandle_class) {
8511                                                         ins = get_runtime_generic_context_field (cfg, method,
8512                                                                         context_used, bblock, handle, generic_context,
8513                                                                         rgctx, MONO_RGCTX_INFO_CLASS_FIELD, ip);
8514                                                 } else {
8515                                                         g_assert_not_reached ();
8516                                                 }
8517                                         }
8518                                         else if (cfg->compile_aot) {
8519                                                 NEW_LDTOKENCONST (cfg, ins, image, n);
8520                                         } else {
8521                                                 NEW_PCONST (cfg, ins, handle);
8522                                         }
8523                                         vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
8524                                         NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
8525                                         NEW_INDSTORE (cfg, store, addr, ins, &mono_defaults.int_class->byval_arg);
8526                                         MONO_ADD_INS (bblock, store);
8527                                         NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
8528                                 }
8529                         }
8530
8531                         *sp++ = ins;
8532                         ip += 5;
8533                         break;
8534                 }
8535                 case CEE_CONV_U2:
8536                 case CEE_CONV_U1:
8537                 case CEE_CONV_I:
8538                         CHECK_STACK (1);
8539                         ADD_UNOP (*ip);
8540                         ip++;
8541                         break;
8542                 case CEE_ADD_OVF:
8543                 case CEE_ADD_OVF_UN:
8544                 case CEE_MUL_OVF:
8545                 case CEE_MUL_OVF_UN:
8546                 case CEE_SUB_OVF:
8547                 case CEE_SUB_OVF_UN:
8548                         CHECK_STACK (2);
8549                         ADD_BINOP (*ip);
8550                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
8551                                 --sp;
8552                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
8553                         }
8554                         ip++;
8555                         break;
8556                 case CEE_ENDFINALLY:
8557                         MONO_INST_NEW (cfg, ins, OP_ENDFINALLY);
8558                         MONO_ADD_INS (bblock, ins);
8559                         ip++;
8560                         start_new_bblock = 1;
8561
8562                         /*
8563                          * Control will leave the method so empty the stack, otherwise
8564                          * the next basic block will start with a nonempty stack.
8565                          */
8566                         while (sp != stack_start) {
8567                                 MONO_INST_NEW (cfg, ins, CEE_POP);
8568                                 sp--;
8569                                 ins->inst_i0 = *sp;
8570                                 MONO_ADD_INS (bblock, ins);
8571                         }
8572                         break;
8573                 case CEE_LEAVE:
8574                 case CEE_LEAVE_S: {
8575                         GList *handlers;
8576
8577                         if (*ip == CEE_LEAVE) {
8578                                 CHECK_OPSIZE (5);
8579                                 target = ip + 5 + (gint32)read32(ip + 1);
8580                         } else {
8581                                 CHECK_OPSIZE (2);
8582                                 target = ip + 2 + (signed char)(ip [1]);
8583                         }
8584
8585                         /* empty the stack */
8586                         while (sp != stack_start) {
8587                                 MONO_INST_NEW (cfg, ins, CEE_POP);
8588                                 sp--;
8589                                 ins->inst_i0 = *sp;
8590                                 MONO_ADD_INS (bblock, ins);
8591                         }
8592
8593                         /* 
8594                          * If this leave statement is in a catch block, check for a
8595                          * pending exception, and rethrow it if necessary.
8596                          */
8597                         for (i = 0; i < header->num_clauses; ++i) {
8598                                 MonoExceptionClause *clause = &header->clauses [i];
8599
8600                                 /* 
8601                                  * Use <= in the final comparison to handle clauses with multiple
8602                                  * leave statements, like in bug #78024.
8603                                  * The ordering of the exception clauses guarantees that we find the
8604                                  * innermost clause.
8605                                  */
8606                                 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)) {
8607                                         int temp;
8608                                         MonoInst *load;
8609
8610                                         NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
8611
8612                                         temp = mono_emit_jit_icall (cfg, bblock, mono_thread_get_undeniable_exception, NULL, ip);
8613                                         NEW_TEMPLOAD (cfg, *sp, temp);
8614                                 
8615                                         MONO_INST_NEW (cfg, ins, OP_THROW_OR_NULL);
8616                                         ins->inst_left = *sp;
8617                                         ins->inst_right = load;
8618                                         MONO_ADD_INS (bblock, ins);
8619                                 }
8620                         }
8621
8622                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
8623                                 GList *tmp;
8624                                 for (tmp = handlers; tmp; tmp = tmp->next) {
8625                                         tblock = tmp->data;
8626                                         link_bblock (cfg, bblock, tblock);
8627                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
8628                                         ins->inst_target_bb = tblock;
8629                                         MONO_ADD_INS (bblock, ins);
8630                                 }
8631                                 g_list_free (handlers);
8632                         } 
8633
8634                         MONO_INST_NEW (cfg, ins, OP_BR);
8635                         MONO_ADD_INS (bblock, ins);
8636                         GET_BBLOCK (cfg, tblock, target);
8637                         link_bblock (cfg, bblock, tblock);
8638                         CHECK_BBLOCK (target, ip, tblock);
8639                         ins->inst_target_bb = tblock;
8640                         start_new_bblock = 1;
8641
8642                         if (*ip == CEE_LEAVE)
8643                                 ip += 5;
8644                         else
8645                                 ip += 2;
8646
8647                         break;
8648                 }
8649                 case CEE_STIND_I:
8650                         CHECK_STACK (2);
8651                         MONO_INST_NEW (cfg, ins, *ip);
8652                         sp -= 2;
8653                         handle_loaded_temps (cfg, bblock, stack_start, sp);
8654                         MONO_ADD_INS (bblock, ins);
8655                         ip++;
8656                         ins->inst_i0 = sp [0];
8657                         ins->inst_i1 = sp [1];
8658                         inline_costs += 1;
8659                         break;
8660                 case CEE_CONV_U:
8661                         CHECK_STACK (1);
8662                         ADD_UNOP (*ip);
8663                         ip++;
8664                         break;
8665                 /* trampoline mono specific opcodes */
8666                 case MONO_CUSTOM_PREFIX: {
8667
8668                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
8669
8670                         CHECK_OPSIZE (2);
8671                         switch (ip [1]) {
8672
8673                         case CEE_MONO_ICALL: {
8674                                 int temp;
8675                                 gpointer func;
8676                                 MonoJitICallInfo *info;
8677
8678                                 token = read32 (ip + 2);
8679                                 func = mono_method_get_wrapper_data (method, token);
8680                                 info = mono_find_jit_icall_by_addr (func);
8681                                 if (info == NULL){
8682                                         g_error ("An attempt has been made to perform an icall to address %p, "
8683                                                  "but the address has not been registered as an icall\n", info);
8684                                         g_assert_not_reached ();
8685                                 }
8686
8687                                 CHECK_STACK (info->sig->param_count);
8688                                 sp -= info->sig->param_count;
8689
8690                                 temp = mono_emit_jit_icall (cfg, bblock, info->func, sp, ip);
8691                                 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
8692                                         NEW_TEMPLOAD (cfg, *sp, temp);
8693                                         sp++;
8694                                 }
8695
8696                                 ip += 6;
8697                                 inline_costs += 10 * num_calls++;
8698
8699                                 break;
8700                         }
8701                         case CEE_MONO_LDPTR: {
8702                                 gpointer ptr;
8703
8704                                 CHECK_STACK_OVF (1);
8705                                 CHECK_OPSIZE (6);
8706                                 token = read32 (ip + 2);
8707
8708                                 ptr = mono_method_get_wrapper_data (method, token);
8709                                 if (cfg->compile_aot && (cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE || cfg->method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE)) {
8710                                         MonoMethod *wrapped = mono_marshal_method_from_wrapper (cfg->method);
8711
8712                                         if (wrapped && ptr != NULL && mono_lookup_internal_call (wrapped) == ptr) {
8713                                                 NEW_AOTCONST (cfg, ins, MONO_PATCH_INFO_ICALL_ADDR, wrapped);
8714                                                 *sp++ = ins;
8715                                                 ip += 6;
8716                                                 break;
8717                                         }
8718
8719                                         if ((method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (strstr (method->name, "__icall_wrapper_") == method->name)) {
8720                                                 MonoJitICallInfo *callinfo;
8721                                                 const char *icall_name;
8722
8723                                                 icall_name = method->name + strlen ("__icall_wrapper_");
8724                                                 g_assert (icall_name);
8725                                                 callinfo = mono_find_jit_icall_by_name (icall_name);
8726                                                 g_assert (callinfo);
8727
8728                                                 if (ptr == callinfo->func) {
8729                                                         /* Will be transformed into an AOTCONST later */
8730                                                         NEW_PCONST (cfg, ins, ptr);
8731                                                         *sp++ = ins;
8732                                                         ip += 6;
8733                                                         break;
8734                                                 }
8735                                         }
8736                                 }
8737                                 /* FIXME: Generalize this */
8738                                 if (cfg->compile_aot && ptr == mono_thread_interruption_request_flag ()) {
8739                                         NEW_AOTCONST (cfg, ins, MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG, NULL);
8740                                         *sp++ = ins;
8741                                         ip += 6;
8742                                         break;
8743                                 }
8744                                 NEW_PCONST (cfg, ins, ptr);
8745                                 *sp++ = ins;
8746                                 ip += 6;
8747                                 inline_costs += 10 * num_calls++;
8748                                 /* Can't embed random pointers into AOT code */
8749                                 cfg->disable_aot = 1;
8750                                 break;
8751                         }
8752                         case CEE_MONO_VTADDR:
8753                                 CHECK_STACK (1);
8754                                 --sp;
8755                                 MONO_INST_NEW (cfg, ins, OP_VTADDR);
8756                                 ins->type = STACK_MP;
8757                                 ins->inst_left = *sp;
8758                                 *sp++ = ins;
8759                                 ip += 2;
8760                                 break;
8761                         case CEE_MONO_NEWOBJ: {
8762                                 MonoInst *iargs [2];
8763                                 int temp;
8764                                 CHECK_STACK_OVF (1);
8765                                 CHECK_OPSIZE (6);
8766                                 token = read32 (ip + 2);
8767                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
8768                                 mono_class_init (klass);
8769                                 NEW_DOMAINCONST (cfg, iargs [0]);
8770                                 NEW_CLASSCONST (cfg, iargs [1], klass);
8771                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
8772                                 NEW_TEMPLOAD (cfg, *sp, temp);
8773                                 sp++;
8774                                 ip += 6;
8775                                 inline_costs += 10 * num_calls++;
8776                                 break;
8777                         }
8778                         case CEE_MONO_OBJADDR:
8779                                 CHECK_STACK (1);
8780                                 --sp;
8781                                 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
8782                                 ins->type = STACK_MP;
8783                                 ins->inst_left = *sp;
8784                                 *sp++ = ins;
8785                                 ip += 2;
8786                                 break;
8787                         case CEE_MONO_LDNATIVEOBJ:
8788                                 CHECK_STACK (1);
8789                                 CHECK_OPSIZE (6);
8790                                 token = read32 (ip + 2);
8791                                 klass = mono_method_get_wrapper_data (method, token);
8792                                 g_assert (klass->valuetype);
8793                                 mono_class_init (klass);
8794                                 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
8795                                 sp [-1] = ins;
8796                                 ip += 6;
8797                                 break;
8798                         case CEE_MONO_RETOBJ:
8799                                 g_assert (cfg->ret);
8800                                 g_assert (mono_method_signature (method)->pinvoke); 
8801                                 CHECK_STACK (1);
8802                                 --sp;
8803                                 
8804                                 CHECK_OPSIZE (6);
8805                                 token = read32 (ip + 2);    
8806                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
8807
8808                                 NEW_RETLOADA (cfg, ins);
8809                                 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE, FALSE);
8810                                 
8811                                 if (sp != stack_start)
8812                                         UNVERIFIED;
8813                                 
8814                                 MONO_INST_NEW (cfg, ins, OP_BR);
8815                                 ins->inst_target_bb = end_bblock;
8816                                 MONO_ADD_INS (bblock, ins);
8817                                 link_bblock (cfg, bblock, end_bblock);
8818                                 start_new_bblock = 1;
8819                                 ip += 6;
8820                                 break;
8821                         case CEE_MONO_CISINST:
8822                         case CEE_MONO_CCASTCLASS: {
8823                                 int token;
8824                                 CHECK_STACK (1);
8825                                 --sp;
8826                                 CHECK_OPSIZE (6);
8827                                 token = read32 (ip + 2);
8828                                 /* Needed by the code generated in inssel.brg */
8829                                 mono_get_got_var (cfg);
8830                 
8831                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
8832                                 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_CISINST) ? OP_CISINST : OP_CCASTCLASS);
8833                                 ins->type = STACK_I4;
8834                                 ins->inst_left = *sp;
8835                                 ins->inst_newa_class = klass;
8836                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 6);
8837                                 ip += 6;
8838                                 break;
8839                         }
8840                         case CEE_MONO_SAVE_LMF:
8841                         case CEE_MONO_RESTORE_LMF:
8842 #ifdef MONO_ARCH_HAVE_LMF_OPS
8843                                 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_SAVE_LMF) ? OP_SAVE_LMF : OP_RESTORE_LMF);
8844                                 MONO_ADD_INS (bblock, ins);
8845                                 cfg->need_lmf_area = TRUE;
8846 #endif
8847                                 ip += 2;
8848                                 break;
8849                         case CEE_MONO_CLASSCONST:
8850                                 CHECK_STACK_OVF (1);
8851                                 CHECK_OPSIZE (6);
8852                                 token = read32 (ip + 2);
8853                                 NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
8854                                 *sp++ = ins;
8855                                 ip += 6;
8856                                 inline_costs += 10 * num_calls++;
8857                                 break;
8858                         case CEE_MONO_NOT_TAKEN:
8859                                 bblock->out_of_line = TRUE;
8860                                 ip += 2;
8861                                 break;
8862                         case CEE_MONO_TLS:
8863                                 CHECK_STACK_OVF (1);
8864                                 CHECK_OPSIZE (6);
8865                                 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
8866                                 ins->inst_offset = (gint32)read32 (ip + 2);
8867                                 ins->type = STACK_PTR;
8868                                 *sp++ = ins;
8869                                 ip += 6;
8870                                 break;
8871                         default:
8872                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
8873                                 break;
8874                         }
8875                         break;
8876                 }
8877                 case CEE_PREFIX1: {
8878                         CHECK_OPSIZE (2);
8879                         switch (ip [1]) {
8880                         case CEE_ARGLIST: {
8881                                 /* somewhat similar to LDTOKEN */
8882                                 MonoInst *addr, *vtvar;
8883                                 CHECK_STACK_OVF (1);
8884                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
8885
8886                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
8887                                 MONO_INST_NEW (cfg, ins, OP_ARGLIST);
8888                                 ins->inst_left = addr;
8889                                 MONO_ADD_INS (bblock, ins);
8890                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
8891                                 *sp++ = ins;
8892                                 ip += 2;
8893                                 break;
8894                         }
8895                         case CEE_CEQ:
8896                         case CEE_CGT:
8897                         case CEE_CGT_UN:
8898                         case CEE_CLT:
8899                         case CEE_CLT_UN: {
8900                                 MonoInst *cmp;
8901                                 CHECK_STACK (2);
8902                                 /*
8903                                  * The following transforms:
8904                                  *    CEE_CEQ    into OP_CEQ
8905                                  *    CEE_CGT    into OP_CGT
8906                                  *    CEE_CGT_UN into OP_CGT_UN
8907                                  *    CEE_CLT    into OP_CLT
8908                                  *    CEE_CLT_UN into OP_CLT_UN
8909                                  */
8910                                 MONO_INST_NEW (cfg, cmp, (OP_CEQ - CEE_CEQ) + ip [1]);
8911                                 
8912                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
8913                                 sp -= 2;
8914                                 cmp->inst_i0 = sp [0];
8915                                 cmp->inst_i1 = sp [1];
8916                                 type_from_op (cmp);
8917                                 CHECK_TYPE (cmp);
8918                                 ins->type = STACK_I4;
8919                                 ins->inst_i0 = cmp;
8920 #if MONO_ARCH_SOFT_FLOAT
8921                                 if (sp [0]->type == STACK_R8) {
8922                                         cmp->type = STACK_I4;
8923                                         *sp++ = emit_tree (cfg, bblock, cmp, ip + 2);
8924                                         ip += 2;
8925                                         break;
8926                                 }
8927 #endif
8928                                 if ((sp [0]->type == STACK_I8) || ((sizeof (gpointer) == 8) && ((sp [0]->type == STACK_PTR) || (sp [0]->type == STACK_OBJ) || (sp [0]->type == STACK_MP))))
8929                                         cmp->opcode = OP_LCOMPARE;
8930                                 else
8931                                         cmp->opcode = OP_COMPARE;
8932                                 *sp++ = ins;
8933                                 /* spill it to reduce the expression complexity
8934                                  * and workaround bug 54209 
8935                                  */
8936                                 if (cmp->inst_left->type == STACK_I8) {
8937                                         --sp;
8938                                         *sp++ = emit_tree (cfg, bblock, ins, ip + 2);
8939                                 }
8940                                 ip += 2;
8941                                 break;
8942                         }
8943                         case CEE_LDFTN: {
8944                                 MonoInst *argconst;
8945                                 MonoMethod *cil_method, *ctor_method;
8946                                 int temp;
8947                                 gboolean is_shared = FALSE;
8948
8949                                 CHECK_STACK_OVF (1);
8950                                 CHECK_OPSIZE (6);
8951                                 n = read32 (ip + 2);
8952                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
8953                                 if (!cmethod)
8954                                         goto load_error;
8955                                 mono_class_init (cmethod->klass);
8956
8957                                 if (cfg->generic_sharing_context)
8958                                         context_used = mono_method_check_context_used (cmethod);
8959
8960                                 if (mono_class_generic_sharing_enabled (cmethod->klass)) {
8961                                         if ((cmethod->flags & METHOD_ATTRIBUTE_STATIC) &&
8962                                                         (cmethod->klass->generic_class ||
8963                                                         cmethod->klass->generic_container)) {
8964                                                 is_shared = TRUE;
8965                                         }
8966                                         if (cmethod->is_inflated && mono_method_get_context (cmethod)->method_inst)
8967                                                 is_shared = TRUE;
8968                                 }
8969
8970                                 cil_method = cmethod;
8971                                 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cmethod))
8972                                         METHOD_ACCESS_FAILURE;
8973                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
8974                                         if (check_linkdemand (cfg, method, cmethod, bblock, ip))
8975                                                 INLINE_FAILURE;
8976                                         CHECK_CFG_EXCEPTION;
8977                                 } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
8978                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
8979                                 }
8980
8981                                 /* 
8982                                  * Optimize the common case of ldftn+delegate creation
8983                                  */
8984 #if defined(MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE) && !defined(HAVE_WRITE_BARRIERS)
8985                                 /* FIXME: SGEN support */
8986                                 /* FIXME: handle shared static generic methods */
8987                                 /* FIXME: handle this in shared code */
8988                                 if (!is_shared && !context_used && (sp > stack_start) && (ip + 6 + 5 < end) && ip_in_bb (cfg, bblock, ip + 6) && (ip [6] == CEE_NEWOBJ) && (ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context)) && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
8989                                         MonoInst *target_ins;
8990
8991                                         ip += 6;
8992                                         if (cfg->verbose_level > 3)
8993                                                 g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
8994                                         target_ins = sp [-1];
8995                                         sp --;
8996                                         *sp = handle_delegate_ctor (cfg, bblock, ctor_method->klass, target_ins, cmethod, ip);
8997                                         ip += 5;                                        
8998                                         sp ++;
8999                                         break;
9000                                 }
9001 #endif
9002
9003                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
9004
9005                                 if (context_used) {
9006                                         MonoInst *rgctx;
9007
9008                                         if (is_shared)
9009                                                 cmethod = mono_marshal_get_static_rgctx_invoke (cmethod);
9010
9011                                         GET_RGCTX (rgctx, context_used);
9012                                         argconst = get_runtime_generic_context_method (cfg, method, context_used,
9013                                                         bblock, cmethod,
9014                                                         generic_context, rgctx, MONO_RGCTX_INFO_METHOD, ip);
9015                                 } else if (is_shared) {
9016                                         NEW_METHODCONST (cfg, argconst, mono_marshal_get_static_rgctx_invoke (cmethod));
9017                                 } else {
9018                                         NEW_METHODCONST (cfg, argconst, cmethod);
9019                                 }
9020                                 if (method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
9021                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
9022                                 else
9023                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn_nosync, &argconst, ip);
9024                                 NEW_TEMPLOAD (cfg, *sp, temp);
9025                                 sp ++;
9026                                 
9027                                 ip += 6;
9028                                 inline_costs += 10 * num_calls++;
9029                                 break;
9030                         }
9031                         case CEE_LDVIRTFTN: {
9032                                 MonoInst *args [2];
9033                                 int temp;
9034
9035                                 CHECK_STACK (1);
9036                                 CHECK_OPSIZE (6);
9037                                 n = read32 (ip + 2);
9038                                 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
9039                                 if (!cmethod)
9040                                         goto load_error;
9041                                 mono_class_init (cmethod->klass);
9042
9043                                 if (cfg->generic_sharing_context)
9044                                         context_used = mono_method_check_context_used (cmethod);
9045
9046                                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
9047                                         if (check_linkdemand (cfg, method, cmethod, bblock, ip))
9048                                                 INLINE_FAILURE;
9049                                         CHECK_CFG_EXCEPTION;
9050                                 } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
9051                                         ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
9052                                 }
9053
9054                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
9055
9056                                 --sp;
9057                                 args [0] = *sp;
9058                                 if (context_used) {
9059                                         MonoInst *rgctx;
9060
9061                                         GET_RGCTX (rgctx, context_used);
9062                                         args [1] = get_runtime_generic_context_method (cfg, method, context_used,
9063                                                         bblock, cmethod,
9064                                                         generic_context, rgctx, MONO_RGCTX_INFO_METHOD, ip);
9065                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn_gshared, args, ip);
9066                                 } else {
9067                                         NEW_METHODCONST (cfg, args [1], cmethod);
9068                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
9069                                 }
9070                                 NEW_TEMPLOAD (cfg, *sp, temp);
9071                                 sp ++;
9072
9073                                 ip += 6;
9074                                 inline_costs += 10 * num_calls++;
9075                                 break;
9076                         }
9077                         case CEE_LDARG:
9078                                 CHECK_STACK_OVF (1);
9079                                 CHECK_OPSIZE (4);
9080                                 n = read16 (ip + 2);
9081                                 CHECK_ARG (n);
9082                                 NEW_ARGLOAD (cfg, ins, n);
9083                                 LDARG_SOFT_FLOAT (cfg, ins, n, ip);
9084                                 *sp++ = ins;
9085                                 ip += 4;
9086                                 break;
9087                         case CEE_LDARGA:
9088                                 CHECK_STACK_OVF (1);
9089                                 CHECK_OPSIZE (4);
9090                                 n = read16 (ip + 2);
9091                                 CHECK_ARG (n);
9092                                 NEW_ARGLOADA (cfg, ins, n);
9093                                 *sp++ = ins;
9094                                 ip += 4;
9095                                 break;
9096                         case CEE_STARG:
9097                                 CHECK_STACK (1);
9098                                 --sp;
9099                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
9100                                 CHECK_OPSIZE (4);
9101                                 n = read16 (ip + 2);
9102                                 CHECK_ARG (n);
9103                                 NEW_ARGSTORE (cfg, ins, n, *sp);
9104                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
9105                                         UNVERIFIED;
9106                                 STARG_SOFT_FLOAT (cfg, ins, n, ip);
9107                                 if (ins->opcode == CEE_STOBJ) {
9108                                         NEW_ARGLOADA (cfg, ins, n);
9109                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
9110                                 } else
9111                                         MONO_ADD_INS (bblock, ins);
9112                                 ip += 4;
9113                                 break;
9114                         case CEE_LDLOC:
9115                                 CHECK_STACK_OVF (1);
9116                                 CHECK_OPSIZE (4);
9117                                 n = read16 (ip + 2);
9118                                 CHECK_LOCAL (n);
9119                                 NEW_LOCLOAD (cfg, ins, n);
9120                                 LDLOC_SOFT_FLOAT (cfg, ins, n, ip);
9121                                 *sp++ = ins;
9122                                 ip += 4;
9123                                 break;
9124                         case CEE_LDLOCA:
9125                                 CHECK_STACK_OVF (1);
9126                                 CHECK_OPSIZE (4);
9127                                 n = read16 (ip + 2);
9128                                 CHECK_LOCAL (n);
9129                                 NEW_LOCLOADA (cfg, ins, n);
9130                                 *sp++ = ins;
9131                                 ip += 4;
9132                                 break;
9133                         case CEE_STLOC:
9134                                 CHECK_STACK (1);
9135                                 --sp;
9136                                 CHECK_OPSIZE (4);
9137                                 n = read16 (ip + 2);
9138                                 CHECK_LOCAL (n);
9139                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
9140                                 NEW_LOCSTORE (cfg, ins, n, *sp);
9141                                 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
9142                                         UNVERIFIED;
9143                                 STLOC_SOFT_FLOAT (cfg, ins, n, ip);
9144                                 if (ins->opcode == CEE_STOBJ) {
9145                                         NEW_LOCLOADA (cfg, ins, n);
9146                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
9147                                 } else
9148                                         MONO_ADD_INS (bblock, ins);
9149                                 ip += 4;
9150                                 inline_costs += 1;
9151                                 break;
9152                         case CEE_LOCALLOC:
9153                                 CHECK_STACK (1);
9154                                 --sp;
9155                                 if (sp != stack_start) 
9156                                         UNVERIFIED;
9157                                 if (cfg->method != method) 
9158                                         /* 
9159                                          * Inlining this into a loop in a parent could lead to 
9160                                          * stack overflows which is different behavior than the
9161                                          * non-inlined case, thus disable inlining in this case.
9162                                          */
9163                                         goto inline_failure;
9164                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
9165                                 ins->inst_left = *sp;
9166                                 ins->type = STACK_PTR;
9167
9168                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
9169                                 if (header->init_locals)
9170                                         ins->flags |= MONO_INST_INIT;
9171
9172                                 *sp++ = ins;
9173                                 ip += 2;
9174                                 /* FIXME: set init flag if locals init is set in this method */
9175                                 break;
9176                         case CEE_ENDFILTER: {
9177                                 MonoExceptionClause *clause, *nearest;
9178                                 int cc, nearest_num;
9179
9180                                 CHECK_STACK (1);
9181                                 --sp;
9182                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
9183                                         UNVERIFIED;
9184                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
9185                                 ins->inst_left = *sp;
9186                                 MONO_ADD_INS (bblock, ins);
9187                                 start_new_bblock = 1;
9188                                 ip += 2;
9189
9190                                 nearest = NULL;
9191                                 nearest_num = 0;
9192                                 for (cc = 0; cc < header->num_clauses; ++cc) {
9193                                         clause = &header->clauses [cc];
9194                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
9195                                                 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
9196                                             (!nearest || (clause->data.filter_offset < nearest->data.filter_offset))) {
9197                                                 nearest = clause;
9198                                                 nearest_num = cc;
9199                                         }
9200                                 }
9201                                 g_assert (nearest);
9202                                 if ((ip - header->code) != nearest->handler_offset)
9203                                         UNVERIFIED;
9204
9205                                 break;
9206                         }
9207                         case CEE_UNALIGNED_:
9208                                 ins_flag |= MONO_INST_UNALIGNED;
9209                                 /* FIXME: record alignment? we can assume 1 for now */
9210                                 CHECK_OPSIZE (3);
9211                                 ip += 3;
9212                                 break;
9213                         case CEE_VOLATILE_:
9214                                 ins_flag |= MONO_INST_VOLATILE;
9215                                 ip += 2;
9216                                 break;
9217                         case CEE_TAIL_:
9218                                 ins_flag   |= MONO_INST_TAILCALL;
9219                                 cfg->flags |= MONO_CFG_HAS_TAIL;
9220                                 /* Can't inline tail calls at this time */
9221                                 inline_costs += 100000;
9222                                 ip += 2;
9223                                 break;
9224                         case CEE_INITOBJ:
9225                                 CHECK_STACK (1);
9226                                 --sp;
9227                                 CHECK_OPSIZE (6);
9228                                 token = read32 (ip + 2);
9229                                 klass = mini_get_class (method, token, generic_context);
9230                                 CHECK_TYPELOAD (klass);
9231
9232                                 if (generic_class_is_reference_type (cfg, klass)) {
9233                                         MonoInst *store, *load;
9234                                         NEW_PCONST (cfg, load, NULL);
9235                                         load->type = STACK_OBJ;
9236                                         load->klass = klass;
9237                                         MONO_INST_NEW (cfg, store, CEE_STIND_REF);
9238                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
9239                                         MONO_ADD_INS (bblock, store);
9240                                         store->inst_i0 = sp [0];
9241                                         store->inst_i1 = load;
9242                                 } else {
9243                                         handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
9244                                 }
9245                                 ip += 6;
9246                                 inline_costs += 1;
9247                                 break;
9248                         case CEE_CONSTRAINED_:
9249                                 /* FIXME: implement */
9250                                 CHECK_OPSIZE (6);
9251                                 token = read32 (ip + 2);
9252                                 constrained_call = mono_class_get_full (image, token, generic_context);
9253                                 CHECK_TYPELOAD (constrained_call);
9254                                 ip += 6;
9255                                 break;
9256                         case CEE_CPBLK:
9257                         case CEE_INITBLK: {
9258                                 MonoInst *iargs [3];
9259                                 CHECK_STACK (3);
9260                                 sp -= 3;
9261                                 if ((cfg->opt & MONO_OPT_INTRINS) && (ip [1] == CEE_CPBLK) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5)) {
9262                                         MonoInst *copy;
9263                                         NEW_MEMCPY (cfg, copy, sp [0], sp [1], n, 0);
9264                                         MONO_ADD_INS (bblock, copy);
9265                                         ip += 2;
9266                                         break;
9267                                 }
9268                                 iargs [0] = sp [0];
9269                                 iargs [1] = sp [1];
9270                                 iargs [2] = sp [2];
9271                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
9272                                 if (ip [1] == CEE_CPBLK) {
9273                                         MonoMethod *memcpy_method = get_memcpy_method ();
9274                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
9275                                 } else {
9276                                         MonoMethod *memset_method = get_memset_method ();
9277                                         mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
9278                                 }
9279                                 ip += 2;
9280                                 inline_costs += 1;
9281                                 break;
9282                         }
9283                         case CEE_NO_:
9284                                 CHECK_OPSIZE (3);
9285                                 if (ip [2] & 0x1)
9286                                         ins_flag |= MONO_INST_NOTYPECHECK;
9287                                 if (ip [2] & 0x2)
9288                                         ins_flag |= MONO_INST_NORANGECHECK;
9289                                 /* we ignore the no-nullcheck for now since we
9290                                  * really do it explicitly only when doing callvirt->call
9291                                  */
9292                                 ip += 3;
9293                                 break;
9294                         case CEE_RETHROW: {
9295                                 MonoInst *load;
9296                                 int handler_offset = -1;
9297
9298                                 for (i = 0; i < header->num_clauses; ++i) {
9299                                         MonoExceptionClause *clause = &header->clauses [i];
9300                                         if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY))
9301                                                 handler_offset = clause->handler_offset;
9302                                 }
9303
9304                                 bblock->flags |= BB_EXCEPTION_UNSAFE;
9305
9306                                 g_assert (handler_offset != -1);
9307
9308                                 NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
9309                                 MONO_INST_NEW (cfg, ins, OP_RETHROW);
9310                                 ins->inst_left = load;
9311                                 MONO_ADD_INS (bblock, ins);
9312                                 sp = stack_start;
9313                                 link_bblock (cfg, bblock, end_bblock);
9314                                 start_new_bblock = 1;
9315                                 ip += 2;
9316                                 break;
9317                         }
9318                         case CEE_SIZEOF:
9319                                 CHECK_STACK_OVF (1);
9320                                 CHECK_OPSIZE (6);
9321                                 token = read32 (ip + 2);
9322                                 /* FIXXME: handle generics. */
9323                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
9324                                         MonoType *type = mono_type_create_from_typespec (image, token);
9325                                         token = mono_type_size (type, &ialign);
9326                                 } else {
9327                                         MonoClass *klass = mono_class_get_full (image, token, generic_context);
9328                                         CHECK_TYPELOAD (klass);
9329                                         mono_class_init (klass);
9330                                         token = mono_class_value_size (klass, &align);
9331                                 }
9332                                 NEW_ICONST (cfg, ins, token);
9333                                 *sp++= ins;
9334                                 ip += 6;
9335                                 break;
9336                         case CEE_REFANYTYPE:
9337                                 CHECK_STACK (1);
9338                                 MONO_INST_NEW (cfg, ins, OP_REFANYTYPE);
9339                                 --sp;
9340                                 ins->type = STACK_MP;
9341                                 ins->inst_left = *sp;
9342                                 ins->type = STACK_VTYPE;
9343                                 ins->klass = mono_defaults.typehandle_class;
9344                                 ip += 2;
9345                                 *sp++ = ins;
9346                                 break;
9347                         case CEE_READONLY_:
9348                                 readonly = TRUE;
9349                                 ip += 2;
9350                                 break;
9351                         default:
9352                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
9353                         }
9354                         break;
9355                 }
9356                 default:
9357                         g_error ("opcode 0x%02x not handled", *ip);
9358                 }
9359         }
9360         if (start_new_bblock != 1)
9361                 UNVERIFIED;
9362
9363         bblock->cil_length = ip - bblock->cil_code;
9364         bblock->next_bb = end_bblock;
9365
9366         if (cfg->method == method && cfg->domainvar) {
9367                 MonoInst *store;
9368                 MonoInst *get_domain;
9369                 
9370                 if (! (get_domain = mono_arch_get_domain_intrinsic (cfg))) {
9371                         MonoCallInst *call;
9372                         
9373                         MONO_INST_NEW_CALL (cfg, call, OP_CALL);
9374                         call->signature = helper_sig_domain_get;
9375                         call->inst.type = STACK_PTR;
9376                         call->fptr = mono_domain_get;
9377                         get_domain = (MonoInst*)call;
9378                 }
9379                 
9380                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
9381                 MONO_ADD_INS (init_localsbb, store);
9382         }
9383
9384         if (cfg->method == method && cfg->got_var)
9385                 mono_emit_load_got_addr (cfg);
9386
9387         if (header->init_locals) {
9388                 MonoInst *store;
9389                 cfg->ip = header->code;
9390                 for (i = 0; i < header->num_locals; ++i) {
9391                         MonoType *ptype = header->locals [i];
9392                         int t = ptype->type;
9393                         if (t == MONO_TYPE_VALUETYPE && ptype->data.klass->enumtype)
9394                                 t = ptype->data.klass->enum_basetype->type;
9395                         if (ptype->byref) {
9396                                 NEW_PCONST (cfg, ins, NULL);
9397                                 NEW_LOCSTORE (cfg, store, i, ins);
9398                                 MONO_ADD_INS (init_localsbb, store);
9399                         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
9400                                 NEW_ICONST (cfg, ins, 0);
9401                                 NEW_LOCSTORE (cfg, store, i, ins);
9402                                 MONO_ADD_INS (init_localsbb, store);
9403                         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
9404                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
9405                                 ins->type = STACK_I8;
9406                                 ins->inst_l = 0;
9407                                 NEW_LOCSTORE (cfg, store, i, ins);
9408                                 MONO_ADD_INS (init_localsbb, store);
9409                         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
9410 #ifdef MONO_ARCH_SOFT_FLOAT
9411                                 /* FIXME: handle init of R4 */
9412 #else
9413                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
9414                                 ins->type = STACK_R8;
9415                                 ins->inst_p0 = (void*)&r8_0;
9416                                 NEW_LOCSTORE (cfg, store, i, ins);
9417                                 MONO_ADD_INS (init_localsbb, store);
9418 #endif
9419                         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
9420                                    ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (ptype))) {
9421                                 NEW_LOCLOADA (cfg, ins, i);
9422                                 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (ptype), NULL, NULL);
9423                         } else {
9424                                 NEW_PCONST (cfg, ins, NULL);
9425                                 NEW_LOCSTORE (cfg, store, i, ins);
9426                                 MONO_ADD_INS (init_localsbb, store);
9427                         }
9428                 }
9429         }
9430
9431         cfg->ip = NULL;
9432
9433         /* resolve backward branches in the middle of an existing basic block */
9434         for (tmp = bb_recheck; tmp; tmp = tmp->next) {
9435                 bblock = tmp->data;
9436                 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
9437                 tblock = find_previous (cfg->cil_offset_to_bb, header->code_size, start_bblock, bblock->cil_code);
9438                 if (tblock != start_bblock) {
9439                         int l;
9440                         split_bblock (cfg, tblock, bblock);
9441                         l = bblock->cil_code - header->code;
9442                         bblock->cil_length = tblock->cil_length - l;
9443                         tblock->cil_length = l;
9444                 } else {
9445                         g_print ("recheck failed.\n");
9446                 }
9447         }
9448
9449         if (cfg->method == method) {
9450                 MonoBasicBlock *bb;
9451                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9452                         bb->region = mono_find_block_region (cfg, bb->real_offset);
9453                         if (cfg->spvars)
9454                                 mono_create_spvar_for_region (cfg, bb->region);
9455                         if (cfg->verbose_level > 2)
9456                                 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
9457                 }
9458         }
9459
9460         g_slist_free (class_inits);
9461         dont_inline = g_list_remove (dont_inline, method);
9462
9463         if (inline_costs < 0) {
9464                 char *mname;
9465
9466                 /* Method is too large */
9467                 mname = mono_method_full_name (method, TRUE);
9468                 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
9469                 cfg->exception_message = g_strdup_printf ("Method %s is too complex.", mname);
9470                 g_free (mname);
9471                 return -1;
9472         }
9473
9474         return inline_costs;
9475
9476  exception_exit:
9477         g_assert (cfg->exception_type != MONO_EXCEPTION_NONE);
9478         g_slist_free (class_inits);
9479         dont_inline = g_list_remove (dont_inline, method);
9480         return -1;
9481
9482  inline_failure:
9483         g_slist_free (class_inits);
9484         dont_inline = g_list_remove (dont_inline, method);
9485         return -1;
9486
9487  load_error:
9488         g_slist_free (class_inits);
9489         dont_inline = g_list_remove (dont_inline, method);
9490         cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
9491         return -1;
9492
9493  unverified:
9494         g_slist_free (class_inits);
9495         dont_inline = g_list_remove (dont_inline, method);
9496         set_exception_type_from_invalid_il (cfg, method, ip);
9497         return -1;
9498 }
9499
9500 void
9501 mono_print_tree (MonoInst *tree) {
9502         int arity;
9503
9504         if (!tree)
9505                 return;
9506
9507         arity = mono_burg_arity [tree->opcode];
9508
9509         printf (" %s%s", arity?"(":"",  mono_inst_name (tree->opcode));
9510
9511         switch (tree->opcode) {
9512         case OP_ICONST:
9513                 printf ("[%d]", (int)tree->inst_c0);
9514                 break;
9515         case OP_I8CONST:
9516                 printf ("[%lld]", (long long)tree->inst_l);
9517                 break;
9518         case OP_R8CONST:
9519                 printf ("[%f]", *(double*)tree->inst_p0);
9520                 break;
9521         case OP_R4CONST:
9522                 printf ("[%f]", *(float*)tree->inst_p0);
9523                 break;
9524         case OP_ARG:
9525         case OP_LOCAL:
9526                 printf ("[%d]", (int)tree->inst_c0);
9527                 break;
9528         case OP_REGOFFSET:
9529                 if (tree->inst_offset < 0)
9530                         printf ("[-0x%x(%s)]", (int)(-tree->inst_offset), mono_arch_regname (tree->inst_basereg));
9531                 else
9532                         printf ("[0x%x(%s)]", (int)(tree->inst_offset), mono_arch_regname (tree->inst_basereg));
9533                 break;
9534         case OP_REGVAR:
9535                 printf ("[%s]", mono_arch_regname (tree->dreg));
9536                 break;
9537         case CEE_NEWARR:
9538                 printf ("[%s]",  tree->inst_newa_class->name);
9539                 mono_print_tree (tree->inst_newa_len);
9540                 break;
9541         case OP_CALL:
9542         case OP_CALLVIRT:
9543         case OP_FCALL:
9544         case OP_FCALLVIRT:
9545         case OP_LCALL:
9546         case OP_LCALLVIRT:
9547         case OP_VCALL:
9548         case OP_VCALLVIRT:
9549         case OP_VOIDCALL:
9550         case OP_VOIDCALLVIRT:
9551         case OP_TRAMPCALL_VTABLE: {
9552                 MonoCallInst *call = (MonoCallInst*)tree;
9553                 if (call->method)
9554                         printf ("[%s]", call->method->name);
9555                 else if (call->fptr) {
9556                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (call->fptr);
9557                         if (info)
9558                                 printf ("[%s]", info->name);
9559                 }
9560                 break;
9561         }
9562         case OP_PHI: {
9563                 int i;
9564                 printf ("[%d (", (int)tree->inst_c0);
9565                 for (i = 0; i < tree->inst_phi_args [0]; i++) {
9566                         if (i)
9567                                 printf (", ");
9568                         printf ("%d", tree->inst_phi_args [i + 1]);
9569                 }
9570                 printf (")]");
9571                 break;
9572         }
9573         case OP_RENAME:
9574         case OP_RETARG:
9575         case OP_NOP:
9576         case OP_JMP:
9577         case OP_BREAK:
9578                 break;
9579         case OP_LOAD_MEMBASE:
9580         case OP_LOADI4_MEMBASE:
9581         case OP_LOADU4_MEMBASE:
9582         case OP_LOADU1_MEMBASE:
9583         case OP_LOADI1_MEMBASE:
9584         case OP_LOADU2_MEMBASE:
9585         case OP_LOADI2_MEMBASE:
9586                 printf ("[%s] <- [%s + 0x%x]", mono_arch_regname (tree->dreg), mono_arch_regname (tree->inst_basereg), (int)tree->inst_offset);
9587                 break;
9588         case OP_BR:
9589         case OP_CALL_HANDLER:
9590                 printf ("[B%d]", tree->inst_target_bb->block_num);
9591                 break;
9592         case OP_SWITCH:
9593         case CEE_ISINST:
9594         case CEE_CASTCLASS:
9595         case OP_OUTARG:
9596         case OP_CALL_REG:
9597         case OP_FCALL_REG:
9598         case OP_LCALL_REG:
9599         case OP_VCALL_REG:
9600         case OP_VOIDCALL_REG:
9601                 mono_print_tree (tree->inst_left);
9602                 break;
9603         case CEE_BNE_UN:
9604         case CEE_BEQ:
9605         case CEE_BLT:
9606         case CEE_BLT_UN:
9607         case CEE_BGT:
9608         case CEE_BGT_UN:
9609         case CEE_BGE:
9610         case CEE_BGE_UN:
9611         case CEE_BLE:
9612         case CEE_BLE_UN:
9613                 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
9614                 mono_print_tree (tree->inst_left);
9615                 break;
9616         default:
9617                 if (!mono_arch_print_tree(tree, arity)) {
9618                         if (arity) {
9619                                 mono_print_tree (tree->inst_left);
9620                                 if (arity > 1)
9621                                         mono_print_tree (tree->inst_right);
9622                         }
9623                 }
9624                 break;
9625         }
9626
9627         if (arity)
9628                 printf (")");
9629 }
9630
9631 void
9632 mono_print_tree_nl (MonoInst *tree)
9633 {
9634         mono_print_tree (tree);
9635         printf ("\n");
9636 }
9637
9638 static void
9639 create_helper_signature (void)
9640 {
9641         helper_sig_domain_get = mono_create_icall_signature ("ptr");
9642         helper_sig_class_init_trampoline = mono_create_icall_signature ("void");
9643         helper_sig_generic_class_init_trampoline = mono_create_icall_signature ("void");
9644         helper_sig_rgctx_lazy_fetch_trampoline = mono_create_icall_signature ("ptr ptr");
9645 }
9646
9647 gconstpointer
9648 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
9649 {
9650         char *name;
9651         MonoMethod *wrapper;
9652         gconstpointer trampoline;
9653         MonoDomain *domain = mono_get_root_domain ();
9654         
9655         if (callinfo->wrapper) {
9656                 return callinfo->wrapper;
9657         }
9658
9659         if (callinfo->trampoline)
9660                 return callinfo->trampoline;
9661
9662         /* 
9663          * We use the lock on the root domain instead of the JIT lock to protect 
9664          * callinfo->trampoline, since we do a lot of stuff inside the critical section.
9665          */
9666         mono_domain_lock (domain);
9667
9668         if (callinfo->trampoline) {
9669                 mono_domain_unlock (domain);
9670                 return callinfo->trampoline;
9671         }
9672
9673         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
9674         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
9675         g_free (name);
9676
9677         trampoline = mono_create_ftnptr (domain, mono_create_jit_trampoline_in_domain (domain, wrapper, TRUE));
9678         mono_register_jit_icall_wrapper (callinfo, trampoline);
9679
9680         callinfo->trampoline = trampoline;
9681
9682         mono_domain_unlock (domain);
9683         
9684         return callinfo->trampoline;
9685 }
9686
9687 static void
9688 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
9689 {
9690         if (!domain->dynamic_code_hash)
9691                 domain->dynamic_code_hash = g_hash_table_new (NULL, NULL);
9692         g_hash_table_insert (domain->dynamic_code_hash, method, ji);
9693 }
9694
9695 static MonoJitDynamicMethodInfo*
9696 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
9697 {
9698         MonoJitDynamicMethodInfo *res;
9699
9700         if (domain->dynamic_code_hash)
9701                 res = g_hash_table_lookup (domain->dynamic_code_hash, method);
9702         else
9703                 res = NULL;
9704         return res;
9705 }
9706
9707 typedef struct {
9708         MonoClass *vtype;
9709         GList *active;
9710         GSList *slots;
9711 } StackSlotInfo;
9712
9713 static inline GSList*
9714 g_slist_prepend_mempool (MonoMemPool *mp, GSList   *list,
9715                                                  gpointer  data)
9716 {
9717   GSList *new_list;
9718
9719   new_list = mono_mempool_alloc (mp, sizeof (GSList));
9720   new_list->data = data;
9721   new_list->next = list;
9722
9723   return new_list;
9724 }
9725
9726 /*
9727  *  mono_allocate_stack_slots_full:
9728  *
9729  *  Allocate stack slots for all non register allocated variables using a
9730  * linear scan algorithm.
9731  * Returns: an array of stack offsets.
9732  * STACK_SIZE is set to the amount of stack space needed.
9733  * STACK_ALIGN is set to the alignment needed by the locals area.
9734  */
9735 gint32*
9736 mono_allocate_stack_slots_full (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
9737 {
9738         int i, slot, offset, size;
9739         guint32 align;
9740         MonoMethodVar *vmv;
9741         MonoInst *inst;
9742         gint32 *offsets;
9743         GList *vars = NULL, *l;
9744         StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
9745         MonoType *t;
9746         int nvtypes;
9747
9748         scalar_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
9749         vtype_stack_slots = NULL;
9750         nvtypes = 0;
9751
9752         offsets = mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
9753         for (i = 0; i < cfg->num_varinfo; ++i)
9754                 offsets [i] = -1;
9755
9756         for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
9757                 inst = cfg->varinfo [i];
9758                 vmv = MONO_VARINFO (cfg, i);
9759
9760                 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
9761                         continue;
9762
9763                 vars = g_list_prepend (vars, vmv);
9764         }
9765
9766         vars = mono_varlist_sort (cfg, vars, 0);
9767         offset = 0;
9768         *stack_align = 0;
9769         for (l = vars; l; l = l->next) {
9770                 vmv = l->data;
9771                 inst = cfg->varinfo [vmv->idx];
9772
9773                 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
9774                 * pinvoke wrappers when they call functions returning structures */
9775                 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF)
9776                         size = mono_class_native_size (inst->inst_vtype->data.klass, &align);
9777                 else {
9778                         int ialign;
9779
9780                         size = mono_type_size (inst->inst_vtype, &ialign);
9781                         align = ialign;
9782                 }
9783
9784                 t = mono_type_get_underlying_type (inst->inst_vtype);
9785                 if (t->byref) {
9786                         slot_info = &scalar_stack_slots [MONO_TYPE_I];
9787                 } else {
9788                         switch (t->type) {
9789                         case MONO_TYPE_GENERICINST:
9790                                 if (!mono_type_generic_inst_is_valuetype (t)) {
9791                                         slot_info = &scalar_stack_slots [t->type];
9792                                         break;
9793                                 }
9794                                 /* Fall through */
9795                         case MONO_TYPE_VALUETYPE:
9796                                 if (!vtype_stack_slots)
9797                                         vtype_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * 256);
9798                                 for (i = 0; i < nvtypes; ++i)
9799                                         if (t->data.klass == vtype_stack_slots [i].vtype)
9800                                                 break;
9801                                 if (i < nvtypes)
9802                                         slot_info = &vtype_stack_slots [i];
9803                                 else {
9804                                         g_assert (nvtypes < 256);
9805                                         vtype_stack_slots [nvtypes].vtype = t->data.klass;
9806                                         slot_info = &vtype_stack_slots [nvtypes];
9807                                         nvtypes ++;
9808                                 }
9809                                 break;
9810                         case MONO_TYPE_CLASS:
9811                         case MONO_TYPE_OBJECT:
9812                         case MONO_TYPE_ARRAY:
9813                         case MONO_TYPE_SZARRAY:
9814                         case MONO_TYPE_STRING:
9815                         case MONO_TYPE_PTR:
9816                         case MONO_TYPE_I:
9817                         case MONO_TYPE_U:
9818 #if SIZEOF_VOID_P == 4
9819                         case MONO_TYPE_I4:
9820 #else
9821                         case MONO_TYPE_I8:
9822 #endif
9823                                 /* Share non-float stack slots of the same size */
9824                                 slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
9825                                 break;
9826                         default:
9827                                 slot_info = &scalar_stack_slots [t->type];
9828                         }
9829                 }
9830
9831                 slot = 0xffffff;
9832                 if (cfg->comp_done & MONO_COMP_LIVENESS) {
9833                         //printf ("START  %2d %08x %08x\n",  vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
9834                         
9835                         /* expire old intervals in active */
9836                         while (slot_info->active) {
9837                                 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
9838
9839                                 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
9840                                         break;
9841
9842                                 //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);
9843
9844                                 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
9845                                 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
9846                         }
9847
9848                         /* 
9849                          * This also handles the case when the variable is used in an
9850                          * exception region, as liveness info is not computed there.
9851                          */
9852                         /* 
9853                          * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
9854                          * opcodes.
9855                          */
9856                         if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
9857                                 if (slot_info->slots) {
9858                                         slot = GPOINTER_TO_INT (slot_info->slots->data);
9859
9860                                         slot_info->slots = slot_info->slots->next;
9861                                 }
9862
9863                                 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
9864                         }
9865                 }
9866
9867                 {
9868                         static int count = 0;
9869                         count ++;
9870
9871                         /*
9872                         if (count == atoi (getenv ("COUNT")))
9873                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
9874                         if (count > atoi (getenv ("COUNT")))
9875                                 slot = 0xffffff;
9876                         else {
9877                                 mono_print_tree_nl (inst);
9878                                 }
9879                         */
9880                 }
9881
9882                 if (cfg->disable_reuse_stack_slots)
9883                         slot = 0xffffff;
9884
9885                 if (slot == 0xffffff) {
9886                         /*
9887                          * Allways allocate valuetypes to sizeof (gpointer) to allow more
9888                          * efficient copying (and to work around the fact that OP_MEMCPY
9889                          * and OP_MEMSET ignores alignment).
9890                          */
9891                         if (MONO_TYPE_ISSTRUCT (t))
9892                                 align = sizeof (gpointer);
9893
9894                         if (backward) {
9895                                 offset += size;
9896                                 offset += align - 1;
9897                                 offset &= ~(align - 1);
9898                                 slot = offset;
9899                         }
9900                         else {
9901                                 offset += align - 1;
9902                                 offset &= ~(align - 1);
9903                                 slot = offset;
9904                                 offset += size;
9905                         }
9906
9907                         if (*stack_align == 0)
9908                                 *stack_align = align;
9909                 }
9910
9911                 offsets [vmv->idx] = slot;
9912         }
9913         g_list_free (vars);
9914         for (i = 0; i < MONO_TYPE_PINNED; ++i) {
9915                 if (scalar_stack_slots [i].active)
9916                         g_list_free (scalar_stack_slots [i].active);
9917         }
9918         for (i = 0; i < nvtypes; ++i) {
9919                 if (vtype_stack_slots [i].active)
9920                         g_list_free (vtype_stack_slots [i].active);
9921         }
9922
9923         mono_jit_stats.locals_stack_size += offset;
9924
9925         *stack_size = offset;
9926         return offsets;
9927 }
9928
9929 gint32*
9930 mono_allocate_stack_slots (MonoCompile *m, guint32 *stack_size, guint32 *stack_align)
9931 {
9932         return mono_allocate_stack_slots_full (m, TRUE, stack_size, stack_align);
9933 }
9934
9935 void
9936 mono_register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, gboolean no_throw)
9937 {
9938         MonoJitICallInfo *info;
9939         MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
9940
9941         if (!emul_opcode_map)
9942                 emul_opcode_map = g_new0 (MonoJitICallInfo*, OP_LAST + 1);
9943
9944         g_assert (!sig->hasthis);
9945         g_assert (sig->param_count < 3);
9946
9947         info = mono_register_jit_icall (func, name, sig, no_throw);
9948
9949         emul_opcode_map [opcode] = info;
9950 }
9951
9952 static void
9953 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
9954 {
9955         MonoMethodSignature *sig;
9956
9957         if (sigstr)
9958                 sig = mono_create_icall_signature (sigstr);
9959         else
9960                 sig = NULL;
9961
9962         mono_register_jit_icall (func, name, sig, save);
9963 }
9964
9965 static void
9966 decompose_foreach (MonoInst *tree, gpointer data) 
9967 {
9968         static MonoJitICallInfo *newarr_info = NULL;
9969         static MonoJitICallInfo *newarr_specific_info = NULL;
9970         MonoJitICallInfo *info;
9971         int i;
9972
9973         switch (tree->opcode) {
9974         case CEE_NEWARR: {
9975                 MonoCompile *cfg = data;
9976                 MonoInst *iargs [3];
9977
9978                 if (!newarr_info) {
9979                         newarr_info = mono_find_jit_icall_by_addr (mono_array_new);
9980                         g_assert (newarr_info);
9981                         newarr_specific_info = mono_find_jit_icall_by_addr (mono_array_new_specific);
9982                         g_assert (newarr_specific_info);
9983                 }
9984
9985                 if (cfg->opt & MONO_OPT_SHARED) {
9986                         NEW_DOMAINCONST (cfg, iargs [0]);
9987                         NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
9988                         iargs [2] = tree->inst_newa_len;
9989
9990                         info = newarr_info;
9991                 }
9992                 else {
9993                         MonoVTable *vtable = mono_class_vtable (cfg->domain, mono_array_class_get (tree->inst_newa_class, 1));
9994
9995                         g_assert (vtable);
9996                         NEW_VTABLECONST (cfg, iargs [0], vtable);
9997                         iargs [1] = tree->inst_newa_len;
9998
9999                         info = newarr_specific_info;
10000                 }
10001
10002                 mono_emulate_opcode (cfg, tree, iargs, info);
10003
10004                 /* Need to decompose arguments after the the opcode is decomposed */
10005                 for (i = 0; i < info->sig->param_count; ++i)
10006                         dec_foreach (iargs [i], cfg);
10007                 break;
10008         }
10009 #ifdef MONO_ARCH_SOFT_FLOAT
10010         case OP_FBEQ:
10011         case OP_FBGE:
10012         case OP_FBGT:
10013         case OP_FBLE:
10014         case OP_FBLT:
10015         case OP_FBNE_UN:
10016         case OP_FBGE_UN:
10017         case OP_FBGT_UN:
10018         case OP_FBLE_UN:
10019         case OP_FBLT_UN: {
10020                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
10021                         MonoCompile *cfg = data;
10022                         MonoInst *iargs [2];
10023                 
10024                         iargs [0] = tree->inst_i0;
10025                         iargs [1] = tree->inst_i1;
10026                 
10027                         mono_emulate_opcode (cfg, tree, iargs, info);
10028
10029                         dec_foreach (iargs [0], cfg);
10030                         dec_foreach (iargs [1], cfg);
10031                         break;
10032                 } else {
10033                         g_assert_not_reached ();
10034                 }
10035                 break;
10036         }
10037         case OP_FCEQ:
10038         case OP_FCGT:
10039         case OP_FCGT_UN:
10040         case OP_FCLT:
10041         case OP_FCLT_UN: {
10042                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
10043                         MonoCompile *cfg = data;
10044                         MonoInst *iargs [2];
10045
10046                         /* the args are in the compare opcode ... */
10047                         iargs [0] = tree->inst_i0;
10048                         iargs [1] = tree->inst_i1;
10049                 
10050                         mono_emulate_opcode (cfg, tree, iargs, info);
10051
10052                         dec_foreach (iargs [0], cfg);
10053                         dec_foreach (iargs [1], cfg);
10054                         break;
10055                 } else {
10056                         g_assert_not_reached ();
10057                 }
10058                 break;
10059         }
10060 #endif
10061
10062         default:
10063                 break;
10064         }
10065 }
10066
10067 void
10068 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
10069
10070         switch (mono_burg_arity [tree->opcode]) {
10071         case 0: break;
10072         case 1: 
10073                 mono_inst_foreach (tree->inst_left, func, data);
10074                 break;
10075         case 2: 
10076                 mono_inst_foreach (tree->inst_left, func, data);
10077                 mono_inst_foreach (tree->inst_right, func, data);
10078                 break;
10079         default:
10080                 g_assert_not_reached ();
10081         }
10082         func (tree, data);
10083 }
10084
10085 G_GNUC_UNUSED
10086 static void
10087 mono_print_bb_code (MonoBasicBlock *bb)
10088 {
10089         MonoInst *c;
10090
10091         MONO_BB_FOR_EACH_INS (bb, c) {
10092                 mono_print_tree (c);
10093                 g_print ("\n");
10094         }
10095 }
10096
10097 static void
10098 print_dfn (MonoCompile *cfg) {
10099         int i, j;
10100         char *code;
10101         MonoBasicBlock *bb;
10102
10103         g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
10104
10105         for (i = 0; i < cfg->num_bblocks; ++i) {
10106                 MonoInst *c;
10107
10108                 bb = cfg->bblocks [i];
10109                 /*if (bb->cil_code) {
10110                         char* code1, *code2;
10111                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
10112                         if (bb->last_ins->cil_code)
10113                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
10114                         else
10115                                 code2 = g_strdup ("");
10116
10117                         code1 [strlen (code1) - 1] = 0;
10118                         code = g_strdup_printf ("%s -> %s", code1, code2);
10119                         g_free (code1);
10120                         g_free (code2);
10121                 } else*/
10122                         code = g_strdup ("\n");
10123                 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
10124                 MONO_BB_FOR_EACH_INS (bb, c) {
10125                         mono_print_tree (c);
10126                         g_print ("\n");
10127                 }
10128
10129                 g_print ("\tprev:");
10130                 for (j = 0; j < bb->in_count; ++j) {
10131                         g_print (" BB%d", bb->in_bb [j]->block_num);
10132                 }
10133                 g_print ("\t\tsucc:");
10134                 for (j = 0; j < bb->out_count; ++j) {
10135                         g_print (" BB%d", bb->out_bb [j]->block_num);
10136                 }
10137                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
10138
10139                 if (bb->idom)
10140                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
10141
10142                 if (bb->dominators)
10143                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
10144                 if (bb->dfrontier)
10145                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
10146                 g_free (code);
10147         }
10148
10149         g_print ("\n");
10150 }
10151
10152 void
10153 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
10154 {
10155         MONO_ADD_INS (bb, inst);
10156 }
10157
10158 void
10159 mono_destroy_compile (MonoCompile *cfg)
10160 {
10161         //mono_mempool_stats (cfg->mempool);
10162         mono_free_loop_info (cfg);
10163         if (cfg->rs)
10164                 mono_regstate_free (cfg->rs);
10165         if (cfg->spvars)
10166                 g_hash_table_destroy (cfg->spvars);
10167         if (cfg->exvars)
10168                 g_hash_table_destroy (cfg->exvars);
10169         mono_mempool_destroy (cfg->mempool);
10170         g_list_free (cfg->ldstr_list);
10171         g_hash_table_destroy (cfg->token_info_hash);
10172
10173         g_free (cfg->varinfo);
10174         g_free (cfg->vars);
10175         g_free (cfg->exception_message);
10176         g_free (cfg);
10177 }
10178
10179 #ifdef HAVE_KW_THREAD
10180 static __thread gpointer mono_lmf_addr MONO_TLS_FAST;
10181 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
10182 /* 
10183  * When this is defined, the current lmf is stored in this tls variable instead of in 
10184  * jit_tls->lmf.
10185  */
10186 static __thread gpointer mono_lmf MONO_TLS_FAST;
10187 #endif
10188 #endif
10189
10190 guint32
10191 mono_get_jit_tls_key (void)
10192 {
10193         return mono_jit_tls_id;
10194 }
10195
10196 gint32
10197 mono_get_jit_tls_offset (void)
10198 {
10199 #ifdef HAVE_KW_THREAD
10200         int offset;
10201         MONO_THREAD_VAR_OFFSET (mono_jit_tls, offset);
10202         return offset;
10203 #else
10204         return -1;
10205 #endif
10206 }
10207
10208 gint32
10209 mono_get_lmf_tls_offset (void)
10210 {
10211 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
10212         int offset;
10213         MONO_THREAD_VAR_OFFSET(mono_lmf,offset);
10214         return offset;
10215 #else
10216         return -1;
10217 #endif
10218 }
10219
10220 gint32
10221 mono_get_lmf_addr_tls_offset (void)
10222 {
10223         int offset;
10224         MONO_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
10225         return offset;
10226 }
10227
10228 MonoLMF *
10229 mono_get_lmf (void)
10230 {
10231 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
10232         return mono_lmf;
10233 #else
10234         MonoJitTlsData *jit_tls;
10235
10236         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
10237                 return jit_tls->lmf;
10238
10239         g_assert_not_reached ();
10240         return NULL;
10241 #endif
10242 }
10243
10244 MonoLMF **
10245 mono_get_lmf_addr (void)
10246 {
10247 #ifdef HAVE_KW_THREAD
10248         return mono_lmf_addr;
10249 #else
10250         MonoJitTlsData *jit_tls;
10251
10252         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
10253                 return &jit_tls->lmf;
10254
10255         g_assert_not_reached ();
10256         return NULL;
10257 #endif
10258 }
10259
10260 /* Called by native->managed wrappers */
10261 void
10262 mono_jit_thread_attach (MonoDomain *domain)
10263 {
10264 #ifdef HAVE_KW_THREAD
10265         if (!mono_lmf_addr) {
10266                 mono_thread_attach (domain);
10267         }
10268 #else
10269         if (!TlsGetValue (mono_jit_tls_id))
10270                 mono_thread_attach (domain);
10271 #endif
10272         if (mono_domain_get () != domain)
10273                 mono_domain_set (domain, TRUE);
10274 }       
10275
10276 /**
10277  * mono_thread_abort:
10278  * @obj: exception object
10279  *
10280  * abort the thread, print exception information and stack trace
10281  */
10282 static void
10283 mono_thread_abort (MonoObject *obj)
10284 {
10285         /* MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id); */
10286         
10287         /* handle_remove should be eventually called for this thread, too
10288         g_free (jit_tls);*/
10289
10290         if ((mono_runtime_unhandled_exception_policy_get () == MONO_UNHANLED_POLICY_LEGACY) ||
10291                         (obj->vtable->klass == mono_defaults.threadabortexception_class)) {
10292                 mono_thread_exit ();
10293         } else {
10294                 exit (mono_environment_exitcode_get ());
10295         }
10296 }
10297
10298 static void*
10299 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
10300 {
10301         MonoJitTlsData *jit_tls;
10302         MonoLMF *lmf;
10303
10304         jit_tls = TlsGetValue (mono_jit_tls_id);
10305         if (jit_tls)
10306                 return jit_tls;
10307
10308         jit_tls = g_new0 (MonoJitTlsData, 1);
10309
10310         TlsSetValue (mono_jit_tls_id, jit_tls);
10311
10312 #ifdef HAVE_KW_THREAD
10313         mono_jit_tls = jit_tls;
10314 #endif
10315
10316         jit_tls->abort_func = abort_func;
10317         jit_tls->end_of_stack = stack_start;
10318
10319         lmf = g_new0 (MonoLMF, 1);
10320 #ifdef MONO_ARCH_INIT_TOP_LMF_ENTRY
10321         MONO_ARCH_INIT_TOP_LMF_ENTRY (lmf);
10322 #else
10323         lmf->ebp = -1;
10324 #endif
10325
10326         jit_tls->first_lmf = lmf;
10327
10328 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
10329         /* jit_tls->lmf is unused */
10330         mono_lmf = lmf;
10331         mono_lmf_addr = &mono_lmf;
10332 #else
10333 #if defined(HAVE_KW_THREAD)
10334         mono_lmf_addr = &jit_tls->lmf;  
10335 #endif
10336
10337         jit_tls->lmf = lmf;
10338 #endif
10339
10340         mono_arch_setup_jit_tls_data (jit_tls);
10341         mono_setup_altstack (jit_tls);
10342
10343         return jit_tls;
10344 }
10345
10346 static void
10347 mono_thread_start_cb (gsize tid, gpointer stack_start, gpointer func)
10348 {
10349         MonoThread *thread;
10350         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
10351         thread = mono_thread_current ();
10352         mono_debugger_thread_created (tid, thread, jit_tls);
10353         if (thread)
10354                 thread->jit_data = jit_tls;
10355 }
10356
10357 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
10358
10359 static void
10360 mono_thread_abort_dummy (MonoObject *obj)
10361 {
10362   if (mono_thread_attach_aborted_cb)
10363     mono_thread_attach_aborted_cb (obj);
10364   else
10365     mono_thread_abort (obj);
10366 }
10367
10368 static void
10369 mono_thread_attach_cb (gsize tid, gpointer stack_start)
10370 {
10371         MonoThread *thread;
10372         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
10373         thread = mono_thread_current ();
10374         mono_debugger_thread_created (tid, thread, (MonoJitTlsData *) jit_tls);
10375         if (thread)
10376                 thread->jit_data = jit_tls;
10377         if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
10378                 setup_stat_profiler ();
10379 }
10380
10381 static void
10382 mini_thread_cleanup (MonoThread *thread)
10383 {
10384         MonoJitTlsData *jit_tls = thread->jit_data;
10385
10386         if (jit_tls) {
10387                 mono_debugger_thread_cleanup (jit_tls);
10388                 mono_arch_free_jit_tls_data (jit_tls);
10389
10390                 mono_free_altstack (jit_tls);
10391                 g_free (jit_tls->first_lmf);
10392                 g_free (jit_tls);
10393                 thread->jit_data = NULL;
10394                 TlsSetValue (mono_jit_tls_id, NULL);
10395         }
10396 }
10397
10398 static MonoInst*
10399 mono_create_tls_get (MonoCompile *cfg, int offset)
10400 {
10401 #ifdef MONO_ARCH_HAVE_TLS_GET
10402         MonoInst* ins;
10403         
10404         if (offset == -1)
10405                 return NULL;
10406         
10407         MONO_INST_NEW (cfg, ins, OP_TLS_GET);
10408         ins->dreg = mono_regstate_next_int (cfg->rs);
10409         ins->inst_offset = offset;
10410         return ins;
10411 #else
10412         return NULL;
10413 #endif
10414 }
10415
10416 MonoInst*
10417 mono_get_jit_tls_intrinsic (MonoCompile *cfg)
10418 {
10419         return mono_create_tls_get (cfg, mono_get_jit_tls_offset ());
10420 }
10421
10422 void
10423 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
10424 {
10425         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
10426
10427         ji->ip.i = ip;
10428         ji->type = type;
10429         ji->data.target = target;
10430         ji->next = cfg->patch_info;
10431
10432         cfg->patch_info = ji;
10433 }
10434
10435 MonoJumpInfo *
10436 mono_patch_info_list_prepend (MonoJumpInfo *list, int ip, MonoJumpInfoType type, gconstpointer target)
10437 {
10438         MonoJumpInfo *ji = g_new0 (MonoJumpInfo, 1);
10439
10440         ji->ip.i = ip;
10441         ji->type = type;
10442         ji->data.target = target;
10443         ji->next = list;
10444
10445         return ji;
10446 }
10447
10448 void
10449 mono_remove_patch_info (MonoCompile *cfg, int ip)
10450 {
10451         MonoJumpInfo **ji = &cfg->patch_info;
10452
10453         while (*ji) {
10454                 if ((*ji)->ip.i == ip)
10455                         *ji = (*ji)->next;
10456                 else
10457                         ji = &((*ji)->next);
10458         }
10459 }
10460
10461 /**
10462  * mono_patch_info_dup_mp:
10463  *
10464  * Make a copy of PATCH_INFO, allocating memory from the mempool MP.
10465  */
10466 MonoJumpInfo*
10467 mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info)
10468 {
10469         MonoJumpInfo *res = mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
10470         memcpy (res, patch_info, sizeof (MonoJumpInfo));
10471
10472         switch (patch_info->type) {
10473         case MONO_PATCH_INFO_RVA:
10474         case MONO_PATCH_INFO_LDSTR:
10475         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
10476         case MONO_PATCH_INFO_LDTOKEN:
10477         case MONO_PATCH_INFO_DECLSEC:
10478                 res->data.token = mono_mempool_alloc (mp, sizeof (MonoJumpInfoToken));
10479                 memcpy (res->data.token, patch_info->data.token, sizeof (MonoJumpInfoToken));
10480                 break;
10481         case MONO_PATCH_INFO_SWITCH:
10482                 res->data.table = mono_mempool_alloc (mp, sizeof (MonoJumpInfoBBTable));
10483                 memcpy (res->data.table, patch_info->data.table, sizeof (MonoJumpInfoBBTable));
10484                 break;
10485         default:
10486                 break;
10487         }
10488
10489         return res;
10490 }
10491
10492 guint
10493 mono_patch_info_hash (gconstpointer data)
10494 {
10495         const MonoJumpInfo *ji = (MonoJumpInfo*)data;
10496
10497         switch (ji->type) {
10498         case MONO_PATCH_INFO_RVA:
10499         case MONO_PATCH_INFO_LDSTR:
10500         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
10501         case MONO_PATCH_INFO_LDTOKEN:
10502         case MONO_PATCH_INFO_DECLSEC:
10503                 return (ji->type << 8) | ji->data.token->token;
10504         case MONO_PATCH_INFO_VTABLE:
10505         case MONO_PATCH_INFO_CLASS:
10506         case MONO_PATCH_INFO_IID:
10507         case MONO_PATCH_INFO_ADJUSTED_IID:
10508                 return (ji->type << 8) | (gssize)ji->data.klass;
10509         case MONO_PATCH_INFO_FIELD:
10510         case MONO_PATCH_INFO_SFLDA:
10511                 return (ji->type << 8) | (gssize)ji->data.field;
10512         case MONO_PATCH_INFO_METHODCONST:
10513         case MONO_PATCH_INFO_METHOD:
10514         case MONO_PATCH_INFO_METHOD_JUMP:
10515                 return (ji->type << 8) | (gssize)ji->data.method;
10516         case MONO_PATCH_INFO_IMAGE:
10517                 return (ji->type << 8) | (gssize)ji->data.image;                
10518         default:
10519                 return (ji->type << 8);
10520         }
10521 }
10522
10523 /* 
10524  * mono_patch_info_equal:
10525  * 
10526  * This might fail to recognize equivalent patches, i.e. floats, so its only
10527  * usable in those cases where this is not a problem, i.e. sharing GOT slots
10528  * in AOT.
10529  */
10530 gint
10531 mono_patch_info_equal (gconstpointer ka, gconstpointer kb)
10532 {
10533         const MonoJumpInfo *ji1 = (MonoJumpInfo*)ka;
10534         const MonoJumpInfo *ji2 = (MonoJumpInfo*)kb;
10535
10536         if (ji1->type != ji2->type)
10537                 return 0;
10538
10539         switch (ji1->type) {
10540         case MONO_PATCH_INFO_RVA:
10541         case MONO_PATCH_INFO_LDSTR:
10542         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
10543         case MONO_PATCH_INFO_LDTOKEN:
10544         case MONO_PATCH_INFO_DECLSEC:
10545                 if ((ji1->data.token->image != ji2->data.token->image) ||
10546                         (ji1->data.token->token != ji2->data.token->token))
10547                         return 0;
10548                 break;
10549         default:
10550                 if (ji1->data.name != ji2->data.name)
10551                         return 0;
10552                 break;
10553         }
10554
10555         return 1;
10556 }
10557
10558 gpointer
10559 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
10560 {
10561         unsigned char *ip = patch_info->ip.i + code;
10562         gconstpointer target = NULL;
10563
10564         switch (patch_info->type) {
10565         case MONO_PATCH_INFO_BB:
10566                 target = patch_info->data.bb->native_offset + code;
10567                 break;
10568         case MONO_PATCH_INFO_ABS:
10569                 target = patch_info->data.target;
10570                 break;
10571         case MONO_PATCH_INFO_LABEL:
10572                 target = patch_info->data.inst->inst_c0 + code;
10573                 break;
10574         case MONO_PATCH_INFO_IP:
10575                 target = ip;
10576                 break;
10577         case MONO_PATCH_INFO_METHOD_REL:
10578                 target = code + patch_info->data.offset;
10579                 break;
10580         case MONO_PATCH_INFO_INTERNAL_METHOD: {
10581                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
10582                 if (!mi) {
10583                         g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
10584                         g_assert_not_reached ();
10585                 }
10586                 target = mono_icall_get_wrapper (mi);
10587                 break;
10588         }
10589         case MONO_PATCH_INFO_METHOD_JUMP: {
10590                 GSList *list;
10591
10592                 /* get the trampoline to the method from the domain */
10593                 target = mono_create_jump_trampoline (domain, patch_info->data.method, TRUE);
10594                 if (!domain->jump_target_hash)
10595                         domain->jump_target_hash = g_hash_table_new (NULL, NULL);
10596                 list = g_hash_table_lookup (domain->jump_target_hash, patch_info->data.method);
10597                 list = g_slist_prepend (list, ip);
10598                 g_hash_table_insert (domain->jump_target_hash, patch_info->data.method, list);
10599                 break;
10600         }
10601         case MONO_PATCH_INFO_METHOD:
10602                 if (patch_info->data.method == method) {
10603                         target = code;
10604                 } else {
10605                         /* get the trampoline to the method from the domain */
10606                         if (method && method->wrapper_type == MONO_WRAPPER_STATIC_RGCTX_INVOKE) {
10607                                 target = mono_create_jit_trampoline_in_domain (mono_domain_get (),
10608                                         patch_info->data.method, FALSE);
10609                         } else {
10610                                 target = mono_create_jit_trampoline (patch_info->data.method);
10611                         }
10612                 }
10613                 break;
10614         case MONO_PATCH_INFO_SWITCH: {
10615                 gpointer *jump_table;
10616                 int i;
10617
10618                 if (method && method->dynamic) {
10619                         jump_table = mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
10620                 } else {
10621                         mono_domain_lock (domain);
10622                         if (mono_aot_only)
10623                                 jump_table = mono_mempool_alloc (domain->mp, sizeof (gpointer) * patch_info->data.table->table_size);
10624                         else
10625                                 jump_table = mono_code_manager_reserve (domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
10626                         mono_domain_unlock (domain);
10627                 }
10628
10629                 for (i = 0; i < patch_info->data.table->table_size; i++) {
10630                         jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
10631                 }
10632                 target = jump_table;
10633                 break;
10634         }
10635         case MONO_PATCH_INFO_METHODCONST:
10636         case MONO_PATCH_INFO_CLASS:
10637         case MONO_PATCH_INFO_IMAGE:
10638         case MONO_PATCH_INFO_FIELD:
10639                 target = patch_info->data.target;
10640                 break;
10641         case MONO_PATCH_INFO_IID:
10642                 mono_class_init (patch_info->data.klass);
10643                 target = GINT_TO_POINTER ((int)patch_info->data.klass->interface_id);
10644                 break;
10645         case MONO_PATCH_INFO_ADJUSTED_IID:
10646                 mono_class_init (patch_info->data.klass);
10647                 target = GINT_TO_POINTER ((int)(-((patch_info->data.klass->interface_id + 1) * SIZEOF_VOID_P)));
10648                 break;
10649         case MONO_PATCH_INFO_VTABLE:
10650                 target = mono_class_vtable (domain, patch_info->data.klass);
10651                 g_assert (target);
10652                 break;
10653         case MONO_PATCH_INFO_CLASS_INIT: {
10654                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.klass);
10655
10656                 g_assert (vtable);
10657                 target = mono_create_class_init_trampoline (vtable);
10658                 break;
10659         }
10660         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
10661                 target = mono_create_delegate_trampoline (patch_info->data.klass);
10662                 break;
10663         case MONO_PATCH_INFO_SFLDA: {
10664                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
10665
10666                 g_assert (vtable);
10667                 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && (method && mono_class_needs_cctor_run (vtable->klass, method)))
10668                         /* Done by the generated code */
10669                         ;
10670                 else {
10671                         if (run_cctors)
10672                                 mono_runtime_class_init (vtable);
10673                 }
10674                 target = (char*)vtable->data + patch_info->data.field->offset;
10675                 break;
10676         }
10677         case MONO_PATCH_INFO_RVA:
10678                 target = mono_image_rva_map (patch_info->data.token->image, patch_info->data.token->token);
10679                 break;
10680         case MONO_PATCH_INFO_R4:
10681         case MONO_PATCH_INFO_R8:
10682                 target = patch_info->data.target;
10683                 break;
10684         case MONO_PATCH_INFO_EXC_NAME:
10685                 target = patch_info->data.name;
10686                 break;
10687         case MONO_PATCH_INFO_LDSTR:
10688                 target =
10689                         mono_ldstr (domain, patch_info->data.token->image, 
10690                                                 mono_metadata_token_index (patch_info->data.token->token));
10691                 break;
10692         case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
10693                 gpointer handle;
10694                 MonoClass *handle_class;
10695
10696                 handle = mono_ldtoken (patch_info->data.token->image, 
10697                                        patch_info->data.token->token, &handle_class, NULL);
10698                 mono_class_init (handle_class);
10699                 mono_class_init (mono_class_from_mono_type (handle));
10700
10701                 target =
10702                         mono_type_get_object (domain, handle);
10703                 break;
10704         }
10705         case MONO_PATCH_INFO_LDTOKEN: {
10706                 gpointer handle;
10707                 MonoClass *handle_class;
10708                 
10709                 handle = mono_ldtoken (patch_info->data.token->image,
10710                                        patch_info->data.token->token, &handle_class, NULL);
10711                 mono_class_init (handle_class);
10712                 
10713                 target = handle;
10714                 break;
10715         }
10716         case MONO_PATCH_INFO_DECLSEC:
10717                 target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
10718                 break;
10719         case MONO_PATCH_INFO_ICALL_ADDR:
10720                 target = mono_lookup_internal_call (patch_info->data.method);
10721                 break;
10722         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
10723                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
10724                 if (!mi) {
10725                         g_warning ("unknown MONO_PATCH_INFO_JIT_ICALL_ADDR %s", patch_info->data.name);
10726                         g_assert_not_reached ();
10727                 }
10728                 target = mi->func;
10729                 break;
10730         }
10731         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
10732                 target = mono_thread_interruption_request_flag ();
10733                 break;
10734         case MONO_PATCH_INFO_BB_OVF:
10735         case MONO_PATCH_INFO_EXC_OVF:
10736         case MONO_PATCH_INFO_GOT_OFFSET:
10737         case MONO_PATCH_INFO_NONE:
10738                 break;
10739         default:
10740                 g_assert_not_reached ();
10741         }
10742
10743         return (gpointer)target;
10744 }
10745
10746 static void
10747 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
10748         MonoJitICallInfo *info;
10749
10750         decompose_foreach (tree, cfg);
10751
10752         switch (mono_burg_arity [tree->opcode]) {
10753         case 0: break;
10754         case 1: 
10755                 dec_foreach (tree->inst_left, cfg);
10756
10757                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
10758                         MonoInst *iargs [2];
10759                 
10760                         iargs [0] = tree->inst_left;
10761
10762                         mono_emulate_opcode (cfg, tree, iargs, info);
10763                         return;
10764                 }
10765
10766                 break;
10767         case 2:
10768 #ifdef MONO_ARCH_BIGMUL_INTRINS
10769                 if (tree->opcode == OP_LMUL
10770                                 && (cfg->opt & MONO_OPT_INTRINS)
10771                                 && (tree->inst_left->opcode == CEE_CONV_I8 
10772                                         || tree->inst_left->opcode == CEE_CONV_U8)
10773                                 && tree->inst_left->inst_left->type == STACK_I4
10774                                 && (tree->inst_right->opcode == CEE_CONV_I8 
10775                                         || tree->inst_right->opcode == CEE_CONV_U8)
10776                                 && tree->inst_right->inst_left->type == STACK_I4
10777                                 && tree->inst_left->opcode == tree->inst_right->opcode) {
10778                         tree->opcode = (tree->inst_left->opcode == CEE_CONV_I8 ? OP_BIGMUL: OP_BIGMUL_UN);
10779                         tree->inst_left = tree->inst_left->inst_left;
10780                         tree->inst_right = tree->inst_right->inst_left;
10781                         dec_foreach (tree, cfg);
10782                 } else 
10783 #endif
10784                         if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
10785                         MonoInst *iargs [2];
10786                 
10787                         iargs [0] = tree->inst_i0;
10788                         iargs [1] = tree->inst_i1;
10789                 
10790                         mono_emulate_opcode (cfg, tree, iargs, info);
10791
10792                         dec_foreach (iargs [0], cfg);
10793                         dec_foreach (iargs [1], cfg);
10794                         return;
10795                 } else {
10796                         dec_foreach (tree->inst_left, cfg);
10797                         dec_foreach (tree->inst_right, cfg);
10798                 }
10799                 break;
10800         default:
10801                 g_assert_not_reached ();
10802         }
10803 }
10804
10805 static void
10806 decompose_pass (MonoCompile *cfg) {
10807         MonoBasicBlock *bb;
10808
10809         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10810                 MonoInst *tree;
10811                 cfg->cbb = bb;
10812                 cfg->prev_ins = NULL;
10813                 MONO_BB_FOR_EACH_INS (cfg->cbb, tree) {
10814                         dec_foreach (tree, cfg);
10815                         cfg->prev_ins = tree;
10816                 }
10817         }
10818 }
10819
10820 static void
10821 nullify_basic_block (MonoBasicBlock *bb) 
10822 {
10823         bb->in_count = 0;
10824         bb->out_count = 0;
10825         bb->in_bb = NULL;
10826         bb->out_bb = NULL;
10827         bb->next_bb = NULL;
10828         MONO_INST_LIST_INIT (&bb->ins_list);
10829         bb->cil_code = NULL;
10830 }
10831
10832 static void 
10833 replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
10834 {
10835         int i;
10836
10837         for (i = 0; i < bb->out_count; i++) {
10838                 MonoBasicBlock *ob = bb->out_bb [i];
10839                 if (ob == orig) {
10840                         if (!repl) {
10841                                 if (bb->out_count > 1) {
10842                                         bb->out_bb [i] = bb->out_bb [bb->out_count - 1];
10843                                 }
10844                                 bb->out_count--;
10845                         } else {
10846                                 bb->out_bb [i] = repl;
10847                         }
10848                 }
10849         }
10850 }
10851
10852 static void 
10853 replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
10854 {
10855         int i;
10856
10857         for (i = 0; i < bb->in_count; i++) {
10858                 MonoBasicBlock *ib = bb->in_bb [i];
10859                 if (ib == orig) {
10860                         if (!repl) {
10861                                 if (bb->in_count > 1) {
10862                                         bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
10863                                 }
10864                                 bb->in_count--;
10865                         } else {
10866                                 bb->in_bb [i] = repl;
10867                         }
10868                 }
10869         }
10870 }
10871
10872 static void
10873 replace_out_block_in_code (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl) {
10874         MonoInst *inst;
10875         
10876         MONO_BB_FOR_EACH_INS (bb, inst) {
10877                 if (inst->opcode == OP_CALL_HANDLER) {
10878                         if (inst->inst_target_bb == orig)
10879                                 inst->inst_target_bb = repl;
10880                 }
10881         }
10882
10883         inst = mono_inst_list_last (&bb->ins_list);
10884         if (!inst)
10885                 return;
10886
10887         switch (inst->opcode) {
10888         case OP_BR:
10889                 if (inst->inst_target_bb == orig)
10890                         inst->inst_target_bb = repl;
10891                 break;
10892         case OP_SWITCH: {
10893                 int i;
10894                 int n = GPOINTER_TO_INT (inst->klass);
10895                 for (i = 0; i < n; i++ ) {
10896                         if (inst->inst_many_bb [i] == orig)
10897                                 inst->inst_many_bb [i] = repl;
10898                 }
10899                 break;
10900         }
10901         case CEE_BNE_UN:
10902         case CEE_BEQ:
10903         case CEE_BLT:
10904         case CEE_BLT_UN:
10905         case CEE_BGT:
10906         case CEE_BGT_UN:
10907         case CEE_BGE:
10908         case CEE_BGE_UN:
10909         case CEE_BLE:
10910         case CEE_BLE_UN:
10911                 if (inst->inst_true_bb == orig)
10912                         inst->inst_true_bb = repl;
10913                 if (inst->inst_false_bb == orig)
10914                         inst->inst_false_bb = repl;
10915                 break;
10916         default:
10917                 break;
10918         }
10919 }
10920
10921 static void 
10922 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
10923 {
10924         int i, j;
10925
10926         for (i = 0; i < bb->out_count; i++) {
10927                 MonoBasicBlock *ob = bb->out_bb [i];
10928                 for (j = 0; j < ob->in_count; j++) {
10929                         if (ob->in_bb [j] == orig) {
10930                                 ob->in_bb [j] = repl;
10931                         }
10932                 }
10933         }
10934
10935 }
10936
10937 /**
10938   * Check if a bb is useless (is just made of NOPs and ends with an
10939   * unconditional branch, or nothing).
10940   * If it is so, unlink it from the CFG and nullify it, and return TRUE.
10941   * Otherwise, return FALSE;
10942   */
10943 static gboolean
10944 remove_block_if_useless (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *previous_bb) {
10945         MonoBasicBlock *target_bb = NULL;
10946         MonoInst *inst;
10947         
10948         /* Do not touch handlers */
10949         if (bb->region != -1) {
10950                 bb->not_useless = TRUE;
10951                 return FALSE;
10952         }
10953         
10954         MONO_BB_FOR_EACH_INS (bb, inst) {
10955                 switch (inst->opcode) {
10956                 case OP_NOP:
10957                         break;
10958                 case OP_BR:
10959                         target_bb = inst->inst_target_bb;
10960                         break;
10961                 default:
10962                         bb->not_useless = TRUE;
10963                         return FALSE;
10964                 }
10965         }
10966         
10967         if (target_bb == NULL) {
10968                 if ((bb->out_count == 1) && (bb->out_bb [0] == bb->next_bb)) {
10969                         target_bb = bb->next_bb;
10970                 } else {
10971                         /* Do not touch empty BBs that do not "fall through" to their next BB (like the exit BB) */
10972                         return FALSE;
10973                 }
10974         }
10975         
10976         /* Do not touch BBs following a switch (they are the "default" branch) */
10977         inst = mono_inst_list_last (&previous_bb->ins_list);
10978         if (inst && inst->opcode == OP_SWITCH)
10979                 return FALSE;
10980         
10981         /* Do not touch BBs following the entry BB and jumping to something that is not */
10982         /* thiry "next" bb (the entry BB cannot contain the branch) */
10983         if ((previous_bb == cfg->bb_entry) && (bb->next_bb != target_bb)) {
10984                 return FALSE;
10985         }
10986
10987         /* 
10988          * Do not touch BBs following a try block as the code in 
10989          * mini_method_compile needs them to compute the length of the try block.
10990          */
10991         if (MONO_BBLOCK_IS_IN_REGION (previous_bb, MONO_REGION_TRY))
10992                 return FALSE;
10993         
10994         /* Check that there is a target BB, and that bb is not an empty loop (Bug 75061) */
10995         if ((target_bb != NULL) && (target_bb != bb)) {
10996                 MonoInst *last_ins;
10997                 int i;
10998
10999                 if (cfg->verbose_level > 1) {
11000                         printf ("remove_block_if_useless, removed BB%d\n", bb->block_num);
11001                 }
11002                 
11003                 /* unlink_bblock () modifies the bb->in_bb array so can't use a for loop here */
11004                 while (bb->in_count) {
11005                         MonoBasicBlock *in_bb = bb->in_bb [0];
11006                         mono_unlink_bblock (cfg, in_bb, bb);
11007                         link_bblock (cfg, in_bb, target_bb);
11008                         replace_out_block_in_code (in_bb, bb, target_bb);
11009                 }
11010                 
11011                 mono_unlink_bblock (cfg, bb, target_bb);
11012                 
11013                 last_ins = mono_inst_list_last (&previous_bb->ins_list);
11014
11015                 if ((previous_bb != cfg->bb_entry) &&
11016                                 (previous_bb->region == bb->region) &&
11017                                 ((last_ins == NULL) ||
11018                                 ((last_ins->opcode != OP_BR) &&
11019                                 (!(MONO_IS_COND_BRANCH_OP (last_ins))) &&
11020                                 (last_ins->opcode != OP_SWITCH)))) {
11021                         for (i = 0; i < previous_bb->out_count; i++) {
11022                                 if (previous_bb->out_bb [i] == target_bb) {
11023                                         MonoInst *jump;
11024                                         MONO_INST_NEW (cfg, jump, OP_BR);
11025                                         MONO_ADD_INS (previous_bb, jump);
11026                                         jump->cil_code = previous_bb->cil_code;
11027                                         jump->inst_target_bb = target_bb;
11028                                         break;
11029                                 }
11030                         }
11031                 }
11032                 
11033                 previous_bb->next_bb = bb->next_bb;
11034                 nullify_basic_block (bb);
11035                 
11036                 return TRUE;
11037         } else {
11038                 return FALSE;
11039         }
11040 }
11041
11042 static void
11043 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn) 
11044 {
11045         MonoInst *last_ins;
11046
11047         bb->out_count = bbn->out_count;
11048         bb->out_bb = bbn->out_bb;
11049
11050         replace_basic_block (bb, bbn, bb);
11051
11052         last_ins = mono_inst_list_last (&bb->ins_list);
11053
11054         /* Nullify branch at the end of bb */
11055         if (last_ins && MONO_IS_BRANCH_OP (last_ins))
11056                 last_ins->opcode = OP_NOP;
11057
11058         MONO_INST_LIST_SPLICE_TAIL_INIT (&bbn->ins_list, &bb->ins_list);
11059
11060         bb->next_bb = bbn->next_bb;
11061         nullify_basic_block (bbn);
11062 }
11063
11064 static void
11065 move_basic_block_to_end (MonoCompile *cfg, MonoBasicBlock *bb)
11066 {
11067         MonoBasicBlock *bbn, *next;
11068         MonoInst *last_ins;
11069
11070         next = bb->next_bb;
11071
11072         /* Find the previous */
11073         for (bbn = cfg->bb_entry; bbn->next_bb && bbn->next_bb != bb; bbn = bbn->next_bb)
11074                 ;
11075         if (bbn->next_bb) {
11076                 bbn->next_bb = bb->next_bb;
11077         }
11078
11079         /* Find the last */
11080         for (bbn = cfg->bb_entry; bbn->next_bb; bbn = bbn->next_bb)
11081                 ;
11082         bbn->next_bb = bb;
11083         bb->next_bb = NULL;
11084
11085         last_ins = mono_inst_list_last (&bb->ins_list);
11086
11087         /* Add a branch */
11088         if (next && (!last_ins || (last_ins->opcode != OP_NOT_REACHED))) {
11089                 MonoInst *ins;
11090
11091                 MONO_INST_NEW (cfg, ins, OP_BR);
11092                 MONO_ADD_INS (bb, ins);
11093                 link_bblock (cfg, bb, next);
11094                 ins->inst_target_bb = next;
11095         }               
11096 }
11097
11098 /* checks that a and b represent the same instructions, conservatively,
11099  * it can return FALSE also for two trees that are equal.
11100  * FIXME: also make sure there are no side effects.
11101  */
11102 static int
11103 same_trees (MonoInst *a, MonoInst *b)
11104 {
11105         int arity;
11106         if (a->opcode != b->opcode)
11107                 return FALSE;
11108         arity = mono_burg_arity [a->opcode];
11109         if (arity == 1) {
11110                 if (a->ssa_op == b->ssa_op && a->ssa_op == MONO_SSA_LOAD && a->inst_i0 == b->inst_i0)
11111                         return TRUE;
11112                 return same_trees (a->inst_left, b->inst_left);
11113         } else if (arity == 2) {
11114                 return same_trees (a->inst_left, b->inst_left) && same_trees (a->inst_right, b->inst_right);
11115         } else if (arity == 0) {
11116                 switch (a->opcode) {
11117                 case OP_ICONST:
11118                         return a->inst_c0 == b->inst_c0;
11119                 default:
11120                         return FALSE;
11121                 }
11122         }
11123         return FALSE;
11124 }
11125
11126 static int
11127 get_unsigned_condbranch (int opcode)
11128 {
11129         switch (opcode) {
11130         case CEE_BLE: return CEE_BLE_UN;
11131         case CEE_BLT: return CEE_BLT_UN;
11132         case CEE_BGE: return CEE_BGE_UN;
11133         case CEE_BGT: return CEE_BGT_UN;
11134         }
11135         g_assert_not_reached ();
11136         return 0;
11137 }
11138
11139 static int
11140 tree_is_unsigned (MonoInst* ins) {
11141         switch (ins->opcode) {
11142         case OP_ICONST:
11143                 return (int)ins->inst_c0 >= 0;
11144         /* array lengths are positive as are string sizes */
11145         case CEE_LDLEN:
11146         case OP_STRLEN:
11147                 return TRUE;
11148         case CEE_CONV_U1:
11149         case CEE_CONV_U2:
11150         case CEE_CONV_U4:
11151         case CEE_CONV_OVF_U1:
11152         case CEE_CONV_OVF_U2:
11153         case CEE_CONV_OVF_U4:
11154                 return TRUE;
11155         case CEE_LDIND_U1:
11156         case CEE_LDIND_U2:
11157         case CEE_LDIND_U4:
11158                 return TRUE;
11159         default:
11160                 return FALSE;
11161         }
11162 }
11163
11164 /* check if an unsigned compare can be used instead of two signed compares
11165  * for (val < 0 || val > limit) conditionals.
11166  * Returns TRUE if the optimization has been applied.
11167  * Note that this can't be applied if the second arg is not positive...
11168  */
11169 static int
11170 try_unsigned_compare (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *bb_last)
11171 {
11172         MonoBasicBlock *truet, *falset;
11173         MonoInst *cmp_inst = bb_last->inst_left;
11174         MonoInst *condb;
11175         if (!cmp_inst->inst_right->inst_c0 == 0)
11176                 return FALSE;
11177         truet = bb_last->inst_true_bb;
11178         falset = bb_last->inst_false_bb;
11179         if (falset->in_count != 1)
11180                 return FALSE;
11181         condb = mono_inst_list_last (&falset->ins_list);
11182         /* target bb must have one instruction */
11183         if (!condb || (condb->node.next != &falset->ins_list))
11184                 return FALSE;
11185         if ((((condb->opcode == CEE_BLE || condb->opcode == CEE_BLT) && (condb->inst_false_bb == truet))
11186                         || ((condb->opcode == CEE_BGE || condb->opcode == CEE_BGT) && (condb->inst_true_bb == truet)))
11187                         && same_trees (cmp_inst->inst_left, condb->inst_left->inst_left)) {
11188                 if (!tree_is_unsigned (condb->inst_left->inst_right))
11189                         return FALSE;
11190                 condb->opcode = get_unsigned_condbranch (condb->opcode);
11191                 /* change the original condbranch to just point to the new unsigned check */
11192                 bb_last->opcode = OP_BR;
11193                 bb_last->inst_target_bb = falset;
11194                 replace_out_block (bb, truet, NULL);
11195                 replace_in_block (truet, bb, NULL);
11196                 return TRUE;
11197         }
11198         return FALSE;
11199 }
11200
11201 /*
11202  * Optimizes the branches on the Control Flow Graph
11203  *
11204  */
11205 static void
11206 optimize_branches (MonoCompile *cfg)
11207 {
11208         int i, changed = FALSE;
11209         MonoBasicBlock *bb, *bbn;
11210         guint32 niterations;
11211
11212         /*
11213          * Some crazy loops could cause the code below to go into an infinite
11214          * loop, see bug #53003 for an example. To prevent this, we put an upper
11215          * bound on the number of iterations.
11216          */
11217         if (cfg->num_bblocks > 1000)
11218                 niterations = cfg->num_bblocks * 2;
11219         else
11220                 niterations = 1000;
11221
11222         do {
11223                 MonoBasicBlock *previous_bb;
11224                 changed = FALSE;
11225                 niterations --;
11226
11227                 /* we skip the entry block (exit is handled specially instead ) */
11228                 for (previous_bb = cfg->bb_entry, bb = cfg->bb_entry->next_bb; bb; previous_bb = bb, bb = bb->next_bb) {
11229                         MonoInst *last_ins;
11230
11231                         /* dont touch code inside exception clauses */
11232                         if (bb->region != -1)
11233                                 continue;
11234
11235                         if (!bb->not_useless && remove_block_if_useless (cfg, bb, previous_bb)) {
11236                                 changed = TRUE;
11237                                 continue;
11238                         }
11239
11240                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
11241                                 if (cfg->verbose_level > 2)
11242                                         g_print ("nullify block triggered %d\n", bbn->block_num);
11243
11244                                 bb->next_bb = bbn->next_bb;
11245
11246                                 for (i = 0; i < bbn->out_count; i++)
11247                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
11248
11249                                 nullify_basic_block (bbn);                      
11250                                 changed = TRUE;
11251                         }
11252
11253                         last_ins = mono_inst_list_last (&bb->ins_list);
11254                         if (bb->out_count == 1) {
11255                                 bbn = bb->out_bb [0];
11256
11257                                 /* conditional branches where true and false targets are the same can be also replaced with OP_BR */
11258                                 if (last_ins && MONO_IS_COND_BRANCH_OP (last_ins)) {
11259                                         MonoInst *pop;
11260                                         MONO_INST_NEW (cfg, pop, CEE_POP);
11261                                         pop->inst_left = last_ins->inst_left->inst_left;
11262                                         mono_add_ins_to_end (bb, pop);
11263                                         MONO_INST_NEW (cfg, pop, CEE_POP);
11264                                         pop->inst_left = last_ins->inst_left->inst_right;
11265                                         mono_add_ins_to_end (bb, pop);
11266                                         last_ins->opcode = OP_BR;
11267                                         last_ins->inst_target_bb = last_ins->inst_true_bb;
11268                                         changed = TRUE;
11269                                         if (cfg->verbose_level > 2)
11270                                                 g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count);
11271                                 }
11272
11273                                 if (bb->region == bbn->region && bb->next_bb == bbn) {
11274                                         /* the block are in sequence anyway ... */
11275
11276                                         /* branches to the following block can be removed */
11277                                         if (last_ins && last_ins->opcode == OP_BR) {
11278                                                 last_ins->opcode = OP_NOP;
11279                                                 changed = TRUE;
11280                                                 if (cfg->verbose_level > 2)
11281                                                         g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
11282                                         }
11283
11284                                         if (bbn->in_count == 1) {
11285
11286                                                 if (bbn != cfg->bb_exit) {
11287                                                         if (cfg->verbose_level > 2)
11288                                                                 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
11289                                                         merge_basic_blocks (bb, bbn);
11290                                                         changed = TRUE;
11291                                                         continue;
11292                                                 }
11293
11294                                                 //mono_print_bb_code (bb);
11295                                         }
11296                                 }
11297                         }
11298                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
11299                                 if (cfg->verbose_level > 2) {
11300                                         g_print ("nullify block triggered %d\n", bbn->block_num);
11301                                 }
11302                                 bb->next_bb = bbn->next_bb;
11303
11304                                 for (i = 0; i < bbn->out_count; i++)
11305                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
11306
11307                                 nullify_basic_block (bbn);                      
11308                                 changed = TRUE;
11309                                 continue;
11310                         }
11311
11312                         if (bb->out_count == 1) {
11313                                 bbn = bb->out_bb [0];
11314
11315                                 if (last_ins && last_ins->opcode == OP_BR) {
11316                                         MonoInst *bbn_code;
11317
11318                                         bbn = last_ins->inst_target_bb;
11319                                         bbn_code = mono_inst_list_first (&bbn->ins_list);
11320                                         if (bb->region == bbn->region && bbn_code &&
11321                                                         bbn_code->opcode == OP_BR &&
11322                                                         bbn_code->inst_target_bb->region == bb->region) {
11323                                                 if (cfg->verbose_level > 2)
11324                                                         g_print ("in %s branch to branch triggered %d -> %d -> %d\n", cfg->method->name, 
11325                                                                  bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num);
11326
11327                                                 replace_in_block (bbn, bb, NULL);
11328                                                 replace_out_block (bb, bbn, bbn_code->inst_target_bb);
11329                                                 link_bblock (cfg, bb, bbn_code->inst_target_bb);
11330                                                 last_ins->inst_target_bb = bbn_code->inst_target_bb;
11331                                                 changed = TRUE;
11332                                                 continue;
11333                                         }
11334                                 }
11335                         } else if (bb->out_count == 2) {
11336                                 if (last_ins && MONO_IS_COND_BRANCH_NOFP (last_ins)) {
11337                                         int branch_result = mono_eval_cond_branch (last_ins);
11338                                         MonoBasicBlock *taken_branch_target = NULL, *untaken_branch_target = NULL;
11339                                         MonoInst *bbn_code;
11340
11341                                         if (branch_result == BRANCH_TAKEN) {
11342                                                 taken_branch_target = last_ins->inst_true_bb;
11343                                                 untaken_branch_target = last_ins->inst_false_bb;
11344                                         } else if (branch_result == BRANCH_NOT_TAKEN) {
11345                                                 taken_branch_target = last_ins->inst_false_bb;
11346                                                 untaken_branch_target = last_ins->inst_true_bb;
11347                                         }
11348                                         if (taken_branch_target) {
11349                                                 /* if mono_eval_cond_branch () is ever taken to handle 
11350                                                  * non-constant values to compare, issue a pop here.
11351                                                  */
11352                                                 last_ins->opcode = OP_BR;
11353                                                 last_ins->inst_target_bb = taken_branch_target;
11354                                                 mono_unlink_bblock (cfg, bb, untaken_branch_target);
11355                                                 changed = TRUE;
11356                                                 continue;
11357                                         }
11358                                         bbn = last_ins->inst_true_bb;
11359                                         bbn_code = mono_inst_list_first (&bbn->ins_list);
11360                                         if (bb->region == bbn->region && bbn_code && bbn_code->opcode == OP_BR &&
11361                                                         bbn_code->inst_target_bb->region == bb->region) {
11362                                                 if (cfg->verbose_level > 2)             
11363                                                         g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n", 
11364                                                                  bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num, 
11365                                                                  bbn_code->opcode);
11366
11367                                                 /* 
11368                                                  * Unlink, then relink bblocks to avoid various
11369                                                  * tricky situations when the two targets of the branch
11370                                                  * are equal, or will become equal after the change.
11371                                                  */
11372                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_true_bb);
11373                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_false_bb);
11374
11375                                                 last_ins->inst_true_bb = bbn_code->inst_target_bb;
11376
11377                                                 link_bblock (cfg, bb, last_ins->inst_true_bb);
11378                                                 link_bblock (cfg, bb, last_ins->inst_false_bb);
11379
11380                                                 changed = TRUE;
11381                                                 continue;
11382                                         }
11383
11384                                         bbn = last_ins->inst_false_bb;
11385                                         bbn_code = mono_inst_list_first (&bbn->ins_list);
11386                                         if (bb->region == bbn->region && bbn_code && bbn_code->opcode == OP_BR &&
11387                                                         bbn_code->inst_target_bb->region == bb->region) {
11388                                                 if (cfg->verbose_level > 2)
11389                                                         g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n", 
11390                                                                  bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num, 
11391                                                                  bbn_code->opcode);
11392
11393                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_true_bb);
11394                                                 mono_unlink_bblock (cfg, bb, last_ins->inst_false_bb);
11395
11396                                                 last_ins->inst_false_bb = bbn_code->inst_target_bb;
11397
11398                                                 link_bblock (cfg, bb, last_ins->inst_true_bb);
11399                                                 link_bblock (cfg, bb, last_ins->inst_false_bb);
11400
11401                                                 changed = TRUE;
11402                                                 continue;
11403                                         }
11404                                 }
11405
11406                                 /* detect and optimize to unsigned compares checks like: if (v < 0 || v > limit */
11407                                 if (last_ins && last_ins->opcode == CEE_BLT && last_ins->inst_left->inst_right->opcode == OP_ICONST) {
11408                                         if (try_unsigned_compare (cfg, bb, last_ins)) {
11409                                                 /*g_print ("applied in bb %d (->%d) %s\n", bb->block_num, last_ins->inst_target_bb->block_num, mono_method_full_name (cfg->method, TRUE));*/
11410                                                 changed = TRUE;
11411                                                 continue;
11412                                         }
11413                                 }
11414
11415                                 if (last_ins && MONO_IS_COND_BRANCH_NOFP (last_ins)) {
11416                                         if (last_ins->inst_false_bb->out_of_line && (bb->region == last_ins->inst_false_bb->region)) {
11417                                                 /* Reverse the branch */
11418                                                 last_ins->opcode = reverse_branch_op (last_ins->opcode);
11419                                                 bbn = last_ins->inst_false_bb;
11420                                                 last_ins->inst_false_bb = last_ins->inst_true_bb;
11421                                                 last_ins->inst_true_bb = bbn;
11422
11423                                                 move_basic_block_to_end (cfg, last_ins->inst_true_bb);
11424                                                 if (cfg->verbose_level > 2)
11425                                                         g_print ("cbranch to throw block triggered %d.\n", 
11426                                                                          bb->block_num);
11427                                         }
11428                                 }
11429                         }
11430                 }
11431         } while (changed && (niterations > 0));
11432
11433 }
11434
11435 static void
11436 mono_compile_create_vars (MonoCompile *cfg)
11437 {
11438         MonoMethodSignature *sig;
11439         MonoMethodHeader *header;
11440         int i;
11441
11442         header = mono_method_get_header (cfg->method);
11443
11444         sig = mono_method_signature (cfg->method);
11445         
11446         if (!MONO_TYPE_IS_VOID (sig->ret)) {
11447                 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
11448                 cfg->ret->opcode = OP_RETARG;
11449                 cfg->ret->inst_vtype = sig->ret;
11450                 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
11451         }
11452         if (cfg->verbose_level > 2)
11453                 g_print ("creating vars\n");
11454
11455         cfg->args = mono_mempool_alloc0 (cfg->mempool, (sig->param_count + sig->hasthis) * sizeof (MonoInst*));
11456
11457         if (sig->hasthis)
11458                 cfg->args [0] = mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
11459
11460         for (i = 0; i < sig->param_count; ++i) {
11461                 cfg->args [i + sig->hasthis] = mono_compile_create_var (cfg, sig->params [i], OP_ARG);
11462                 if (sig->params [i]->byref) {
11463                         cfg->disable_ssa = TRUE;
11464                 }
11465         }
11466
11467         cfg->locals_start = cfg->num_varinfo;
11468
11469         if (cfg->verbose_level > 2)
11470                 g_print ("creating locals\n");
11471
11472         for (i = 0; i < header->num_locals; ++i)
11473                 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
11474         if (cfg->verbose_level > 2)
11475                 g_print ("locals done\n");
11476
11477         mono_arch_create_vars (cfg);
11478 }
11479
11480 void
11481 mono_print_code (MonoCompile *cfg)
11482 {
11483         MonoBasicBlock *bb;
11484         
11485         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11486                 MonoInst *tree;
11487
11488                 if (!MONO_INST_LIST_EMPTY (&bb->ins_list))
11489                         g_print ("CODE BLOCK %d (nesting %d):\n",
11490                                  bb->block_num, bb->nesting);
11491
11492                 MONO_BB_FOR_EACH_INS (bb, tree) {
11493                         mono_print_tree (tree);
11494                         g_print ("\n");
11495                 }
11496         }
11497 }
11498
11499 extern const char * const mono_burg_rule_string [];
11500
11501 static void
11502 emit_state (MonoCompile *cfg, MBState *state, int goal)
11503 {
11504         MBState *kids [10];
11505         int ern = mono_burg_rule (state, goal);
11506         const guint16 *nts = mono_burg_nts_data + mono_burg_nts [ern];
11507
11508         //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
11509         switch (goal) {
11510         case MB_NTERM_reg:
11511                 //if (state->reg2)
11512                 //      state->reg1 = state->reg2; /* chain rule */
11513                 //else
11514 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
11515                 if (!state->reg1)
11516 #endif
11517                         state->reg1 = mono_regstate_next_int (cfg->rs);
11518                 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
11519                 break;
11520         case MB_NTERM_lreg:
11521                 state->reg1 = mono_regstate_next_int (cfg->rs);
11522                 state->reg2 = mono_regstate_next_int (cfg->rs);
11523                 break;
11524         case MB_NTERM_freg:
11525 #ifdef MONO_ARCH_SOFT_FLOAT
11526                 state->reg1 = mono_regstate_next_int (cfg->rs);
11527                 state->reg2 = mono_regstate_next_int (cfg->rs);
11528 #else
11529                 state->reg1 = mono_regstate_next_float (cfg->rs);
11530 #endif
11531                 break;
11532         default:
11533 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
11534                 /*
11535                  * Enabling this might cause bugs to surface in the local register
11536                  * allocators on some architectures like x86.
11537                  */
11538                 if ((state->tree->ssa_op == MONO_SSA_STORE) && (state->left->tree->opcode == OP_REGVAR)) {
11539                         /* Do not optimize away reg-reg moves */
11540                         if (! ((state->right->tree->ssa_op == MONO_SSA_LOAD) && (state->right->left->tree->opcode == OP_REGVAR))) {
11541                                 state->right->reg1 = state->left->tree->dreg;
11542                         }
11543                 }
11544 #endif
11545
11546                 /* do nothing */
11547                 break;
11548         }
11549         if (nts [0]) {
11550                 mono_burg_kids (state, ern, kids);
11551
11552                 emit_state (cfg, kids [0], nts [0]);
11553                 if (nts [1]) {
11554                         emit_state (cfg, kids [1], nts [1]);
11555                         if (nts [2]) {
11556                                 emit_state (cfg, kids [2], nts [2]);
11557                                 if (nts [3]) {
11558                                         g_assert (!nts [4]);
11559                                         emit_state (cfg, kids [3], nts [3]);
11560                                 }
11561                         }
11562                 }
11563         }
11564
11565 //      g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
11566         mono_burg_emit (ern, state, state->tree, cfg);
11567 }
11568
11569 #define DEBUG_SELECTION
11570
11571 static void 
11572 mini_select_instructions (MonoCompile *cfg)
11573 {
11574         MonoBasicBlock *bb;
11575         
11576         cfg->state_pool = mono_mempool_new ();
11577         cfg->rs = mono_regstate_new ();
11578
11579         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11580                 MonoInst *last_ins = mono_inst_list_last (&bb->ins_list);
11581
11582                 if (last_ins && MONO_IS_COND_BRANCH_OP (last_ins) &&
11583                                 bb->next_bb != last_ins->inst_false_bb) {
11584
11585                         /* we are careful when inverting, since bugs like #59580
11586                          * could show up when dealing with NaNs.
11587                          */
11588                         if (MONO_IS_COND_BRANCH_NOFP(last_ins) && bb->next_bb == last_ins->inst_true_bb) {
11589                                 MonoBasicBlock *tmp =  last_ins->inst_true_bb;
11590                                 last_ins->inst_true_bb = last_ins->inst_false_bb;
11591                                 last_ins->inst_false_bb = tmp;
11592
11593                                 last_ins->opcode = reverse_branch_op (last_ins->opcode);
11594                         } else {                        
11595                                 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
11596                                 inst->opcode = OP_BR;
11597                                 inst->inst_target_bb = last_ins->inst_false_bb;
11598                                 mono_bblock_add_inst (bb, inst);
11599                         }
11600                 }
11601         }
11602
11603 #ifdef DEBUG_SELECTION
11604         if (cfg->verbose_level >= 4) {
11605         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11606                 MonoInst *tree; 
11607                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
11608
11609                 MONO_BB_FOR_EACH_INS (bb, tree) {
11610                         mono_print_tree (tree);
11611                         g_print ("\n");
11612                 }
11613         }
11614         }
11615 #endif
11616
11617         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11618                 MonoInst *tree, *n;     
11619                 MonoInstList head;
11620                 MBState *mbstate;
11621
11622                 MONO_INST_LIST_INIT (&head);
11623                 if (MONO_INST_LIST_EMPTY (&bb->ins_list))
11624                         continue;
11625                 MONO_INST_LIST_SPLICE_INIT (&bb->ins_list, &head);
11626                 
11627                 cfg->cbb = bb;
11628                 mono_regstate_reset (cfg->rs);
11629
11630 #ifdef DEBUG_SELECTION
11631                 if (cfg->verbose_level >= 3)
11632                         g_print ("LABEL BLOCK %d:\n", bb->block_num);
11633 #endif
11634                 MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (tree, n, &head, node) {
11635 #ifdef DEBUG_SELECTION
11636                         if (cfg->verbose_level >= 3) {
11637                                 mono_print_tree (tree);
11638                                 g_print ("\n");
11639                         }
11640 #endif
11641
11642                         cfg->ip = tree->cil_code;
11643                         if (!(mbstate = mono_burg_label (tree, cfg))) {
11644                                 g_warning ("unable to label tree %p", tree);
11645                                 mono_print_tree (tree);
11646                                 g_print ("\n");                         
11647                                 g_assert_not_reached ();
11648                         }
11649                         emit_state (cfg, mbstate, MB_NTERM_stmt);
11650                 }
11651                 bb->max_vreg = cfg->rs->next_vreg;
11652
11653                 mono_mempool_empty (cfg->state_pool); 
11654         }
11655         mono_mempool_destroy (cfg->state_pool); 
11656
11657         cfg->ip = NULL;
11658 }
11659
11660 /*
11661  * mono_normalize_opcodes:
11662  *
11663  *   Replace CEE_ and OP_ opcodes with the corresponding OP_I or OP_L opcodes.
11664  */
11665
11666 static gint16 *remap_table;
11667
11668 #if SIZEOF_VOID_P == 8
11669 #define REMAP_OPCODE(opcode) OP_L ## opcode
11670 #else
11671 #define REMAP_OPCODE(opcode) OP_I ## opcode
11672 #endif
11673
11674 static G_GNUC_UNUSED void
11675 mono_normalize_opcodes (MonoCompile *cfg, MonoBasicBlock *bb)
11676 {
11677         MonoInst *ins;
11678
11679         if (!remap_table) {
11680                 remap_table = g_new0 (gint16, OP_LAST);
11681
11682 #if SIZEOF_VOID_P == 8
11683                 remap_table [CEE_CONV_U8] = OP_ZEXT_I4;
11684                 remap_table [CEE_CONV_U] = OP_ZEXT_I4;
11685                 remap_table [CEE_CONV_I8] = OP_SEXT_I4;
11686                 remap_table [CEE_CONV_I] = OP_SEXT_I4;
11687                 remap_table [CEE_CONV_OVF_U4] = OP_LCONV_TO_OVF_U4;
11688                 remap_table [CEE_CONV_OVF_I4_UN] = OP_LCONV_TO_OVF_I4_UN;
11689 #else
11690 #endif
11691                 remap_table [CEE_CONV_R4] = OP_ICONV_TO_R4;
11692                 remap_table [CEE_CONV_R8] = OP_ICONV_TO_R8;
11693                 remap_table [CEE_CONV_I4] = OP_MOVE;
11694                 remap_table [CEE_CONV_U4] = OP_MOVE;
11695                 remap_table [CEE_CONV_I1] = REMAP_OPCODE (CONV_TO_I1);
11696                 remap_table [CEE_CONV_I2] = REMAP_OPCODE (CONV_TO_I2);
11697                 remap_table [CEE_CONV_U1] = REMAP_OPCODE (CONV_TO_U1);
11698                 remap_table [CEE_CONV_U2] = REMAP_OPCODE (CONV_TO_U2);
11699                 remap_table [CEE_CONV_R_UN] = REMAP_OPCODE (CONV_TO_R_UN);
11700                 remap_table [CEE_ADD] = REMAP_OPCODE (ADD);
11701                 remap_table [CEE_SUB] = REMAP_OPCODE (SUB);
11702                 remap_table [CEE_MUL] = REMAP_OPCODE (MUL);
11703                 remap_table [CEE_DIV] = REMAP_OPCODE (DIV);
11704                 remap_table [CEE_REM] = REMAP_OPCODE (REM);
11705                 remap_table [CEE_DIV_UN] = REMAP_OPCODE (DIV_UN);
11706                 remap_table [CEE_REM_UN] = REMAP_OPCODE (REM_UN);
11707                 remap_table [CEE_AND] = REMAP_OPCODE (AND);
11708                 remap_table [CEE_OR] = REMAP_OPCODE (OR);
11709                 remap_table [CEE_XOR] = REMAP_OPCODE (XOR);
11710                 remap_table [CEE_SHL] = REMAP_OPCODE (SHL);
11711                 remap_table [CEE_SHR] = REMAP_OPCODE (SHR);
11712                 remap_table [CEE_SHR_UN] = REMAP_OPCODE (SHR_UN);
11713                 remap_table [CEE_NOT] = REMAP_OPCODE (NOT);
11714                 remap_table [CEE_NEG] = REMAP_OPCODE (NEG);
11715                 remap_table [CEE_CALL] = OP_CALL;
11716                 remap_table [CEE_BEQ] = REMAP_OPCODE (BEQ);
11717                 remap_table [CEE_BNE_UN] = REMAP_OPCODE (BNE_UN);
11718                 remap_table [CEE_BLT] = REMAP_OPCODE (BLT);
11719                 remap_table [CEE_BLT_UN] = REMAP_OPCODE (BLT_UN);
11720                 remap_table [CEE_BGT] = REMAP_OPCODE (BGT);
11721                 remap_table [CEE_BGT_UN] = REMAP_OPCODE (BGT_UN);
11722                 remap_table [CEE_BGE] = REMAP_OPCODE (BGE);
11723                 remap_table [CEE_BGE_UN] = REMAP_OPCODE (BGE_UN);
11724                 remap_table [CEE_BLE] = REMAP_OPCODE (BLE);
11725                 remap_table [CEE_BLE_UN] = REMAP_OPCODE (BLE_UN);
11726                 remap_table [CEE_ADD_OVF] = REMAP_OPCODE (ADD_OVF);
11727                 remap_table [CEE_ADD_OVF_UN] = REMAP_OPCODE (ADD_OVF_UN);
11728                 remap_table [CEE_SUB_OVF] = REMAP_OPCODE (SUB_OVF);
11729                 remap_table [CEE_SUB_OVF_UN] = REMAP_OPCODE (SUB_OVF_UN);
11730                 remap_table [CEE_MUL_OVF] = REMAP_OPCODE (MUL_OVF);
11731                 remap_table [CEE_MUL_OVF_UN] = REMAP_OPCODE (MUL_OVF_UN);
11732         }
11733
11734         MONO_BB_FOR_EACH_INS (bb, ins) {
11735                 int remapped = remap_table [ins->opcode];
11736                 if (remapped)
11737                         ins->opcode = remapped;
11738         }
11739 }
11740
11741 void
11742 mono_codegen (MonoCompile *cfg)
11743 {
11744         MonoJumpInfo *patch_info;
11745         MonoBasicBlock *bb;
11746         int i, max_epilog_size;
11747         guint8 *code;
11748
11749         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11750                 cfg->spill_count = 0;
11751                 /* we reuse dfn here */
11752                 /* bb->dfn = bb_count++; */
11753 #ifdef MONO_ARCH_ENABLE_NORMALIZE_OPCODES
11754                 mono_normalize_opcodes (cfg, bb);
11755 #endif
11756
11757                 mono_arch_lowering_pass (cfg, bb);
11758
11759                 if (cfg->opt & MONO_OPT_PEEPHOLE)
11760                         mono_arch_peephole_pass_1 (cfg, bb);
11761
11762                 mono_local_regalloc (cfg, bb);
11763
11764                 if (cfg->opt & MONO_OPT_PEEPHOLE)
11765                         mono_arch_peephole_pass_2 (cfg, bb);
11766         }
11767
11768         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
11769                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
11770
11771         code = mono_arch_emit_prolog (cfg);
11772
11773         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
11774                 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
11775
11776         cfg->code_len = code - cfg->native_code;
11777         cfg->prolog_end = cfg->code_len;
11778
11779         mono_debug_open_method (cfg);
11780
11781         /* emit code all basic blocks */
11782         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11783                 bb->native_offset = cfg->code_len;
11784                 mono_arch_output_basic_block (cfg, bb);
11785
11786                 if (bb == cfg->bb_exit) {
11787                         cfg->epilog_begin = cfg->code_len;
11788
11789                         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
11790                                 code = cfg->native_code + cfg->code_len;
11791                                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
11792                                 cfg->code_len = code - cfg->native_code;
11793                                 g_assert (cfg->code_len < cfg->code_size);
11794                         }
11795
11796                         mono_arch_emit_epilog (cfg);
11797                 }
11798         }
11799
11800         mono_arch_emit_exceptions (cfg);
11801
11802         max_epilog_size = 0;
11803
11804         code = cfg->native_code + cfg->code_len;
11805
11806         /* we always allocate code in cfg->domain->code_mp to increase locality */
11807         cfg->code_size = cfg->code_len + max_epilog_size;
11808         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
11809
11810         if (cfg->method->dynamic) {
11811                 guint unwindlen = 0;
11812 #ifdef WIN64
11813                 unwindlen = mono_arch_unwindinfo_get_size (cfg->arch.unwindinfo);
11814 #endif
11815                 /* Allocate the code into a separate memory pool so it can be freed */
11816                 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
11817                 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
11818                 mono_domain_lock (cfg->domain);
11819                 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
11820                 mono_domain_unlock (cfg->domain);
11821
11822                 code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size + unwindlen);
11823         } else {
11824                 guint unwindlen = 0;
11825 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
11826                 unwindlen = mono_arch_unwindinfo_get_size (cfg->arch.unwindinfo);
11827 #endif
11828                 mono_domain_lock (cfg->domain);
11829                 code = mono_code_manager_reserve (cfg->domain->code_mp, cfg->code_size + unwindlen);
11830                 mono_domain_unlock (cfg->domain);
11831         }
11832
11833         memcpy (code, cfg->native_code, cfg->code_len);
11834         g_free (cfg->native_code);
11835         cfg->native_code = code;
11836         code = cfg->native_code + cfg->code_len;
11837   
11838         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
11839         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
11840                 switch (patch_info->type) {
11841                 case MONO_PATCH_INFO_ABS: {
11842                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
11843                         if (info) {
11844                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
11845                                 // FIXME: CLEAN UP THIS MESS.
11846                                 if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && 
11847                                         strstr (cfg->method->name, info->name)) {
11848                                         /*
11849                                          * This is an icall wrapper, and this is a call to the
11850                                          * wrapped function.
11851                                          */
11852                                         if (cfg->compile_aot) {
11853                                                 patch_info->type = MONO_PATCH_INFO_JIT_ICALL_ADDR;
11854                                                 patch_info->data.name = info->name;
11855                                         }
11856                                 } else {
11857                                         /* for these array methods we currently register the same function pointer
11858                                          * since it's a vararg function. But this means that mono_find_jit_icall_by_addr ()
11859                                          * will return the incorrect one depending on the order they are registered.
11860                                          * See tests/test-arr.cs
11861                                          */
11862                                         if (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL) {
11863                                                 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
11864                                                 patch_info->data.name = info->name;
11865                                         }
11866                                 }
11867                         }
11868                         else {
11869                                 MonoVTable *vtable = mono_find_class_init_trampoline_by_addr (patch_info->data.target);
11870                                 if (vtable) {
11871                                         patch_info->type = MONO_PATCH_INFO_CLASS_INIT;
11872                                         patch_info->data.klass = vtable->klass;
11873                                 } else {
11874                                         MonoClass *klass = mono_find_delegate_trampoline_by_addr (patch_info->data.target);
11875                                         if (klass) {
11876                                                 patch_info->type = MONO_PATCH_INFO_DELEGATE_TRAMPOLINE;
11877                                                 patch_info->data.klass = klass;
11878                                         }
11879                                 }
11880                         }
11881                         break;
11882                 }
11883                 case MONO_PATCH_INFO_SWITCH: {
11884                         gpointer *table;
11885                         if (cfg->method->dynamic) {
11886                                 table = mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
11887                         } else {
11888                                 mono_domain_lock (cfg->domain);
11889                                 table = mono_code_manager_reserve (cfg->domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
11890                                 mono_domain_unlock (cfg->domain);
11891                         }
11892
11893                         if (!cfg->compile_aot)
11894                                 /* In the aot case, the patch already points to the correct location */
11895                                 patch_info->ip.i = patch_info->ip.label->inst_c0;
11896                         for (i = 0; i < patch_info->data.table->table_size; i++) {
11897                                 table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
11898                         }
11899                         patch_info->data.table->table = (MonoBasicBlock**)table;
11900                         break;
11901                 }
11902                 default:
11903                         /* do nothing */
11904                         break;
11905                 }
11906         }
11907
11908 #ifdef VALGRIND_JIT_REGISTER_MAP
11909 if (valgrind_register){
11910                 char* nm = mono_method_full_name (cfg->method, TRUE);
11911                 VALGRIND_JIT_REGISTER_MAP (nm, cfg->native_code, cfg->native_code + cfg->code_len);
11912                 g_free (nm);
11913         }
11914 #endif
11915  
11916         if (cfg->verbose_level > 0) {
11917                 char* nm = mono_method_full_name (cfg->method, TRUE);
11918                 g_print ("Method %s emitted at %p to %p (code length %d) [%s]\n", 
11919                                  nm, 
11920                                  cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
11921                 g_free (nm);
11922         }
11923
11924         {
11925                 gboolean is_generic = FALSE;
11926
11927                 if (cfg->method->is_inflated || mono_method_get_generic_container (cfg->method) ||
11928                                 cfg->method->klass->generic_container || cfg->method->klass->generic_class) {
11929                         is_generic = TRUE;
11930                 }
11931
11932                 if (cfg->generic_sharing_context)
11933                         g_assert (is_generic);
11934         }
11935
11936 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
11937         mono_arch_save_unwind_info (cfg);
11938 #endif
11939         
11940         mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
11941
11942         if (cfg->method->dynamic) {
11943                 mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
11944         } else {
11945                 mono_domain_lock (cfg->domain);
11946                 mono_code_manager_commit (cfg->domain->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
11947                 mono_domain_unlock (cfg->domain);
11948         }
11949         
11950         mono_arch_flush_icache (cfg->native_code, cfg->code_len);
11951
11952         mono_debug_close_method (cfg);
11953 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
11954         mono_arch_unwindinfo_install_unwind_info (&cfg->arch.unwindinfo, cfg->native_code, cfg->code_len);
11955 #endif
11956 }
11957
11958
11959
11960 static void
11961 remove_critical_edges (MonoCompile *cfg) {
11962         MonoBasicBlock *bb;
11963         MonoBasicBlock *previous_bb;
11964         
11965         if (cfg->verbose_level > 3) {
11966                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11967                         MonoInst *last_ins;
11968                         int i;
11969                         printf ("remove_critical_edges %s, BEFORE BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
11970                         for (i = 0; i < bb->in_count; i++) {
11971                                 printf (" %d", bb->in_bb [i]->block_num);
11972                         }
11973                         printf (") (out:");
11974                         for (i = 0; i < bb->out_count; i++) {
11975                                 printf (" %d", bb->out_bb [i]->block_num);
11976                         }
11977                         printf (")");
11978                         last_ins = mono_inst_list_last (&bb->ins_list);
11979                         if (last_ins) {
11980                                 printf (" ");
11981                                 mono_print_tree (last_ins);
11982                         }
11983                         printf ("\n");
11984                 }
11985         }
11986         
11987         for (previous_bb = cfg->bb_entry, bb = previous_bb->next_bb; bb != NULL; previous_bb = previous_bb->next_bb, bb = bb->next_bb) {
11988                 if (bb->in_count > 1) {
11989                         int in_bb_index;
11990                         for (in_bb_index = 0; in_bb_index < bb->in_count; in_bb_index++) {
11991                                 MonoBasicBlock *in_bb = bb->in_bb [in_bb_index];
11992                                 if (in_bb->out_count > 1) {
11993                                         MonoBasicBlock *new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
11994                                         MONO_INST_LIST_INIT (&new_bb->ins_list);
11995                                         new_bb->block_num = cfg->num_bblocks++;
11996 //                                      new_bb->real_offset = bb->real_offset;
11997                                         new_bb->region = bb->region;
11998                                         
11999                                         /* Do not alter the CFG while altering the BB list */
12000                                         if (previous_bb->region == bb->region) {
12001                                                 if (previous_bb != cfg->bb_entry) {
12002                                                         MonoInst *last_ins;
12003                                                         /* If previous_bb "followed through" to bb, */
12004                                                         /* keep it linked with a OP_BR */
12005                                                         last_ins = mono_inst_list_last (&previous_bb->ins_list);
12006                                                         if ((last_ins == NULL) ||
12007                                                                         ((last_ins->opcode != OP_BR) &&
12008                                                                         (!(MONO_IS_COND_BRANCH_OP (last_ins))) &&
12009                                                                         (last_ins->opcode != OP_SWITCH))) {
12010                                                                 int i;
12011                                                                 /* Make sure previous_bb really falls through bb */
12012                                                                 for (i = 0; i < previous_bb->out_count; i++) {
12013                                                                         if (previous_bb->out_bb [i] == bb) {
12014                                                                                 MonoInst *jump;
12015                                                                                 MONO_INST_NEW (cfg, jump, OP_BR);
12016                                                                                 MONO_ADD_INS (previous_bb, jump);
12017                                                                                 jump->cil_code = previous_bb->cil_code;
12018                                                                                 jump->inst_target_bb = bb;
12019                                                                                 break;
12020                                                                         }
12021                                                                 }
12022                                                         }
12023                                                 } else {
12024                                                         /* We cannot add any inst to the entry BB, so we must */
12025                                                         /* put a new BB in the middle to hold the OP_BR */
12026                                                         MonoInst *jump;
12027                                                         MonoBasicBlock *new_bb_after_entry = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
12028                                                         MONO_INST_LIST_INIT (&new_bb_after_entry->ins_list);
12029                                                         new_bb_after_entry->block_num = cfg->num_bblocks++;
12030 //                                                      new_bb_after_entry->real_offset = bb->real_offset;
12031                                                         new_bb_after_entry->region = bb->region;
12032                                                         
12033                                                         MONO_INST_NEW (cfg, jump, OP_BR);
12034                                                         MONO_ADD_INS (new_bb_after_entry, jump);
12035                                                         jump->cil_code = bb->cil_code;
12036                                                         jump->inst_target_bb = bb;
12037                                                         
12038                                                         previous_bb->next_bb = new_bb_after_entry;
12039                                                         previous_bb = new_bb_after_entry;
12040                                                         
12041                                                         if (cfg->verbose_level > 2) {
12042                                                                 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);
12043                                                         }
12044                                                 }
12045                                         }
12046                                         
12047                                         /* Insert new_bb in the BB list */
12048                                         previous_bb->next_bb = new_bb;
12049                                         new_bb->next_bb = bb;
12050                                         previous_bb = new_bb;
12051                                         
12052                                         /* Setup in_bb and out_bb */
12053                                         new_bb->in_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
12054                                         new_bb->in_bb [0] = in_bb;
12055                                         new_bb->in_count = 1;
12056                                         new_bb->out_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
12057                                         new_bb->out_bb [0] = bb;
12058                                         new_bb->out_count = 1;
12059                                         
12060                                         /* Relink in_bb and bb to (from) new_bb */
12061                                         replace_out_block (in_bb, bb, new_bb);
12062                                         replace_out_block_in_code (in_bb, bb, new_bb);
12063                                         replace_in_block (bb, in_bb, new_bb);
12064                                         
12065                                         if (cfg->verbose_level > 2) {
12066                                                 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);
12067                                         }
12068                                 }
12069                         }
12070                 }
12071         }
12072         
12073         if (cfg->verbose_level > 3) {
12074                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
12075                         MonoInst *last_ins;
12076                         int i;
12077                         printf ("remove_critical_edges %s, AFTER BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
12078                         for (i = 0; i < bb->in_count; i++) {
12079                                 printf (" %d", bb->in_bb [i]->block_num);
12080                         }
12081                         printf (") (out:");
12082                         for (i = 0; i < bb->out_count; i++) {
12083                                 printf (" %d", bb->out_bb [i]->block_num);
12084                         }
12085                         printf (")");
12086                         last_ins = mono_inst_list_last (&bb->ins_list);
12087                         if (last_ins) {
12088                                 printf (" ");
12089                                 mono_print_tree (last_ins);
12090                         }
12091                         printf ("\n");
12092                 }
12093         }
12094 }
12095
12096 static MonoGenericInst*
12097 get_object_generic_inst (int type_argc)
12098 {
12099         MonoType **type_argv;
12100         int i;
12101
12102         type_argv = alloca (sizeof (MonoType*) * type_argc);
12103
12104         for (i = 0; i < type_argc; ++i)
12105                 type_argv [i] = &mono_defaults.object_class->byval_arg;
12106
12107         return mono_metadata_get_generic_inst (type_argc, type_argv);
12108 }
12109
12110 /*
12111  * mini_method_compile:
12112  * @method: the method to compile
12113  * @opts: the optimization flags to use
12114  * @domain: the domain where the method will be compiled in
12115  * @run_cctors: whether we should run type ctors if possible
12116  * @compile_aot: whether this is an AOT compilation
12117  * @parts: debug flag
12118  *
12119  * Returns: a MonoCompile* pointer. Caller must check the exception_type
12120  * field in the returned struct to see if compilation succeded.
12121  */
12122 MonoCompile*
12123 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
12124 {
12125         MonoMethodHeader *header;
12126         guint8 *ip;
12127         MonoCompile *cfg;
12128         MonoJitInfo *jinfo;
12129         int dfn = 0, i, code_size_ratio;
12130         gboolean deadce_has_run = FALSE;
12131         gboolean try_generic_shared;
12132         MonoMethod *method_to_compile, *method_to_register;
12133         int generic_info_size;
12134
12135         mono_jit_stats.methods_compiled++;
12136         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
12137                 mono_profiler_method_jit (method);
12138         if (MONO_PROBE_METHOD_COMPILE_BEGIN_ENABLED ())
12139                 MONO_PROBE_METHOD_COMPILE_BEGIN (method);
12140  
12141         if (compile_aot)
12142                 /* We are passed the original generic method definition */
12143                 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
12144                         (opts & MONO_OPT_GSHARED) && (method->is_generic || method->klass->generic_container);
12145         else
12146                 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
12147                         (opts & MONO_OPT_GSHARED) && mono_method_is_generic_sharable_impl (method, FALSE);
12148
12149         if (opts & MONO_OPT_GSHARED) {
12150                 if (try_generic_shared)
12151                         mono_stats.generics_sharable_methods++;
12152                 else if (mono_method_is_generic_impl (method))
12153                         mono_stats.generics_unsharable_methods++;
12154         }
12155
12156  restart_compile:
12157         if (try_generic_shared) {
12158                 MonoMethod *declaring_method;
12159                 MonoGenericContext *shared_context;
12160
12161                 if (compile_aot) {
12162                         declaring_method = method;
12163                 } else {
12164                         declaring_method = mono_method_get_declaring_generic_method (method);
12165                         if (method->klass->generic_class)
12166                                 g_assert (method->klass->generic_class->container_class == declaring_method->klass);
12167                         else
12168                                 g_assert (method->klass == declaring_method->klass);
12169                 }
12170
12171                 if (declaring_method->is_generic)
12172                         shared_context = &(mono_method_get_generic_container (declaring_method)->context);
12173                 else
12174                         shared_context = &declaring_method->klass->generic_container->context;
12175
12176                 method_to_compile = mono_class_inflate_generic_method (declaring_method, shared_context);
12177                 g_assert (method_to_compile);
12178         } else {
12179                 method_to_compile = method;
12180         }
12181
12182         cfg = g_new0 (MonoCompile, 1);
12183         cfg->method = method_to_compile;
12184         cfg->mempool = mono_mempool_new ();
12185         cfg->opt = opts;
12186         cfg->prof_options = mono_profiler_get_events ();
12187         cfg->run_cctors = run_cctors;
12188         cfg->domain = domain;
12189         cfg->verbose_level = mini_verbose;
12190         cfg->compile_aot = compile_aot;
12191         cfg->skip_visibility = method->skip_visibility;
12192         if (try_generic_shared)
12193                 cfg->generic_sharing_context = (MonoGenericSharingContext*)&cfg->generic_sharing_context;
12194         cfg->token_info_hash = g_hash_table_new (NULL, NULL);
12195
12196         /* The debugger has no liveness information, so avoid sharing registers/stack slots */
12197         if (mono_debug_using_mono_debugger () || debug_options.mdb_optimizations) {
12198                 cfg->disable_reuse_registers = TRUE;
12199                 cfg->disable_reuse_stack_slots = TRUE;
12200                 /* 
12201                  * This decreases the change the debugger will read registers/stack slots which are
12202                  * not yet initialized.
12203                  */
12204                 cfg->disable_initlocals_opt = TRUE;
12205
12206                 /* Temporarily disable this when running in the debugger until we have support
12207                  * for this in the debugger. */
12208                 cfg->disable_omit_fp = TRUE;
12209
12210                 // cfg->opt |= MONO_OPT_SHARED;
12211                 cfg->opt &= ~MONO_OPT_INLINE;
12212                 cfg->opt &= ~MONO_OPT_COPYPROP;
12213                 cfg->opt &= ~MONO_OPT_CONSPROP;
12214         }
12215
12216         header = mono_method_get_header (method_to_compile);
12217         if (!header) {
12218                 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
12219                 cfg->exception_message = g_strdup_printf ("Missing or incorrect header for method %s", cfg->method->name);
12220                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
12221                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
12222                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
12223                         mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
12224                 return cfg;
12225         }
12226
12227         ip = (guint8 *)header->code;
12228
12229         if (cfg->verbose_level > 2) {
12230                 if (cfg->generic_sharing_context)
12231                         g_print ("converting shared method %s\n", mono_method_full_name (method, TRUE));
12232                 else
12233                         g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
12234         }
12235
12236         /*
12237          * create MonoInst* which represents arguments and local variables
12238          */
12239         mono_compile_create_vars (cfg);
12240
12241         if ((i = mono_method_to_ir (cfg, method_to_compile, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
12242                 if (try_generic_shared && cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
12243                         if (compile_aot) {
12244                                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
12245                                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
12246                                 return cfg;
12247                         }
12248                         mono_destroy_compile (cfg);
12249                         try_generic_shared = FALSE;
12250                         goto restart_compile;
12251                 }
12252                 g_assert (cfg->exception_type != MONO_EXCEPTION_GENERIC_SHARING_FAILED);
12253
12254                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
12255                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
12256                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
12257                         mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
12258                 /* cfg contains the details of the failure, so let the caller cleanup */
12259                 return cfg;
12260         }
12261
12262         mono_jit_stats.basic_blocks += cfg->num_bblocks;
12263         mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
12264
12265         if ((cfg->num_varinfo > 2000) && !cfg->compile_aot) {
12266                 /* 
12267                  * we disable some optimizations if there are too many variables
12268                  * because JIT time may become too expensive. The actual number needs 
12269                  * to be tweaked and eventually the non-linear algorithms should be fixed.
12270                  */
12271                 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
12272                 cfg->disable_ssa = TRUE;
12273         }
12274
12275         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
12276
12277         if (cfg->opt & MONO_OPT_BRANCH)
12278                 optimize_branches (cfg);
12279
12280         if (cfg->opt & MONO_OPT_SSAPRE) {
12281                 remove_critical_edges (cfg);
12282         }
12283
12284         /* Depth-first ordering on basic blocks */
12285         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
12286
12287         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
12288         if (cfg->num_bblocks != dfn + 1) {
12289                 MonoBasicBlock *bb;
12290
12291                 cfg->num_bblocks = dfn + 1;
12292
12293                 if (!header->clauses) {
12294                         /* remove unreachable code, because the code in them may be 
12295                          * inconsistent  (access to dead variables for example) */
12296                         for (bb = cfg->bb_entry; bb;) {
12297                                 MonoBasicBlock *bbn = bb->next_bb;
12298
12299                                 if (bbn && bbn->region == -1 && !bbn->dfn) {
12300                                         if (cfg->verbose_level > 1)
12301                                                 g_print ("found unreachable code in BB%d\n", bbn->block_num);
12302                                         bb->next_bb = bbn->next_bb;
12303                                         nullify_basic_block (bbn);                      
12304                                 } else {
12305                                         bb = bb->next_bb;
12306                                 }
12307                         }
12308                 }
12309         }
12310
12311         if (cfg->opt & MONO_OPT_LOOP) {
12312                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
12313                 mono_compute_natural_loops (cfg);
12314         }
12315
12316         /* after method_to_ir */
12317         if (parts == 1) {
12318                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
12319                         MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
12320                 return cfg;
12321         }
12322
12323 //#define DEBUGSSA "logic_run"
12324 #define DEBUGSSA_CLASS "Tests"
12325 #ifdef DEBUGSSA
12326
12327         if (!header->num_clauses && !cfg->disable_ssa) {
12328                 mono_local_cprop (cfg);
12329 #ifndef DISABLE_SSA
12330                 mono_ssa_compute (cfg);
12331 #endif
12332         }
12333 #else 
12334
12335         /* fixme: add all optimizations which requires SSA */
12336         if (cfg->opt & (MONO_OPT_SSA | MONO_OPT_ABCREM | MONO_OPT_SSAPRE)) {
12337                 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
12338                         mono_local_cprop (cfg);
12339 #ifndef DISABLE_SSA
12340                         mono_ssa_compute (cfg);
12341 #endif
12342
12343                         if (cfg->verbose_level >= 2) {
12344                                 print_dfn (cfg);
12345                         }
12346                 }
12347         }
12348 #endif
12349
12350         /* after SSA translation */
12351         if (parts == 2) {
12352                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
12353                         MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
12354                 return cfg;
12355         }
12356
12357         if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
12358                 if (cfg->comp_done & MONO_COMP_SSA) {
12359 #ifndef DISABLE_SSA
12360                         mono_ssa_cprop (cfg);
12361 #endif
12362                 } else {
12363                         mono_local_cprop (cfg);
12364                 }
12365         }
12366
12367 #ifndef DISABLE_SSA
12368         if (cfg->comp_done & MONO_COMP_SSA) {                   
12369                 //mono_ssa_deadce (cfg);
12370
12371                 //mono_ssa_strength_reduction (cfg);
12372
12373                 if (cfg->opt & MONO_OPT_SSAPRE) {
12374                         mono_perform_ssapre (cfg);
12375                         //mono_local_cprop (cfg);
12376                 }
12377                 
12378                 if (cfg->opt & MONO_OPT_DEADCE) {
12379                         mono_ssa_deadce (cfg);
12380                         deadce_has_run = TRUE;
12381                 }
12382                 
12383                 if ((cfg->flags & MONO_CFG_HAS_LDELEMA) && (cfg->opt & MONO_OPT_ABCREM))
12384                         mono_perform_abc_removal (cfg);
12385                 
12386                 mono_ssa_remove (cfg);
12387
12388                 if (cfg->opt & MONO_OPT_BRANCH)
12389                         optimize_branches (cfg);
12390         }
12391 #endif
12392
12393         /* after SSA removal */
12394         if (parts == 3) {
12395                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
12396                         MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
12397                 return cfg;
12398         }
12399
12400         if (cfg->verbose_level > 4) {
12401                 printf ("BEFORE DECOMPSE START\n");
12402                 mono_print_code (cfg);
12403                 printf ("BEFORE DECOMPSE END\n");
12404         }
12405         
12406         decompose_pass (cfg);
12407
12408         if (cfg->got_var) {
12409                 GList *regs;
12410
12411                 g_assert (cfg->got_var_allocated);
12412
12413                 /* 
12414                  * Allways allocate the GOT var to a register, because keeping it
12415                  * in memory will increase the number of live temporaries in some
12416                  * code created by inssel.brg, leading to the well known spills+
12417                  * branches problem. Testcase: mcs crash in 
12418                  * System.MonoCustomAttrs:GetCustomAttributes.
12419                  */
12420                 regs = mono_arch_get_global_int_regs (cfg);
12421                 g_assert (regs);
12422                 cfg->got_var->opcode = OP_REGVAR;
12423                 cfg->got_var->dreg = GPOINTER_TO_INT (regs->data);
12424                 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
12425                 
12426                 g_list_free (regs);
12427         }
12428
12429         /* todo: remove code when we have verified that the liveness for try/catch blocks
12430          * works perfectly 
12431          */
12432         /* 
12433          * Currently, this can't be commented out since exception blocks are not
12434          * processed during liveness analysis.
12435          */
12436         mono_liveness_handle_exception_clauses (cfg);
12437
12438         if (cfg->opt & MONO_OPT_LINEARS) {
12439                 GList *vars, *regs;
12440                 
12441                 /* For now, compute aliasing info only if needed for deadce... */
12442                 if ((cfg->opt & MONO_OPT_DEADCE) && (! deadce_has_run) && (header->num_clauses == 0)) {
12443                         cfg->aliasing_info = mono_build_aliasing_information (cfg);
12444                 }
12445
12446                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
12447                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
12448                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
12449                         mono_analyze_liveness (cfg);
12450
12451                 if (cfg->aliasing_info != NULL) {
12452                         mono_aliasing_deadce (cfg->aliasing_info);
12453                         deadce_has_run = TRUE;
12454                 }
12455                 
12456                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
12457                         regs = mono_arch_get_global_int_regs (cfg);
12458                         if (cfg->got_var)
12459                                 regs = g_list_delete_link (regs, regs);
12460                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
12461                 }
12462                 
12463                 if (cfg->aliasing_info != NULL) {
12464                         mono_destroy_aliasing_information (cfg->aliasing_info);
12465                         cfg->aliasing_info = NULL;
12466                 }
12467         }
12468
12469         //mono_print_code (cfg);
12470
12471     //print_dfn (cfg);
12472         
12473         /* variables are allocated after decompose, since decompose could create temps */
12474         mono_arch_allocate_vars (cfg);
12475
12476         if (cfg->opt & MONO_OPT_CFOLD)
12477                 mono_constant_fold (cfg);
12478
12479         mini_select_instructions (cfg);
12480
12481         mono_codegen (cfg);
12482         if (cfg->verbose_level >= 2) {
12483                 char *id =  mono_method_full_name (cfg->method, FALSE);
12484                 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
12485                 g_free (id);
12486         }
12487
12488         if (cfg->generic_sharing_context)
12489                 generic_info_size = sizeof (MonoGenericJitInfo);
12490         else
12491                 generic_info_size = 0;
12492
12493         if (cfg->method->dynamic) {
12494                 jinfo = g_malloc0 (sizeof (MonoJitInfo) + (header->num_clauses * sizeof (MonoJitExceptionInfo)) +
12495                                 generic_info_size);
12496         } else {
12497                 /* we access cfg->domain->mp */
12498                 mono_domain_lock (cfg->domain);
12499                 jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo) +
12500                                 (header->num_clauses * sizeof (MonoJitExceptionInfo)) +
12501                                 generic_info_size);
12502                 mono_domain_unlock (cfg->domain);
12503         }
12504
12505         if (cfg->generic_sharing_context) {
12506                 MonoGenericContext object_context;
12507
12508                 g_assert (!method_to_compile->klass->generic_class);
12509                 if (method_to_compile->klass->generic_container) {
12510                         int type_argc = method_to_compile->klass->generic_container->type_argc;
12511
12512                         object_context.class_inst = get_object_generic_inst (type_argc);
12513                 } else {
12514                         object_context.class_inst = NULL;
12515                 }
12516
12517                 if (mini_method_get_context (method_to_compile)->method_inst) {
12518                         int type_argc = mini_method_get_context (method_to_compile)->method_inst->type_argc;
12519
12520                         object_context.method_inst = get_object_generic_inst (type_argc);
12521                 } else {
12522                         object_context.method_inst = NULL;
12523                 }
12524
12525                 g_assert (object_context.class_inst || object_context.method_inst);
12526
12527                 method_to_register = mono_class_inflate_generic_method (method_to_compile, &object_context);
12528         } else {
12529                 g_assert (method == method_to_compile);
12530                 method_to_register = method;
12531         }
12532
12533         jinfo->method = method_to_register;
12534         jinfo->code_start = cfg->native_code;
12535         jinfo->code_size = cfg->code_len;
12536         jinfo->used_regs = cfg->used_int_regs;
12537         jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
12538         jinfo->cas_inited = FALSE; /* initialization delayed at the first stalk walk using this method */
12539         jinfo->num_clauses = header->num_clauses;
12540
12541         if (cfg->generic_sharing_context) {
12542                 MonoInst *inst;
12543                 MonoGenericJitInfo *gi;
12544
12545                 jinfo->has_generic_jit_info = 1;
12546
12547                 gi = mono_jit_info_get_generic_jit_info (jinfo);
12548                 g_assert (gi);
12549
12550                 gi->generic_sharing_context = cfg->generic_sharing_context;
12551
12552                 /*
12553                  * Non-generic static methods only get a "this" info
12554                  * if they use the rgctx variable (which they are
12555                  * forced to if they have any open catch clauses).
12556                  */
12557                 if (cfg->rgctx_var ||
12558                                 (!(method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) &&
12559                                 !mini_method_get_context (method_to_compile)->method_inst)) {
12560                         gi->has_this = 1;
12561
12562                         if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
12563                                         mini_method_get_context (method_to_compile)->method_inst) {
12564                                 inst = cfg->rgctx_var;
12565                                 g_assert (inst->opcode == OP_REGOFFSET);
12566                         } else {
12567                                 inst = cfg->args [0];
12568                         }
12569
12570                         if (inst->opcode == OP_REGVAR) {
12571                                 gi->this_in_reg = 1;
12572                                 gi->this_reg = inst->dreg;
12573
12574                                 //g_print ("this in reg %d\n", inst->dreg);
12575                         } else {
12576                                 g_assert (inst->opcode == OP_REGOFFSET);
12577 #ifdef __i386__
12578                                 g_assert (inst->inst_basereg == X86_EBP);
12579 #elif defined(__x86_64__)
12580                                 g_assert (inst->inst_basereg == X86_EBP || inst->inst_basereg == X86_ESP);
12581 #endif
12582                                 g_assert (inst->inst_offset >= G_MININT32 && inst->inst_offset <= G_MAXINT32);
12583
12584                                 gi->this_in_reg = 0;
12585                                 gi->this_reg = inst->inst_basereg;
12586                                 gi->this_offset = inst->inst_offset;
12587
12588                                 //g_print ("this at offset %d from reg %d\n", gi->this_offset, gi->this_reg);
12589                         }
12590                 } else {
12591                         gi->has_this = 0;
12592                 }
12593         }
12594
12595         if (header->num_clauses) {
12596                 int i;
12597
12598                 for (i = 0; i < header->num_clauses; i++) {
12599                         MonoExceptionClause *ec = &header->clauses [i];
12600                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
12601                         MonoBasicBlock *tblock;
12602                         MonoInst *exvar;
12603
12604                         ei->flags = ec->flags;
12605
12606                         exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
12607                         ei->exvar_offset = exvar ? exvar->inst_offset : 0;
12608
12609                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
12610                                 tblock = cfg->cil_offset_to_bb [ec->data.filter_offset];
12611                                 g_assert (tblock);
12612                                 ei->data.filter = cfg->native_code + tblock->native_offset;
12613                         } else {
12614                                 ei->data.catch_class = ec->data.catch_class;
12615                         }
12616
12617                         tblock = cfg->cil_offset_to_bb [ec->try_offset];
12618                         g_assert (tblock);
12619                         ei->try_start = cfg->native_code + tblock->native_offset;
12620                         g_assert (tblock->native_offset);
12621                         tblock = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
12622                         g_assert (tblock);
12623                         ei->try_end = cfg->native_code + tblock->native_offset;
12624                         g_assert (tblock->native_offset);
12625                         tblock = cfg->cil_offset_to_bb [ec->handler_offset];
12626                         g_assert (tblock);
12627                         ei->handler_start = cfg->native_code + tblock->native_offset;
12628                 }
12629         }
12630
12631         cfg->jit_info = jinfo;
12632 #if defined(__arm__)
12633         mono_arch_fixup_jinfo (cfg);
12634 #endif
12635
12636         mono_domain_lock (cfg->domain);
12637         mono_jit_info_table_add (cfg->domain, jinfo);
12638
12639         if (cfg->method->dynamic)
12640                 mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = jinfo;
12641         mono_domain_unlock (cfg->domain);
12642
12643         /* collect statistics */
12644         mono_jit_stats.allocated_code_size += cfg->code_len;
12645         code_size_ratio = cfg->code_len;
12646         if (code_size_ratio > mono_jit_stats.biggest_method_size && mono_jit_stats.enabled) {
12647                 mono_jit_stats.biggest_method_size = code_size_ratio;
12648                 g_free (mono_jit_stats.biggest_method);
12649                 mono_jit_stats.biggest_method = g_strdup_printf ("%s::%s)", method->klass->name, method->name);
12650         }
12651         code_size_ratio = (code_size_ratio * 100) / mono_method_get_header (method)->code_size;
12652         if (code_size_ratio > mono_jit_stats.max_code_size_ratio && mono_jit_stats.enabled) {
12653                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
12654                 g_free (mono_jit_stats.max_ratio_method);
12655                 mono_jit_stats.max_ratio_method = g_strdup_printf ("%s::%s)", method->klass->name, method->name);
12656         }
12657         mono_jit_stats.native_code_size += cfg->code_len;
12658
12659         if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
12660                 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
12661         if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
12662                 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
12663
12664         return cfg;
12665 }
12666
12667 static MonoJitInfo*
12668 lookup_generic_method (MonoDomain *domain, MonoMethod *method)
12669 {
12670         MonoMethod *open_method;
12671
12672         if (!mono_method_is_generic_sharable_impl (method, FALSE))
12673                 return NULL;
12674
12675         open_method = mono_method_get_declaring_generic_method (method);
12676
12677         return mono_domain_lookup_shared_generic (domain, open_method);
12678 }
12679
12680 /*
12681  * LOCKING: Assumes domain->jit_code_hash_lock is held.
12682  */
12683 static MonoJitInfo*
12684 lookup_method_inner (MonoDomain *domain, MonoMethod *method)
12685 {
12686         MonoJitInfo *ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, method);
12687
12688         if (ji)
12689                 return ji;
12690
12691         return lookup_generic_method (domain, method);
12692 }
12693
12694 static MonoJitInfo*
12695 lookup_method (MonoDomain *domain, MonoMethod *method)
12696 {
12697         MonoJitInfo *info;
12698
12699         mono_domain_jit_code_hash_lock (domain);
12700         info = lookup_method_inner (domain, method);
12701         mono_domain_jit_code_hash_unlock (domain);
12702
12703         return info;
12704 }
12705
12706 static gpointer
12707 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt)
12708 {
12709         MonoCompile *cfg;
12710         gpointer code = NULL;
12711         MonoJitInfo *info;
12712         MonoVTable *vtable;
12713
12714 #ifdef MONO_USE_AOT_COMPILER
12715         if ((opt & MONO_OPT_AOT) && !(mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)) {
12716                 MonoDomain *domain = mono_domain_get ();
12717
12718                 mono_class_init (method->klass);
12719
12720                 mono_domain_lock (domain);
12721                 if ((code = mono_aot_get_method (domain, method))) {
12722                         mono_domain_unlock (domain);
12723                         vtable = mono_class_vtable (domain, method->klass);
12724                         g_assert (vtable);
12725                         mono_runtime_class_init (vtable);
12726                         return code;
12727                 }
12728
12729                 mono_domain_unlock (domain);
12730         }
12731 #endif
12732
12733         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
12734             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
12735                 MonoMethod *nm;
12736                 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
12737
12738                 if (!piinfo->addr) {
12739                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
12740                                 piinfo->addr = mono_lookup_internal_call (method);
12741                         else if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
12742 #ifdef PLATFORM_WIN32
12743                                 g_warning ("Method '%s' in assembly '%s' contains native code that cannot be executed by Mono in modules loaded from byte arrays. The assembly was probably created using C++/CLI.\n", mono_method_full_name (method, TRUE), method->klass->image->name);
12744 #else
12745                                 g_warning ("Method '%s' in assembly '%s' contains native code that cannot be executed by Mono on this platform. The assembly was probably created using C++/CLI.\n", mono_method_full_name (method, TRUE), method->klass->image->name);
12746 #endif
12747                         else
12748                                 mono_lookup_pinvoke_call (method, NULL, NULL);
12749                 }
12750                         nm = mono_marshal_get_native_wrapper (method, check_for_pending_exc);
12751                         return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12752
12753                         //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE) 
12754                         //mono_debug_add_wrapper (method, nm);
12755         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
12756                 const char *name = method->name;
12757                 MonoMethod *nm;
12758
12759                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
12760                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
12761                                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name ("mono_delegate_ctor");
12762                                 g_assert (mi);
12763                                 return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper (mi));
12764                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
12765 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
12766                                 return mono_create_delegate_trampoline (method->klass);
12767 #else
12768                                 nm = mono_marshal_get_delegate_invoke (method, NULL);
12769                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12770 #endif
12771                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
12772                                 nm = mono_marshal_get_delegate_begin_invoke (method);
12773                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12774                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
12775                                 nm = mono_marshal_get_delegate_end_invoke (method);
12776                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12777                         }
12778                 }
12779                 return NULL;
12780         }
12781
12782         if (mono_aot_only)
12783                 g_error ("Attempting to JIT compile method '%s' while running with --aot-only.\n", mono_method_full_name (method, TRUE));
12784
12785         cfg = mini_method_compile (method, opt, target_domain, TRUE, FALSE, 0);
12786
12787         switch (cfg->exception_type) {
12788         case MONO_EXCEPTION_NONE: break;
12789         case MONO_EXCEPTION_TYPE_LOAD:
12790         case MONO_EXCEPTION_MISSING_FIELD:
12791         case MONO_EXCEPTION_MISSING_METHOD:
12792         case MONO_EXCEPTION_FILE_NOT_FOUND: {
12793                 /* Throw a type load exception if needed */
12794                 MonoLoaderError *error = mono_loader_get_last_error ();
12795                 MonoException *ex;
12796
12797                 if (error) {
12798                         ex = mono_loader_error_prepare_exception (error);
12799                 } else {
12800                         if (cfg->exception_ptr) {
12801                                 ex = mono_class_get_exception_for_failure (cfg->exception_ptr);
12802                         } else {
12803                                 if (cfg->exception_type == MONO_EXCEPTION_MISSING_FIELD)
12804                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingFieldException", cfg->exception_message);
12805                                 else if (cfg->exception_type == MONO_EXCEPTION_MISSING_METHOD)
12806                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingMethodException", cfg->exception_message);
12807                                 else if (cfg->exception_type == MONO_EXCEPTION_TYPE_LOAD)
12808                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "TypeLoadException", cfg->exception_message);
12809                                 else if (cfg->exception_type == MONO_EXCEPTION_FILE_NOT_FOUND)
12810                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FileNotFoundException", cfg->exception_message);
12811                                 else
12812                                         g_assert_not_reached ();
12813                         }
12814                 }
12815                 mono_destroy_compile (cfg);
12816                 mono_raise_exception (ex);
12817                 break;
12818         }
12819         case MONO_EXCEPTION_INVALID_PROGRAM: {
12820                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", cfg->exception_message);
12821                 mono_destroy_compile (cfg);
12822                 mono_raise_exception (ex);
12823                 break;
12824         }
12825         case MONO_EXCEPTION_UNVERIFIABLE_IL: {
12826                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.Security", "VerificationException", cfg->exception_message);
12827                 mono_destroy_compile (cfg);
12828                 mono_raise_exception (ex);
12829                 break;
12830         }
12831         case MONO_EXCEPTION_METHOD_ACCESS: {
12832                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MethodAccessException", cfg->exception_message);
12833                 mono_destroy_compile (cfg);
12834                 mono_raise_exception (ex);
12835                 break;
12836         }
12837         case MONO_EXCEPTION_FIELD_ACCESS: {
12838                 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FieldAccessException", cfg->exception_message);
12839                 mono_destroy_compile (cfg);
12840                 mono_raise_exception (ex);
12841                 break;
12842         }
12843         /* this can only be set if the security manager is active */
12844         case MONO_EXCEPTION_SECURITY_LINKDEMAND: {
12845                 MonoSecurityManager* secman = mono_security_manager_get_methods ();
12846                 MonoObject *exc = NULL;
12847                 gpointer args [2];
12848
12849                 args [0] = &cfg->exception_data;
12850                 args [1] = &method;
12851                 mono_runtime_invoke (secman->linkdemandsecurityexception, NULL, args, &exc);
12852
12853                 mono_destroy_compile (cfg);
12854                 cfg = NULL;
12855
12856                 mono_raise_exception ((MonoException*)exc);
12857         }
12858         default:
12859                 g_assert_not_reached ();
12860         }
12861
12862         mono_domain_lock (target_domain);
12863
12864         /* Check if some other thread already did the job. In this case, we can
12865        discard the code this thread generated. */
12866
12867         mono_domain_jit_code_hash_lock (target_domain);
12868
12869         info = lookup_method_inner (target_domain, method);
12870         if (info) {
12871                 /* We can't use a domain specific method in another domain */
12872                 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
12873                         code = info->code_start;
12874 //                      printf("Discarding code for method %s\n", method->name);
12875                 }
12876         }
12877         
12878         if (code == NULL) {
12879                 mono_internal_hash_table_insert (&target_domain->jit_code_hash, cfg->jit_info->method, cfg->jit_info);
12880                 mono_domain_jit_code_hash_unlock (target_domain);
12881                 code = cfg->native_code;
12882
12883                 if (cfg->generic_sharing_context && mono_method_is_generic_sharable_impl (method, FALSE)) {
12884                         /* g_print ("inserting method %s.%s.%s\n", method->klass->name_space, method->klass->name, method->name); */
12885                         mono_domain_register_shared_generic (target_domain, 
12886                                 mono_method_get_declaring_generic_method (method), cfg->jit_info);
12887                         mono_stats.generics_shared_methods++;
12888                 }
12889         } else {
12890                 mono_domain_jit_code_hash_unlock (target_domain);
12891         }
12892
12893         mono_destroy_compile (cfg);
12894
12895         if (target_domain->jump_target_hash) {
12896                 MonoJumpInfo patch_info;
12897                 GSList *list, *tmp;
12898                 list = g_hash_table_lookup (target_domain->jump_target_hash, method);
12899                 if (list) {
12900                         patch_info.next = NULL;
12901                         patch_info.ip.i = 0;
12902                         patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
12903                         patch_info.data.method = method;
12904                         g_hash_table_remove (target_domain->jump_target_hash, method);
12905                 }
12906                 for (tmp = list; tmp; tmp = tmp->next)
12907                         mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info, TRUE);
12908                 g_slist_free (list);
12909         }
12910
12911         mono_domain_unlock (target_domain);
12912
12913         vtable = mono_class_vtable (target_domain, method->klass);
12914         if (!vtable) {
12915                 MonoException *exc;
12916                 exc = mono_class_get_exception_for_failure (method->klass);
12917                 g_assert (exc);
12918                 mono_raise_exception (exc);
12919         }
12920         mono_runtime_class_init (vtable);
12921         return code;
12922 }
12923
12924 static gpointer
12925 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt)
12926 {
12927         MonoDomain *target_domain, *domain = mono_domain_get ();
12928         MonoJitInfo *info;
12929         gpointer p;
12930         MonoJitICallInfo *callinfo = NULL;
12931
12932         /*
12933          * ICALL wrappers are handled specially, since there is only one copy of them
12934          * shared by all appdomains.
12935          */
12936         if ((method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (strstr (method->name, "__icall_wrapper_") == method->name)) {
12937                 const char *icall_name;
12938
12939                 icall_name = method->name + strlen ("__icall_wrapper_");
12940                 g_assert (icall_name);
12941                 callinfo = mono_find_jit_icall_by_name (icall_name);
12942                 g_assert (callinfo);
12943
12944                 /* Must be domain neutral since there is only one copy */
12945                 opt |= MONO_OPT_SHARED;
12946         }
12947
12948         if (opt & MONO_OPT_SHARED)
12949                 target_domain = mono_get_root_domain ();
12950         else 
12951                 target_domain = domain;
12952
12953         info = lookup_method (target_domain, method);
12954         if (info) {
12955                 /* We can't use a domain specific method in another domain */
12956                 if (! ((domain != target_domain) && !info->domain_neutral)) {
12957                         MonoVTable *vtable;
12958
12959                         mono_jit_stats.methods_lookups++;
12960                         vtable = mono_class_vtable (domain, method->klass);
12961                         mono_runtime_class_init (vtable);
12962                         return mono_create_ftnptr (target_domain, info->code_start);
12963                 }
12964         }
12965
12966         p = mono_create_ftnptr (target_domain, mono_jit_compile_method_inner (method, target_domain, opt));
12967
12968         if (callinfo) {
12969                 mono_jit_lock ();
12970                 if (!callinfo->wrapper) {
12971                         callinfo->wrapper = p;
12972                         mono_register_jit_icall_wrapper (callinfo, p);
12973                         mono_debug_add_icall_wrapper (method, callinfo);
12974                 }
12975                 mono_jit_unlock ();
12976         }
12977
12978         return p;
12979 }
12980
12981 static gpointer
12982 mono_jit_compile_method (MonoMethod *method)
12983 {
12984         return mono_jit_compile_method_with_opt (method, default_opt);
12985 }
12986
12987 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
12988 static void
12989 invalidated_delegate_trampoline (char *desc)
12990 {
12991         g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
12992                  "See http://www.go-mono.com/delegate.html for an explanation and ways to fix this.",
12993                  desc);
12994 }
12995 #endif
12996
12997 /*
12998  * mono_jit_free_method:
12999  *
13000  *  Free all memory allocated by the JIT for METHOD.
13001  */
13002 static void
13003 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
13004 {
13005         MonoJitDynamicMethodInfo *ji;
13006         gboolean destroy = TRUE;
13007
13008         g_assert (method->dynamic);
13009
13010         mono_domain_lock (domain);
13011         ji = mono_dynamic_code_hash_lookup (domain, method);
13012         mono_domain_unlock (domain);
13013
13014         if (!ji)
13015                 return;
13016         mono_domain_lock (domain);
13017         g_hash_table_remove (domain->dynamic_code_hash, method);
13018         mono_internal_hash_table_remove (&domain->jit_code_hash, method);
13019         g_hash_table_remove (domain->jump_trampoline_hash, method);
13020         mono_domain_unlock (domain);
13021
13022 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
13023         if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
13024                 /*
13025                  * Instead of freeing the code, change it to call an error routine
13026                  * so people can fix their code.
13027                  */
13028                 char *type = mono_type_full_name (&method->klass->byval_arg);
13029                 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
13030
13031                 g_free (type);
13032                 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
13033                 destroy = FALSE;
13034         }
13035 #endif
13036
13037         /* 
13038          * This needs to be done before freeing code_mp, since the code address is the
13039          * key in the table, so if we free the code_mp first, another thread can grab the
13040          * same code address and replace our entry in the table.
13041          */
13042         mono_jit_info_table_remove (domain, ji->ji);
13043
13044         if (destroy)
13045                 mono_code_manager_destroy (ji->code_mp);
13046         g_free (ji);
13047 }
13048
13049 gpointer
13050 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
13051 {
13052         MonoDomain *target_domain;
13053         MonoJitInfo *info;
13054
13055         if (default_opt & MONO_OPT_SHARED)
13056                 target_domain = mono_get_root_domain ();
13057         else 
13058                 target_domain = domain;
13059
13060         info = lookup_method (target_domain, method);
13061         if (info) {
13062                 /* We can't use a domain specific method in another domain */
13063                 if (! ((domain != target_domain) && !info->domain_neutral)) {
13064                         mono_jit_stats.methods_lookups++;
13065                         return info->code_start;
13066                 }
13067         }
13068
13069         return NULL;
13070 }
13071
13072 /**
13073  * mono_jit_runtime_invoke:
13074  * @method: the method to invoke
13075  * @obj: this pointer
13076  * @params: array of parameter values.
13077  * @exc: used to catch exceptions objects
13078  */
13079 static MonoObject*
13080 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
13081 {
13082         MonoMethod *to_compile;
13083         MonoMethod *invoke;
13084         MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
13085         void* compiled_method;
13086         MonoVTable *vtable;
13087
13088         if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
13089                 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
13090                 return NULL;
13091         }
13092
13093         if (((method->flags & METHOD_ATTRIBUTE_STATIC) ||
13094                                 (method->is_inflated && mono_method_get_context (method)->method_inst)) &&
13095                         mono_class_generic_sharing_enabled (method->klass) &&
13096                         mono_method_is_generic_sharable_impl (method, FALSE)) {
13097                 to_compile = mono_marshal_get_static_rgctx_invoke (method);
13098         } else {
13099                 to_compile = method;
13100         }
13101
13102         invoke = mono_marshal_get_runtime_invoke (method);
13103         runtime_invoke = mono_jit_compile_method (invoke);
13104         
13105         /* We need this here becuase mono_marshal_get_runtime_invoke can be place 
13106          * the helper method in System.Object and not the target class
13107          */
13108         vtable = mono_class_vtable (mono_domain_get (), method->klass);
13109         g_assert (vtable);
13110         mono_runtime_class_init (vtable);
13111
13112         if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
13113                 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
13114                 /* 
13115                  * Array Get/Set/Address methods. The JIT implements them using inline code 
13116                  * inside the runtime invoke wrappers, so no need to compile them.
13117                  */
13118                 compiled_method = NULL;
13119         } else {
13120                 compiled_method = mono_jit_compile_method (to_compile);
13121         }
13122         return runtime_invoke (obj, params, exc, compiled_method);
13123 }
13124
13125 #ifdef MONO_GET_CONTEXT
13126 #define GET_CONTEXT MONO_GET_CONTEXT
13127 #endif
13128
13129 #ifndef GET_CONTEXT
13130 #ifdef PLATFORM_WIN32
13131 #define GET_CONTEXT \
13132         struct sigcontext *ctx = (struct sigcontext*)_dummy;
13133 #else
13134 #ifdef MONO_ARCH_USE_SIGACTION
13135 #define GET_CONTEXT \
13136     void *ctx = context;
13137 #elif defined(__sparc__)
13138 #define GET_CONTEXT \
13139     void *ctx = sigctx;
13140 #else
13141 #define GET_CONTEXT \
13142         void **_p = (void **)&_dummy; \
13143         struct sigcontext *ctx = (struct sigcontext *)++_p;
13144 #endif
13145 #endif
13146 #endif
13147
13148 #ifdef MONO_ARCH_USE_SIGACTION
13149 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, siginfo_t *info, void *context)
13150 #elif defined(__sparc__)
13151 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, void *sigctx)
13152 #else
13153 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy)
13154 #endif
13155
13156 static void
13157 SIG_HANDLER_SIGNATURE (sigfpe_signal_handler)
13158 {
13159         MonoException *exc = NULL;
13160 #ifndef MONO_ARCH_USE_SIGACTION
13161         void *info = NULL;
13162 #endif
13163         GET_CONTEXT;
13164
13165 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
13166         if (mono_arch_is_int_overflow (ctx, info))
13167                 exc = mono_get_exception_arithmetic ();
13168         else
13169                 exc = mono_get_exception_divide_by_zero ();
13170 #else
13171         exc = mono_get_exception_divide_by_zero ();
13172 #endif
13173         
13174         mono_arch_handle_exception (ctx, exc, FALSE);
13175 }
13176
13177 static void
13178 SIG_HANDLER_SIGNATURE (sigill_signal_handler)
13179 {
13180         MonoException *exc;
13181         GET_CONTEXT;
13182
13183         exc = mono_get_exception_execution_engine ("SIGILL");
13184         
13185         mono_arch_handle_exception (ctx, exc, FALSE);
13186 }
13187
13188 static void
13189 SIG_HANDLER_SIGNATURE (sigsegv_signal_handler)
13190 {
13191 #ifndef MONO_ARCH_SIGSEGV_ON_ALTSTACK
13192         MonoException *exc = NULL;
13193 #endif
13194         MonoJitInfo *ji;
13195
13196 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
13197         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
13198 #endif
13199         GET_CONTEXT;
13200
13201 #ifdef MONO_ARCH_USE_SIGACTION
13202         if (debug_options.collect_pagefault_stats) {
13203                 if (mono_raw_buffer_is_pagefault (info->si_addr)) {
13204                         mono_raw_buffer_handle_pagefault (info->si_addr);
13205                         return;
13206                 }
13207                 if (mono_aot_is_pagefault (info->si_addr)) {
13208                         mono_aot_handle_pagefault (info->si_addr);
13209                         return;
13210                 }
13211         }
13212 #endif
13213
13214         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (ctx));
13215
13216 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
13217         /* we got a stack overflow in the soft-guard pages
13218          * There are two cases:
13219          * 1) managed code caused the overflow: we unprotect the soft-guard page
13220          * and let the arch-specific code trigger the exception handling mechanism
13221          * in the thread stack. The soft-guard pages will be protected again as the stack is unwound.
13222          * 2) unmanaged code caused the overflow: we unprotect the soft-guard page
13223          * and hope we can continue with those enabled, at least until the hard-guard page
13224          * is hit. The alternative to continuing here is to just print a message and abort.
13225          * We may add in the future the code to protect the pages again in the codepath
13226          * when we return from unmanaged to managed code.
13227          */
13228         if (jit_tls->stack_ovf_guard_size && (guint8*)info->si_addr >= (guint8*)jit_tls->stack_ovf_guard_base &&
13229                         (guint8*)info->si_addr < (guint8*)jit_tls->stack_ovf_guard_base + jit_tls->stack_ovf_guard_size) {
13230                 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
13231                 if (ji) {
13232                         mono_arch_handle_altstack_exception (ctx, info->si_addr, TRUE);
13233                 } else {
13234                         /* We print a message: after this even managed stack overflows
13235                          * may crash the runtime
13236                          */
13237                         fprintf (stderr, "Stack overflow in unmanaged: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
13238                 }
13239                 return;
13240         }
13241         /* The hard-guard page has been hit: there is not much we can do anymore
13242          * Print a hopefully clear message and abort.
13243          */
13244         if (jit_tls->stack_size && 
13245                         ABS ((guint8*)info->si_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 32768) {
13246                 const char *method;
13247                 /* we don't do much now, but we can warn the user with a useful message */
13248                 fprintf (stderr, "Stack overflow: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
13249                 if (ji && ji->method)
13250                         method = mono_method_full_name (ji->method, TRUE);
13251                 else
13252                         method = "Unmanaged";
13253                 fprintf (stderr, "At %s\n", method);
13254                 abort ();
13255         } else {
13256                 mono_arch_handle_altstack_exception (ctx, info->si_addr, FALSE);
13257         }
13258 #else
13259
13260         if (!ji) {
13261                 mono_handle_native_sigsegv (SIGSEGV, ctx);
13262         }
13263                         
13264         mono_arch_handle_exception (ctx, exc, FALSE);
13265 #endif
13266 }
13267
13268 #ifndef PLATFORM_WIN32
13269
13270 static void
13271 SIG_HANDLER_SIGNATURE (sigabrt_signal_handler)
13272 {
13273         MonoJitInfo *ji;
13274         GET_CONTEXT;
13275
13276         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
13277         if (!ji) {
13278                 mono_handle_native_sigsegv (SIGABRT, ctx);
13279         }
13280 }
13281
13282 static void
13283 SIG_HANDLER_SIGNATURE (sigusr1_signal_handler)
13284 {
13285         gboolean running_managed;
13286         MonoException *exc;
13287         MonoThread *thread = mono_thread_current ();
13288         void *ji;
13289         
13290         GET_CONTEXT;
13291
13292         if (thread->thread_dump_requested) {
13293                 thread->thread_dump_requested = FALSE;
13294
13295                 mono_print_thread_dump (ctx);
13296         }
13297
13298         /*
13299          * FIXME:
13300          * This is an async signal, so the code below must not call anything which
13301          * is not async safe. That includes the pthread locking functions. If we
13302          * know that we interrupted managed code, then locking is safe.
13303          */
13304         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
13305         running_managed = ji != NULL;
13306         
13307         exc = mono_thread_request_interruption (running_managed); 
13308         if (!exc) return;
13309
13310         mono_arch_handle_exception (ctx, exc, FALSE);
13311 }
13312
13313 #if defined(__i386__) || defined(__x86_64__)
13314 #define FULL_STAT_PROFILER_BACKTRACE 1
13315 #define CURRENT_FRAME_GET_BASE_POINTER(f) (* (gpointer*)(f))
13316 #define CURRENT_FRAME_GET_RETURN_ADDRESS(f) (* (((gpointer*)(f)) + 1))
13317 #if MONO_ARCH_STACK_GROWS_UP
13318 #define IS_BEFORE_ON_STACK <
13319 #define IS_AFTER_ON_STACK >
13320 #else
13321 #define IS_BEFORE_ON_STACK >
13322 #define IS_AFTER_ON_STACK <
13323 #endif
13324 #else
13325 #define FULL_STAT_PROFILER_BACKTRACE 0
13326 #endif
13327
13328 #if defined(__ia64__) || defined(__sparc__) || defined(sparc) || defined(__s390__) || defined(s390)
13329
13330 static void
13331 SIG_HANDLER_SIGNATURE (sigprof_signal_handler)
13332 {
13333         NOT_IMPLEMENTED;
13334 }
13335
13336 #else
13337
13338 static void
13339 SIG_HANDLER_SIGNATURE (sigprof_signal_handler)
13340 {
13341         int call_chain_depth = mono_profiler_stat_get_call_chain_depth ();
13342         GET_CONTEXT;
13343         
13344         if (call_chain_depth == 0) {
13345                 mono_profiler_stat_hit (mono_arch_ip_from_context (ctx), ctx);
13346         } else {
13347                 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
13348                 int current_frame_index = 1;
13349                 MonoContext mono_context;
13350 #if FULL_STAT_PROFILER_BACKTRACE
13351                 guchar *current_frame;
13352                 guchar *stack_bottom;
13353                 guchar *stack_top;
13354 #else
13355                 MonoDomain *domain;
13356 #endif
13357                 guchar *ips [call_chain_depth + 1];
13358
13359                 mono_arch_sigctx_to_monoctx (ctx, &mono_context);
13360                 ips [0] = MONO_CONTEXT_GET_IP (&mono_context);
13361                 
13362                 if (jit_tls != NULL) {
13363 #if FULL_STAT_PROFILER_BACKTRACE
13364                         stack_bottom = jit_tls->end_of_stack;
13365                         stack_top = MONO_CONTEXT_GET_SP (&mono_context);
13366                         current_frame = MONO_CONTEXT_GET_BP (&mono_context);
13367                         
13368                         while ((current_frame_index <= call_chain_depth) &&
13369                                         (stack_bottom IS_BEFORE_ON_STACK (guchar*) current_frame) &&
13370                                         ((guchar*) current_frame IS_BEFORE_ON_STACK stack_top)) {
13371                                 ips [current_frame_index] = CURRENT_FRAME_GET_RETURN_ADDRESS (current_frame);
13372                                 current_frame_index ++;
13373                                 stack_top = current_frame;
13374                                 current_frame = CURRENT_FRAME_GET_BASE_POINTER (current_frame);
13375                         }
13376 #else
13377                         domain = mono_domain_get ();
13378                         if (domain != NULL) {
13379                                 MonoLMF *lmf = NULL;
13380                                 MonoJitInfo *ji;
13381                                 MonoJitInfo res;
13382                                 MonoContext new_mono_context;
13383                                 int native_offset;
13384                                 ji = mono_arch_find_jit_info (domain, jit_tls, &res, NULL, &mono_context,
13385                                                 &new_mono_context, NULL, &lmf, &native_offset, NULL);
13386                                 while ((ji != NULL) && (current_frame_index <= call_chain_depth)) {
13387                                         ips [current_frame_index] = MONO_CONTEXT_GET_IP (&new_mono_context);
13388                                         current_frame_index ++;
13389                                         mono_context = new_mono_context;
13390                                         ji = mono_arch_find_jit_info (domain, jit_tls, &res, NULL, &mono_context,
13391                                                         &new_mono_context, NULL, &lmf, &native_offset, NULL);
13392                                 }
13393                         }
13394 #endif
13395                 }
13396                 
13397                 
13398                 mono_profiler_stat_call_chain (current_frame_index, & ips [0], ctx);
13399         }
13400 }
13401
13402 #endif
13403
13404 static void
13405 SIG_HANDLER_SIGNATURE (sigquit_signal_handler)
13406 {
13407         GET_CONTEXT;
13408
13409         printf ("Full thread dump:\n");
13410
13411         mono_threads_request_thread_dump ();
13412
13413         /*
13414          * print_thread_dump () skips the current thread, since sending a signal
13415          * to it would invoke the signal handler below the sigquit signal handler,
13416          * and signal handlers don't create an lmf, so the stack walk could not
13417          * be performed.
13418          */
13419         mono_print_thread_dump (ctx);
13420 }
13421
13422 static void
13423 SIG_HANDLER_SIGNATURE (sigusr2_signal_handler)
13424 {
13425         gboolean enabled = mono_trace_is_enabled ();
13426
13427         mono_trace_enable (!enabled);
13428 }
13429
13430 #endif
13431
13432 static void
13433 SIG_HANDLER_SIGNATURE (sigint_signal_handler)
13434 {
13435         MonoException *exc;
13436         GET_CONTEXT;
13437
13438         exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
13439         
13440         mono_arch_handle_exception (ctx, exc, FALSE);
13441 }
13442
13443 #ifdef PLATFORM_MACOSX
13444
13445 /*
13446  * This code disables the CrashReporter of MacOS X by installing
13447  * a dummy Mach exception handler.
13448  */
13449
13450 /*
13451  * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/exc_server.html
13452  */
13453 extern
13454 boolean_t
13455 exc_server (mach_msg_header_t *request_msg,
13456             mach_msg_header_t *reply_msg);
13457
13458 /*
13459  * The exception message
13460  */
13461 typedef struct {
13462         mach_msg_base_t msg;  /* common mach message header */
13463         char payload [1024];  /* opaque */
13464 } mach_exception_msg_t;
13465
13466 /* The exception port */
13467 static mach_port_t mach_exception_port = VM_MAP_NULL;
13468
13469 /*
13470  * Implicitly called by exc_server. Must be public.
13471  *
13472  * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/catch_exception_raise.html
13473  */
13474 kern_return_t
13475 catch_exception_raise (
13476         mach_port_t exception_port,
13477         mach_port_t thread,
13478         mach_port_t task,
13479         exception_type_t exception,
13480         exception_data_t code,
13481         mach_msg_type_number_t code_count)
13482 {
13483         /* consume the exception */
13484         return KERN_FAILURE;
13485 }
13486
13487 /*
13488  * Exception thread handler.
13489  */
13490 static
13491 void *
13492 mach_exception_thread (void *arg)
13493 {
13494         for (;;) {
13495                 mach_exception_msg_t request;
13496                 mach_exception_msg_t reply;
13497                 mach_msg_return_t result;
13498
13499                 /* receive from "mach_exception_port" */
13500                 result = mach_msg (&request.msg.header,
13501                                    MACH_RCV_MSG | MACH_RCV_LARGE,
13502                                    0,
13503                                    sizeof (request),
13504                                    mach_exception_port,
13505                                    MACH_MSG_TIMEOUT_NONE,
13506                                    MACH_PORT_NULL);
13507
13508                 g_assert (result == MACH_MSG_SUCCESS);
13509
13510                 /* dispatch to catch_exception_raise () */
13511                 exc_server (&request.msg.header, &reply.msg.header);
13512
13513                 /* send back to sender */
13514                 result = mach_msg (&reply.msg.header,
13515                                    MACH_SEND_MSG,
13516                                    reply.msg.header.msgh_size,
13517                                    0,
13518                                    MACH_PORT_NULL,
13519                                    MACH_MSG_TIMEOUT_NONE,
13520                                    MACH_PORT_NULL);
13521
13522                 g_assert (result == MACH_MSG_SUCCESS);
13523         }
13524         return NULL;
13525 }
13526
13527 static void
13528 macosx_register_exception_handler ()
13529 {
13530         mach_port_t task;
13531         pthread_attr_t attr;
13532         pthread_t thread;
13533
13534         if (mach_exception_port != VM_MAP_NULL)
13535                 return;
13536
13537         task = mach_task_self ();
13538
13539         /* create the "mach_exception_port" with send & receive rights */
13540         g_assert (mach_port_allocate (task, MACH_PORT_RIGHT_RECEIVE,
13541                                       &mach_exception_port) == KERN_SUCCESS);
13542         g_assert (mach_port_insert_right (task, mach_exception_port, mach_exception_port,
13543                                           MACH_MSG_TYPE_MAKE_SEND) == KERN_SUCCESS);
13544
13545         /* create the exception handler thread */
13546         g_assert (!pthread_attr_init (&attr));
13547         g_assert (!pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED));
13548         g_assert (!pthread_create (&thread, &attr, mach_exception_thread, NULL));
13549         pthread_attr_destroy (&attr);
13550
13551         /*
13552          * register "mach_exception_port" as a receiver for the
13553          * EXC_BAD_ACCESS exception
13554          *
13555          * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/task_set_exception_ports.html
13556          */
13557         g_assert (task_set_exception_ports (task, EXC_MASK_BAD_ACCESS,
13558                                             mach_exception_port,
13559                                             EXCEPTION_DEFAULT,
13560                                             MACHINE_THREAD_STATE) == KERN_SUCCESS);
13561 }
13562 #endif
13563
13564 #ifndef PLATFORM_WIN32
13565 static void
13566 add_signal_handler (int signo, gpointer handler)
13567 {
13568         struct sigaction sa;
13569
13570 #ifdef MONO_ARCH_USE_SIGACTION
13571         sa.sa_sigaction = handler;
13572         sigemptyset (&sa.sa_mask);
13573         sa.sa_flags = SA_SIGINFO;
13574 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
13575         if (signo == SIGSEGV)
13576                 sa.sa_flags |= SA_ONSTACK;
13577 #endif
13578 #else
13579         sa.sa_handler = handler;
13580         sigemptyset (&sa.sa_mask);
13581         sa.sa_flags = 0;
13582 #endif
13583         g_assert (sigaction (signo, &sa, NULL) != -1);
13584 }
13585
13586 static void
13587 remove_signal_handler (int signo)
13588 {
13589         struct sigaction sa;
13590
13591         sa.sa_handler = SIG_DFL;
13592         sigemptyset (&sa.sa_mask);
13593         sa.sa_flags = 0;
13594
13595         g_assert (sigaction (signo, &sa, NULL) != -1);
13596 }
13597 #endif
13598
13599 static void
13600 mono_runtime_install_handlers (void)
13601 {
13602 #ifdef PLATFORM_WIN32
13603         win32_seh_init();
13604         win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
13605         win32_seh_set_handler(SIGILL, sigill_signal_handler);
13606         win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
13607         if (debug_options.handle_sigint)
13608                 win32_seh_set_handler(SIGINT, sigint_signal_handler);
13609
13610 #else /* !PLATFORM_WIN32 */
13611
13612
13613 #ifdef PLATFORM_MACOSX
13614         macosx_register_exception_handler ();
13615 #endif
13616
13617         if (debug_options.handle_sigint)
13618                 add_signal_handler (SIGINT, sigint_signal_handler);
13619
13620         add_signal_handler (SIGFPE, sigfpe_signal_handler);
13621         add_signal_handler (SIGQUIT, sigquit_signal_handler);
13622         add_signal_handler (SIGILL, sigill_signal_handler);
13623         add_signal_handler (SIGBUS, sigsegv_signal_handler);
13624         if (mono_jit_trace_calls != NULL)
13625                 add_signal_handler (SIGUSR2, sigusr2_signal_handler);
13626
13627         add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
13628         signal (SIGPIPE, SIG_IGN);
13629
13630         add_signal_handler (SIGABRT, sigabrt_signal_handler);
13631
13632         /* catch SIGSEGV */
13633         add_signal_handler (SIGSEGV, sigsegv_signal_handler);
13634 #endif /* PLATFORM_WIN32 */
13635 }
13636
13637 static void
13638 mono_runtime_cleanup_handlers (void)
13639 {
13640 #ifdef PLATFORM_WIN32
13641         win32_seh_cleanup();
13642 #else
13643         if (debug_options.handle_sigint)
13644                 remove_signal_handler (SIGINT);
13645
13646         remove_signal_handler (SIGFPE);
13647         remove_signal_handler (SIGQUIT);
13648         remove_signal_handler (SIGILL);
13649         remove_signal_handler (SIGBUS);
13650         if (mono_jit_trace_calls != NULL)
13651                 remove_signal_handler (SIGUSR2);
13652
13653         remove_signal_handler (mono_thread_get_abort_signal ());
13654
13655         remove_signal_handler (SIGABRT);
13656
13657         remove_signal_handler (SIGSEGV);
13658 #endif /* PLATFORM_WIN32 */
13659 }
13660
13661
13662 #ifdef HAVE_LINUX_RTC_H
13663 #include <linux/rtc.h>
13664 #include <sys/ioctl.h>
13665 #include <fcntl.h>
13666 static int rtc_fd = -1;
13667
13668 static int
13669 enable_rtc_timer (gboolean enable)
13670 {
13671         int flags;
13672         flags = fcntl (rtc_fd, F_GETFL);
13673         if (flags < 0) {
13674                 perror ("getflags");
13675                 return 0;
13676         }
13677         if (enable)
13678                 flags |= FASYNC;
13679         else
13680                 flags &= ~FASYNC;
13681         if (fcntl (rtc_fd, F_SETFL, flags) == -1) {
13682                 perror ("setflags");
13683                 return 0;
13684         }
13685         return 1;
13686 }
13687 #endif
13688
13689 #ifdef PLATFORM_WIN32
13690 static HANDLE win32_main_thread;
13691 static MMRESULT win32_timer;
13692
13693 static void CALLBACK
13694 win32_time_proc (UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
13695 {
13696         CONTEXT context;
13697
13698         context.ContextFlags = CONTEXT_CONTROL;
13699         if (GetThreadContext (win32_main_thread, &context)) {
13700 #ifdef _WIN64
13701                 mono_profiler_stat_hit ((guchar *) context.Rip, &context);
13702 #else
13703                 mono_profiler_stat_hit ((guchar *) context.Eip, &context);
13704 #endif
13705         }
13706 }
13707 #endif
13708
13709 static void
13710 setup_stat_profiler (void)
13711 {
13712 #ifdef ITIMER_PROF
13713         struct itimerval itval;
13714         static int inited = 0;
13715 #ifdef HAVE_LINUX_RTC_H
13716         const char *rtc_freq;
13717         if (!inited && (rtc_freq = g_getenv ("MONO_RTC"))) {
13718                 int freq = 0;
13719                 inited = 1;
13720                 if (*rtc_freq)
13721                         freq = atoi (rtc_freq);
13722                 if (!freq)
13723                         freq = 1024;
13724                 rtc_fd = open ("/dev/rtc", O_RDONLY);
13725                 if (rtc_fd == -1) {
13726                         perror ("open /dev/rtc");
13727                         return;
13728                 }
13729                 add_signal_handler (SIGPROF, sigprof_signal_handler);
13730                 if (ioctl (rtc_fd, RTC_IRQP_SET, freq) == -1) {
13731                         perror ("set rtc freq");
13732                         return;
13733                 }
13734                 if (ioctl (rtc_fd, RTC_PIE_ON, 0) == -1) {
13735                         perror ("start rtc");
13736                         return;
13737                 }
13738                 if (fcntl (rtc_fd, F_SETSIG, SIGPROF) == -1) {
13739                         perror ("setsig");
13740                         return;
13741                 }
13742                 if (fcntl (rtc_fd, F_SETOWN, getpid ()) == -1) {
13743                         perror ("setown");
13744                         return;
13745                 }
13746                 enable_rtc_timer (TRUE);
13747                 return;
13748         }
13749         if (rtc_fd >= 0)
13750                 return;
13751 #endif
13752
13753         itval.it_interval.tv_usec = 999;
13754         itval.it_interval.tv_sec = 0;
13755         itval.it_value = itval.it_interval;
13756         setitimer (ITIMER_PROF, &itval, NULL);
13757         if (inited)
13758                 return;
13759         inited = 1;
13760         add_signal_handler (SIGPROF, sigprof_signal_handler);
13761 #elif defined (PLATFORM_WIN32)
13762         static int inited = 0;
13763         TIMECAPS timecaps;
13764
13765         if (inited)
13766                 return;
13767
13768         inited = 1;
13769         if (timeGetDevCaps (&timecaps, sizeof (timecaps)) != TIMERR_NOERROR)
13770                 return;
13771
13772         if ((win32_main_thread = OpenThread (READ_CONTROL | THREAD_GET_CONTEXT, FALSE, GetCurrentThreadId ())) == NULL)
13773                 return;
13774
13775         if (timeBeginPeriod (1) != TIMERR_NOERROR)
13776                 return;
13777
13778         if ((win32_timer = timeSetEvent (1, 0, win32_time_proc, 0, TIME_PERIODIC)) == 0) {
13779                 timeEndPeriod (1);
13780                 return;
13781         }
13782 #endif
13783 }
13784
13785 /* mono_jit_create_remoting_trampoline:
13786  * @method: pointer to the method info
13787  *
13788  * Creates a trampoline which calls the remoting functions. This
13789  * is used in the vtable of transparent proxies.
13790  * 
13791  * Returns: a pointer to the newly created code 
13792  */
13793 static gpointer
13794 mono_jit_create_remoting_trampoline (MonoMethod *method, MonoRemotingTarget target)
13795 {
13796         MonoMethod *nm;
13797         guint8 *addr = NULL;
13798
13799         if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || 
13800             (mono_method_signature (method)->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
13801                 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
13802                 addr = mono_compile_method (nm);
13803         } else {
13804                 addr = mono_compile_method (method);
13805         }
13806         return mono_get_addr_from_ftnptr (addr);
13807 }
13808
13809 #ifdef MONO_ARCH_HAVE_IMT
13810 static gpointer
13811 mini_get_imt_trampoline (void)
13812 {
13813         static gpointer tramp = NULL;
13814         if (!tramp)
13815                 tramp = mono_create_specific_trampoline (MONO_FAKE_IMT_METHOD, MONO_TRAMPOLINE_JIT, mono_get_root_domain (), NULL);
13816         return tramp;
13817 }
13818 #endif
13819
13820 #ifdef MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
13821 gpointer
13822 mini_get_vtable_trampoline (void)
13823 {
13824         static gpointer tramp = NULL;
13825         if (!tramp)
13826                 tramp = mono_create_specific_trampoline (MONO_FAKE_VTABLE_METHOD, MONO_TRAMPOLINE_JIT, mono_get_root_domain (), NULL);
13827         return tramp;
13828 }
13829 #endif
13830
13831 static void
13832 mini_parse_debug_options (void)
13833 {
13834         char *options = getenv ("MONO_DEBUG");
13835         gchar **args, **ptr;
13836         
13837         if (!options)
13838                 return;
13839
13840         args = g_strsplit (options, ",", -1);
13841
13842         for (ptr = args; ptr && *ptr; ptr++) {
13843                 const char *arg = *ptr;
13844
13845                 if (!strcmp (arg, "handle-sigint"))
13846                         debug_options.handle_sigint = TRUE;
13847                 else if (!strcmp (arg, "keep-delegates"))
13848                         debug_options.keep_delegates = TRUE;
13849                 else if (!strcmp (arg, "collect-pagefault-stats"))
13850                         debug_options.collect_pagefault_stats = TRUE;
13851                 else if (!strcmp (arg, "break-on-unverified"))
13852                         debug_options.break_on_unverified = TRUE;
13853                 else if (!strcmp (arg, "no-gdb-backtrace"))
13854                         debug_options.no_gdb_backtrace = TRUE;
13855                 else if (!strcmp (arg, "dont-free-domains"))
13856                         mono_dont_free_domains = TRUE;
13857                 else {
13858                         fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
13859                         fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'collect-pagefault-stats', 'break-on-unverified', 'no-gdb-backtrace', 'dont-free-domains'\n");
13860                         exit (1);
13861                 }
13862         }
13863 }
13864
13865 MonoDebugOptions *
13866 mini_get_debug_options (void)
13867 {
13868         return &debug_options;
13869 }
13870
13871 MonoDomain *
13872 mini_init (const char *filename, const char *runtime_version)
13873 {
13874         MonoDomain *domain;
13875
13876         MONO_PROBE_VES_INIT_BEGIN ();
13877
13878 #ifdef __linux__
13879         if (access ("/proc/self/maps", F_OK) != 0) {
13880                 g_print ("Mono requires /proc to be mounted.\n");
13881                 exit (1);
13882         }
13883 #endif
13884
13885         /* Happens when using the embedding interface */
13886         if (!default_opt_set)
13887                 default_opt = mono_parse_default_optimizations (NULL);
13888
13889         InitializeCriticalSection (&jit_mutex);
13890
13891         if (!global_codeman)
13892                 global_codeman = mono_code_manager_new ();
13893         jit_icall_name_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
13894
13895         mono_arch_cpu_init ();
13896
13897         mono_arch_init ();
13898
13899         mono_trampolines_init ();
13900
13901         if (!g_thread_supported ())
13902                 g_thread_init (NULL);
13903
13904         if (getenv ("MONO_DEBUG") != NULL)
13905                 mini_parse_debug_options ();
13906
13907         mono_gc_base_init ();
13908
13909         mono_jit_tls_id = TlsAlloc ();
13910         setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
13911
13912         mono_burg_init ();
13913
13914         if (default_opt & MONO_OPT_AOT)
13915                 mono_aot_init ();
13916
13917         mono_runtime_install_handlers ();
13918         mono_threads_install_cleanup (mini_thread_cleanup);
13919
13920 #ifdef MONO_ARCH_HAVE_NOTIFY_PENDING_EXC
13921         // This is experimental code so provide an env var to switch it off
13922         if (getenv ("MONO_DISABLE_PENDING_EXCEPTIONS")) {
13923                 printf ("MONO_DISABLE_PENDING_EXCEPTIONS env var set.\n");
13924         } else {
13925                 check_for_pending_exc = FALSE;
13926                 mono_threads_install_notify_pending_exc (mono_arch_notify_pending_exc);
13927         }
13928 #endif
13929
13930 #define JIT_TRAMPOLINES_WORK
13931 #ifdef JIT_TRAMPOLINES_WORK
13932         mono_install_compile_method (mono_jit_compile_method);
13933         mono_install_free_method (mono_jit_free_method);
13934         mono_install_trampoline (mono_create_jit_trampoline);
13935         mono_install_jump_trampoline (mono_create_jump_trampoline);
13936         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
13937         mono_install_delegate_trampoline (mono_create_delegate_trampoline);
13938 #endif
13939 #define JIT_INVOKE_WORKS
13940 #ifdef JIT_INVOKE_WORKS
13941         mono_install_runtime_invoke (mono_jit_runtime_invoke);
13942 #endif
13943         mono_install_stack_walk (mono_jit_walk_stack);
13944         mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
13945         mono_install_get_class_from_name (mono_aot_get_class_from_name);
13946         mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
13947
13948         if (debug_options.collect_pagefault_stats) {
13949                 mono_raw_buffer_set_make_unreadable (TRUE);
13950                 mono_aot_set_make_unreadable (TRUE);
13951         }
13952
13953         if (runtime_version)
13954                 domain = mono_init_version (filename, runtime_version);
13955         else
13956                 domain = mono_init_from_assembly (filename, filename);
13957
13958         if (mono_aot_only) {
13959                 /* The IMT tables are very dynamic thus they are hard to AOT */
13960                 mono_use_imt = FALSE;
13961                 /* This helps catch code allocation requests */
13962                 mono_code_manager_set_read_only (domain->code_mp);
13963         }
13964
13965 #ifdef MONO_ARCH_HAVE_IMT
13966         if (mono_use_imt) {
13967                 mono_install_imt_thunk_builder (mono_arch_build_imt_thunk);
13968                 mono_install_imt_trampoline (mini_get_imt_trampoline ());
13969 #if MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
13970                 mono_install_vtable_trampoline (mini_get_vtable_trampoline ());
13971 #endif
13972         }
13973 #endif
13974
13975         /* This must come after mono_init () in the aot-only case */
13976         mono_exceptions_init ();
13977         mono_install_handler (mono_get_throw_exception ());
13978
13979         mono_icall_init ();
13980
13981         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info", 
13982                                 ves_icall_get_frame_info);
13983         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace", 
13984                                 ves_icall_get_trace);
13985         mono_add_internal_call ("System.Exception::get_trace", 
13986                                 ves_icall_System_Exception_get_trace);
13987         mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityFrame",
13988                                 ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
13989         mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityStack",
13990                                 ves_icall_System_Security_SecurityFrame_GetSecurityStack);
13991         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers", 
13992                                 mono_runtime_install_handlers);
13993
13994
13995         create_helper_signature ();
13996
13997 #define JIT_CALLS_WORK
13998 #ifdef JIT_CALLS_WORK
13999         /* Needs to be called here since register_jit_icall depends on it */
14000         mono_marshal_init ();
14001
14002         mono_arch_register_lowlevel_calls ();
14003         register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
14004         register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
14005         register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
14006         register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
14007         register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
14008         register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "void", TRUE);
14009         register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
14010
14011         register_icall (mono_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
14012         register_icall (mono_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
14013         register_icall (mono_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", "void ptr", TRUE); 
14014 #if MONO_ARCH_HAVE_THROW_CORLIB_EXCEPTION
14015         register_icall (mono_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception", 
14016                                  "void ptr", TRUE);
14017 #endif
14018         register_icall (mono_thread_get_undeniable_exception, "mono_thread_get_undeniable_exception", "object", FALSE);
14019         register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "void", FALSE);
14020         register_icall (mono_thread_force_interruption_checkpoint, "mono_thread_force_interruption_checkpoint", "void", FALSE);
14021         register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
14022         register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
14023
14024         /* 
14025          * NOTE, NOTE, NOTE, NOTE:
14026          * when adding emulation for some opcodes, remember to also add a dummy
14027          * rule to the burg files, because we need the arity information to be correct.
14028          */
14029 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
14030         mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, TRUE);
14031         mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, FALSE);
14032         mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, FALSE);
14033         mono_register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, FALSE);
14034         mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, FALSE);
14035         mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, FALSE);
14036         mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, FALSE);
14037 #endif
14038
14039 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
14040         mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, TRUE);
14041         mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, TRUE);
14042         mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, TRUE);
14043 #endif
14044
14045 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
14046         mono_register_opcode_emulation (CEE_DIV, "__emul_idiv", "int32 int32 int32", mono_idiv, FALSE);
14047         mono_register_opcode_emulation (CEE_DIV_UN, "__emul_idiv_un", "int32 int32 int32", mono_idiv_un, FALSE);
14048         mono_register_opcode_emulation (CEE_REM, "__emul_irem", "int32 int32 int32", mono_irem, FALSE);
14049         mono_register_opcode_emulation (CEE_REM_UN, "__emul_irem_un", "int32 int32 int32", mono_irem_un, FALSE);
14050 #endif
14051
14052 #ifdef MONO_ARCH_EMULATE_MUL_DIV
14053         mono_register_opcode_emulation (CEE_MUL_OVF, "__emul_imul_ovf", "int32 int32 int32", mono_imul_ovf, FALSE);
14054         mono_register_opcode_emulation (CEE_MUL_OVF_UN, "__emul_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, FALSE);
14055         mono_register_opcode_emulation (CEE_MUL, "__emul_imul", "int32 int32 int32", mono_imul, TRUE);
14056 #endif
14057 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_SOFT_FLOAT)
14058         mono_register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, FALSE);
14059 #endif
14060
14061         mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, FALSE);
14062         mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, FALSE);
14063         mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, FALSE);
14064         mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, FALSE);
14065
14066 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
14067         mono_register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, FALSE);
14068 #endif
14069 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
14070         mono_register_opcode_emulation (CEE_CONV_R_UN, "__emul_conv_r_un", "double int32", mono_conv_to_r8_un, FALSE);
14071 #endif
14072 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
14073         mono_register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, FALSE);
14074 #endif
14075 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
14076         mono_register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, FALSE);
14077 #endif
14078 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
14079         mono_register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", "double long", mono_lconv_to_r8_un, FALSE);
14080 #endif
14081 #ifdef MONO_ARCH_EMULATE_FREM
14082         mono_register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, FALSE);
14083 #endif
14084
14085 #ifdef MONO_ARCH_SOFT_FLOAT
14086         mono_register_opcode_emulation (OP_FSUB, "__emul_fsub", "double double double", mono_fsub, FALSE);
14087         mono_register_opcode_emulation (OP_FADD, "__emul_fadd", "double double double", mono_fadd, FALSE);
14088         mono_register_opcode_emulation (OP_FMUL, "__emul_fmul", "double double double", mono_fmul, FALSE);
14089         mono_register_opcode_emulation (OP_FNEG, "__emul_fneg", "double double", mono_fneg, FALSE);
14090         mono_register_opcode_emulation (CEE_CONV_R8, "__emul_conv_r8", "double int32", mono_conv_to_r8, FALSE);
14091         mono_register_opcode_emulation (CEE_CONV_R4, "__emul_conv_r4", "double int32", mono_conv_to_r4, FALSE);
14092         mono_register_opcode_emulation (OP_FCONV_TO_R4, "__emul_fconv_to_r4", "double double", mono_fconv_r4, FALSE);
14093         mono_register_opcode_emulation (OP_FCONV_TO_I1, "__emul_fconv_to_i1", "int8 double", mono_fconv_i1, FALSE);
14094         mono_register_opcode_emulation (OP_FCONV_TO_I2, "__emul_fconv_to_i2", "int16 double", mono_fconv_i2, FALSE);
14095         mono_register_opcode_emulation (OP_FCONV_TO_I4, "__emul_fconv_to_i4", "int32 double", mono_fconv_i4, FALSE);
14096         mono_register_opcode_emulation (OP_FCONV_TO_U1, "__emul_fconv_to_u1", "uint8 double", mono_fconv_u1, FALSE);
14097         mono_register_opcode_emulation (OP_FCONV_TO_U2, "__emul_fconv_to_u2", "uint16 double", mono_fconv_u2, FALSE);
14098
14099         mono_register_opcode_emulation (OP_FBEQ, "__emul_fcmp_eq", "uint32 double double", mono_fcmp_eq, FALSE);
14100         mono_register_opcode_emulation (OP_FBLT, "__emul_fcmp_lt", "uint32 double double", mono_fcmp_lt, FALSE);
14101         mono_register_opcode_emulation (OP_FBGT, "__emul_fcmp_gt", "uint32 double double", mono_fcmp_gt, FALSE);
14102         mono_register_opcode_emulation (OP_FBLE, "__emul_fcmp_le", "uint32 double double", mono_fcmp_le, FALSE);
14103         mono_register_opcode_emulation (OP_FBGE, "__emul_fcmp_ge", "uint32 double double", mono_fcmp_ge, FALSE);
14104         mono_register_opcode_emulation (OP_FBNE_UN, "__emul_fcmp_ne_un", "uint32 double double", mono_fcmp_ne_un, FALSE);
14105         mono_register_opcode_emulation (OP_FBLT_UN, "__emul_fcmp_lt_un", "uint32 double double", mono_fcmp_lt_un, FALSE);
14106         mono_register_opcode_emulation (OP_FBGT_UN, "__emul_fcmp_gt_un", "uint32 double double", mono_fcmp_gt_un, FALSE);
14107         mono_register_opcode_emulation (OP_FBLE_UN, "__emul_fcmp_le_un", "uint32 double double", mono_fcmp_le_un, FALSE);
14108         mono_register_opcode_emulation (OP_FBGE_UN, "__emul_fcmp_ge_un", "uint32 double double", mono_fcmp_ge_un, FALSE);
14109
14110         mono_register_opcode_emulation (OP_FCEQ, "__emul_fcmp_ceq", "uint32 double double", mono_fceq, FALSE);
14111         mono_register_opcode_emulation (OP_FCGT, "__emul_fcmp_cgt", "uint32 double double", mono_fcgt, FALSE);
14112         mono_register_opcode_emulation (OP_FCGT_UN, "__emul_fcmp_cgt_un", "uint32 double double", mono_fcgt_un, FALSE);
14113         mono_register_opcode_emulation (OP_FCLT, "__emul_fcmp_clt", "uint32 double double", mono_fclt, FALSE);
14114         mono_register_opcode_emulation (OP_FCLT_UN, "__emul_fcmp_clt_un", "uint32 double double", mono_fclt_un, FALSE);
14115
14116         register_icall (mono_fload_r4, "mono_fload_r4", "double ptr", FALSE);
14117         register_icall (mono_fstore_r4, "mono_fstore_r4", "void double ptr", FALSE);
14118         register_icall (mono_fload_r4_arg, "mono_fload_r4_arg", "uint32 double", FALSE);
14119 #endif
14120
14121 #if SIZEOF_VOID_P == 4
14122         mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, TRUE);
14123 #endif
14124
14125         /* other jit icalls */
14126         register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
14127         register_icall (mono_class_static_field_address , "mono_class_static_field_address", 
14128                                  "ptr ptr ptr", FALSE);
14129         register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
14130         register_icall (mono_ldtoken_wrapper_generic_shared, "mono_ldtoken_wrapper_generic_shared",
14131                 "ptr ptr ptr ptr", FALSE);
14132         register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
14133         register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
14134         register_icall (mono_helper_stelem_ref_check, "helper_stelem_ref_check", "void object object", FALSE);
14135         register_icall (mono_object_new, "mono_object_new", "object ptr ptr", FALSE);
14136         register_icall (mono_object_new_specific, "mono_object_new_specific", "object ptr", FALSE);
14137         register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
14138         register_icall (mono_array_new_specific, "mono_array_new_specific", "object ptr int32", FALSE);
14139         register_icall (mono_runtime_class_init, "mono_runtime_class_init", "void ptr", FALSE);
14140         register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
14141         register_icall (mono_ldftn_nosync, "mono_ldftn_nosync", "ptr ptr", FALSE);
14142         register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
14143         register_icall (mono_ldvirtfn_gshared, "mono_ldvirtfn_gshared", "ptr object ptr", FALSE);
14144         register_icall (mono_helper_compile_generic_method, "compile_generic_method", "ptr object ptr ptr ptr", FALSE);
14145         register_icall (mono_helper_compile_generic_method_wo_context, "compile_generic_method_wo_context",
14146                 "ptr object ptr ptr", FALSE);
14147         register_icall (mono_helper_ldstr, "helper_ldstr", "object ptr int", FALSE);
14148         register_icall (mono_helper_ldstr_mscorlib, "helper_ldstr_mscorlib", "object int", FALSE);
14149         register_icall (mono_helper_newobj_mscorlib, "helper_newobj_mscorlib", "object int", FALSE);
14150         register_icall (mono_value_copy, "mono_value_copy", "void ptr ptr ptr", FALSE);
14151         register_icall (mono_object_castclass, "mono_object_castclass", "object object ptr", FALSE);
14152         register_icall (mono_break, "mono_break", NULL, TRUE);
14153         register_icall (mono_create_corlib_exception_0, "mono_create_corlib_exception_0", "object int", TRUE);
14154         register_icall (mono_create_corlib_exception_1, "mono_create_corlib_exception_1", "object int object", TRUE);
14155         register_icall (mono_create_corlib_exception_2, "mono_create_corlib_exception_2", "object int object object", TRUE);
14156         register_icall (mono_array_new_2, "mono_array_new_2", "object ptr int int", FALSE);
14157 #endif
14158
14159 #define JIT_RUNTIME_WORKS
14160 #ifdef JIT_RUNTIME_WORKS
14161         mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
14162         mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
14163 #endif
14164
14165         mono_generic_sharing_init ();
14166
14167         mono_thread_attach (domain);
14168         
14169         MONO_PROBE_VES_INIT_END ();
14170         
14171         return domain;
14172 }
14173
14174 MonoJitStats mono_jit_stats = {0};
14175
14176 static void 
14177 print_jit_stats (void)
14178 {
14179         if (mono_jit_stats.enabled) {
14180                 g_print ("Mono Jit statistics\n");
14181                 g_print ("Compiled methods:       %ld\n", mono_jit_stats.methods_compiled);
14182                 g_print ("Methods from AOT:       %ld\n", mono_jit_stats.methods_aot);
14183                 g_print ("Methods cache lookup:   %ld\n", mono_jit_stats.methods_lookups);
14184                 g_print ("Method trampolines:     %ld\n", mono_jit_stats.method_trampolines);
14185                 g_print ("Basic blocks:           %ld\n", mono_jit_stats.basic_blocks);
14186                 g_print ("Max basic blocks:       %ld\n", mono_jit_stats.max_basic_blocks);
14187                 g_print ("Allocated vars:         %ld\n", mono_jit_stats.allocate_var);
14188                 g_print ("Analyze stack repeat:   %ld\n", mono_jit_stats.analyze_stack_repeat);
14189                 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
14190                 g_print ("Native code size:       %ld\n", mono_jit_stats.native_code_size);
14191                 g_print ("Max code size ratio:    %.2f (%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
14192                                  mono_jit_stats.max_ratio_method);
14193                 g_print ("Biggest method:         %ld (%s)\n", mono_jit_stats.biggest_method_size,
14194                                  mono_jit_stats.biggest_method);
14195                 g_print ("Code reallocs:          %ld\n", mono_jit_stats.code_reallocs);
14196                 g_print ("Allocated code size:    %ld\n", mono_jit_stats.allocated_code_size);
14197                 g_print ("Inlineable methods:     %ld\n", mono_jit_stats.inlineable_methods);
14198                 g_print ("Inlined methods:        %ld\n", mono_jit_stats.inlined_methods);
14199                 g_print ("Locals stack size:      %ld\n", mono_jit_stats.locals_stack_size);
14200
14201                 g_print ("\nCreated object count:   %ld\n", mono_stats.new_object_count);
14202                 g_print ("Delegates created:      %ld\n", mono_stats.delegate_creations);
14203                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
14204                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
14205                 g_print ("Generic vtables:        %ld\n", mono_stats.generic_vtable_count);
14206                 g_print ("Methods:                %ld\n", mono_stats.method_count);
14207                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
14208                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
14209                 g_print ("Mscorlib mempool size:  %d\n", mono_mempool_get_allocated (mono_defaults.corlib->mempool));
14210
14211                 g_print ("\nGeneric instances:      %ld\n", mono_stats.generic_instance_count);
14212                 g_print ("Initialized classes:    %ld\n", mono_stats.generic_class_count);
14213                 g_print ("Inflated methods:       %ld / %ld\n", mono_stats.inflated_method_count_2,
14214                          mono_stats.inflated_method_count);
14215                 g_print ("Inflated types:         %ld\n", mono_stats.inflated_type_count);
14216                 g_print ("Generics metadata size: %ld\n", mono_stats.generics_metadata_size);
14217                 g_print ("Generics virtual invokes: %ld\n", mono_jit_stats.generic_virtual_invocations);
14218
14219                 g_print ("Sharable generic methods: %ld\n", mono_stats.generics_sharable_methods);
14220                 g_print ("Unsharable generic methods: %ld\n", mono_stats.generics_unsharable_methods);
14221                 g_print ("Shared generic methods: %ld\n", mono_stats.generics_shared_methods);
14222
14223                 g_print ("Dynamic code allocs:    %ld\n", mono_stats.dynamic_code_alloc_count);
14224                 g_print ("Dynamic code bytes:     %ld\n", mono_stats.dynamic_code_bytes_count);
14225                 g_print ("Dynamic code frees:     %ld\n", mono_stats.dynamic_code_frees_count);
14226
14227                 g_print ("IMT tables size:        %ld\n", mono_stats.imt_tables_size);
14228                 g_print ("IMT number of tables:   %ld\n", mono_stats.imt_number_of_tables);
14229                 g_print ("IMT number of methods:  %ld\n", mono_stats.imt_number_of_methods);
14230                 g_print ("IMT used slots:         %ld\n", mono_stats.imt_used_slots);
14231                 g_print ("IMT colliding slots:    %ld\n", mono_stats.imt_slots_with_collisions);
14232                 g_print ("IMT max collisions:     %ld\n", mono_stats.imt_max_collisions_in_slot);
14233                 g_print ("IMT methods at max col: %ld\n", mono_stats.imt_method_count_when_max_collisions);
14234                 g_print ("IMT thunks size:        %ld\n", mono_stats.imt_thunks_size);
14235
14236                 g_print ("JIT info table inserts: %ld\n", mono_stats.jit_info_table_insert_count);
14237                 g_print ("JIT info table removes: %ld\n", mono_stats.jit_info_table_remove_count);
14238                 g_print ("JIT info table lookups: %ld\n", mono_stats.jit_info_table_lookup_count);
14239
14240                 g_print ("Hazardous pointers:     %ld\n", mono_stats.hazardous_pointer_count);
14241 #ifdef HAVE_SGEN_GC
14242                 g_print ("Minor GC collections:   %ld\n", mono_stats.minor_gc_count);
14243                 g_print ("Major GC collections:   %ld\n", mono_stats.major_gc_count);
14244                 g_print ("Minor GC time in msecs: %lf\n", (double)mono_stats.minor_gc_time_usecs / 1000.0);
14245                 g_print ("Major GC time in msecs: %lf\n", (double)mono_stats.major_gc_time_usecs / 1000.0);
14246 #endif
14247                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
14248                         g_print ("\nDecl security check   : %ld\n", mono_jit_stats.cas_declsec_check);
14249                         g_print ("LinkDemand (user)     : %ld\n", mono_jit_stats.cas_linkdemand);
14250                         g_print ("LinkDemand (icall)    : %ld\n", mono_jit_stats.cas_linkdemand_icall);
14251                         g_print ("LinkDemand (pinvoke)  : %ld\n", mono_jit_stats.cas_linkdemand_pinvoke);
14252                         g_print ("LinkDemand (aptc)     : %ld\n", mono_jit_stats.cas_linkdemand_aptc);
14253                         g_print ("Demand (code gen)     : %ld\n", mono_jit_stats.cas_demand_generation);
14254                 }
14255                 if (debug_options.collect_pagefault_stats) {
14256                         g_print ("Metadata pagefaults   : %d\n", mono_raw_buffer_get_n_pagefaults ());
14257                         g_print ("AOT pagefaults        : %d\n", mono_aot_get_n_pagefaults ());
14258                 }
14259
14260                 g_free (mono_jit_stats.max_ratio_method);
14261                 mono_jit_stats.max_ratio_method = NULL;
14262                 g_free (mono_jit_stats.biggest_method);
14263                 mono_jit_stats.biggest_method = NULL;
14264         }
14265 }
14266
14267 void
14268 mini_cleanup (MonoDomain *domain)
14269 {
14270 #ifdef HAVE_LINUX_RTC_H
14271         if (rtc_fd >= 0)
14272                 enable_rtc_timer (FALSE);
14273 #endif
14274
14275         /* 
14276          * mono_runtime_cleanup() and mono_domain_finalize () need to
14277          * be called early since they need the execution engine still
14278          * fully working (mono_domain_finalize may invoke managed finalizers
14279          * and mono_runtime_cleanup will wait for other threads to finish).
14280          */
14281         mono_domain_finalize (domain, 2000);
14282
14283         /* This accesses metadata so needs to be called before runtime shutdown */
14284         print_jit_stats ();
14285
14286         mono_runtime_cleanup (domain);
14287
14288         mono_profiler_shutdown ();
14289
14290         mono_icall_cleanup ();
14291
14292         mono_runtime_cleanup_handlers ();
14293
14294         mono_domain_free (domain, TRUE);
14295
14296         mono_debugger_cleanup ();
14297
14298         mono_trampolines_cleanup ();
14299
14300         mono_code_manager_destroy (global_codeman);
14301         g_hash_table_destroy (jit_icall_name_hash);
14302         g_free (emul_opcode_map);
14303
14304         mono_arch_cleanup ();
14305
14306         mono_cleanup ();
14307
14308         mono_trace_cleanup ();
14309
14310         mono_counters_dump (-1, stdout);
14311
14312         if (mono_inject_async_exc_method)
14313                 mono_method_desc_free (mono_inject_async_exc_method);
14314
14315         TlsFree(mono_jit_tls_id);
14316
14317         DeleteCriticalSection (&jit_mutex);
14318
14319         DeleteCriticalSection (&mono_delegate_section);
14320 }
14321
14322 void
14323 mono_set_defaults (int verbose_level, guint32 opts)
14324 {
14325         mini_verbose = verbose_level;
14326         default_opt = opts;
14327         default_opt_set = TRUE;
14328 }
14329
14330 static void
14331 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
14332 {
14333         GHashTable *assemblies = (GHashTable*)user_data;
14334         MonoImage *image = mono_assembly_get_image (ass);
14335         MonoMethod *method, *invoke;
14336         int i, count = 0;
14337
14338         if (g_hash_table_lookup (assemblies, ass))
14339                 return;
14340
14341         g_hash_table_insert (assemblies, ass, ass);
14342
14343         if (mini_verbose > 0)
14344                 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
14345
14346         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
14347                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
14348                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
14349                         continue;
14350
14351                 count++;
14352                 if (mini_verbose > 1) {
14353                         char * desc = mono_method_full_name (method, TRUE);
14354                         g_print ("Compiling %d %s\n", count, desc);
14355                         g_free (desc);
14356                 }
14357                 mono_compile_method (method);
14358                 if (strcmp (method->name, "Finalize") == 0) {
14359                         invoke = mono_marshal_get_runtime_invoke (method);
14360                         mono_compile_method (invoke);
14361                 }
14362                 if (method->klass->marshalbyref && mono_method_signature (method)->hasthis) {
14363                         invoke = mono_marshal_get_remoting_invoke_with_check (method);
14364                         mono_compile_method (invoke);
14365                 }
14366         }
14367
14368         /* Load and precompile referenced assemblies as well */
14369         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
14370                 mono_assembly_load_reference (image, i);
14371                 if (image->references [i])
14372                         mono_precompile_assembly (image->references [i], assemblies);
14373         }
14374 }
14375
14376 void mono_precompile_assemblies ()
14377 {
14378         GHashTable *assemblies = g_hash_table_new (NULL, NULL);
14379
14380         mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
14381
14382         g_hash_table_destroy (assemblies);
14383 }