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