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