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