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