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