Tue Oct 4 20:23:25 CEST 2005 Paolo Molaro <lupus@ximian.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 *ldfld_wrapper = 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 (ldfld_wrapper)->ret)) {
5268                                                 costs = inline_method (cfg, ldfld_wrapper, mono_method_signature (ldfld_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                                                 if (*ip == CEE_LDFLDA) {
5282                                                         /* not sure howto handle this */
5283                                                         NEW_TEMPLOADA (cfg, *sp, temp);
5284                                                 } else {
5285                                                         NEW_TEMPLOAD (cfg, *sp, temp);
5286                                                 }
5287                                                 sp++;
5288
5289                                                 /* indicates start of a new block, and triggers a load of
5290                                                    all stack arguments at bb boundarie */
5291                                                 bblock = ebblock;
5292                                                 
5293                                                 inline_costs += costs;
5294                                                 break;
5295                                         } else {
5296                                                 temp = mono_emit_method_call_spilled (cfg, bblock, ldfld_wrapper, mono_method_signature (ldfld_wrapper), iargs, ip, NULL);
5297                                                 if (*ip == CEE_LDFLDA) {
5298                                                         /* not sure howto handle this */
5299                                                         NEW_TEMPLOADA (cfg, *sp, temp);
5300                                                 } else {
5301                                                         NEW_TEMPLOAD (cfg, *sp, temp);
5302                                                 }
5303                                                 sp++;
5304                                         }
5305                                 } else {
5306                                         NEW_ICONST (cfg, offset_ins, foffset);
5307                                         MONO_INST_NEW (cfg, ins, OP_PADD);
5308                                         ins->cil_code = ip;
5309                                         ins->inst_left = *sp;
5310                                         ins->inst_right = offset_ins;
5311                                         ins->type = STACK_MP;
5312
5313                                         if (*ip == CEE_LDFLDA) {
5314                                                 *sp++ = ins;
5315                                         } else {
5316                                                 MonoInst *load;
5317                                                 MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
5318                                                 type_to_eval_stack_type (field->type, load);
5319                                                 load->cil_code = ip;
5320                                                 load->inst_left = ins;
5321                                                 load->flags |= ins_flag;
5322                                                 ins_flag = 0;
5323                                                 *sp++ = load;
5324                                         }
5325                                 }
5326                         }
5327                         ip += 5;
5328                         break;
5329                 }
5330                 case CEE_LDSFLD:
5331                 case CEE_LDSFLDA:
5332                 case CEE_STSFLD: {
5333                         MonoClassField *field;
5334                         gpointer addr = NULL;
5335
5336                         CHECK_OPSIZE (5);
5337                         token = read32 (ip + 1);
5338
5339                         field = mono_field_from_token (image, token, &klass, generic_context);
5340                         if (!field)
5341                                 goto load_error;
5342                         mono_class_init (klass);
5343
5344                         g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL));
5345
5346                         if ((*ip) == CEE_STSFLD)
5347                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5348
5349                         /* The special_static_fields field is init'd in mono_class_vtable, so it needs
5350                          * to be called here.
5351                          */
5352                         if (!(cfg->opt & MONO_OPT_SHARED))
5353                                 mono_class_vtable (cfg->domain, klass);
5354                         mono_domain_lock (cfg->domain);
5355                         if (cfg->domain->special_static_fields)
5356                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
5357                         mono_domain_unlock (cfg->domain);
5358
5359                         if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
5360                                 int temp;
5361                                 MonoInst *iargs [2];
5362                                 MonoInst *domain_var;
5363                                 
5364                                 g_assert (field->parent);
5365                                 /* avoid depending on undefined C behavior in sequence points */
5366                                 domain_var = mono_get_domainvar (cfg);
5367                                 NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
5368                                 NEW_FIELDCONST (cfg, iargs [1], field);
5369                                 temp = mono_emit_jit_icall (cfg, bblock, mono_class_static_field_address, iargs, ip);
5370                                 NEW_TEMPLOAD (cfg, ins, temp);
5371                         } else {
5372                                 MonoVTable *vtable;
5373                                 vtable = mono_class_vtable (cfg->domain, klass);
5374                                 if (!addr) {
5375                                         if (mini_field_access_needs_cctor_run (cfg, method, vtable) && !(g_slist_find (class_inits, vtable))) {
5376                                                 guint8 *tramp = mono_create_class_init_trampoline (vtable);
5377                                                 mono_emit_native_call (cfg, bblock, tramp, 
5378                                                                                            helper_sig_class_init_trampoline,
5379                                                                                            NULL, ip, FALSE, FALSE);
5380                                                 if (cfg->verbose_level > 2)
5381                                                         g_print ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, field->name);
5382                                                 class_inits = g_slist_prepend (class_inits, vtable);
5383                                         } else {
5384                                                 if (cfg->run_cctors)
5385                                                         mono_runtime_class_init (vtable);
5386                                         }
5387                                         addr = (char*)vtable->data + field->offset;
5388
5389                                         if (cfg->compile_aot)
5390                                                 NEW_SFLDACONST (cfg, ins, field);
5391                                         else
5392                                                 NEW_PCONST (cfg, ins, addr);
5393                                         ins->cil_code = ip;
5394                                 } else {
5395                                         /* 
5396                                          * insert call to mono_threads_get_static_data (GPOINTER_TO_UINT (addr)) 
5397                                          * This could be later optimized to do just a couple of
5398                                          * memory dereferences with constant offsets.
5399                                          */
5400                                         int temp;
5401                                         MonoInst *iargs [1];
5402                                         NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
5403                                         temp = mono_emit_jit_icall (cfg, bblock, mono_get_special_static_data, iargs, ip);
5404                                         NEW_TEMPLOAD (cfg, ins, temp);
5405                                 }
5406                         }
5407
5408                         /* FIXME: mark instructions for use in SSA */
5409                         if (*ip == CEE_LDSFLDA) {
5410                                 *sp++ = ins;
5411                         } else if (*ip == CEE_STSFLD) {
5412                                 MonoInst *store;
5413                                 CHECK_STACK (1);
5414                                 sp--;
5415                                 MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
5416                                 store->cil_code = ip;
5417                                 store->inst_left = ins;
5418                                 store->inst_right = sp [0];
5419                                 store->flags |= ins_flag;
5420                                 ins_flag = 0;
5421
5422                                 if (store->opcode == CEE_STOBJ) {
5423                                         handle_stobj (cfg, bblock, ins, sp [0], ip, mono_class_from_mono_type (field->type), FALSE, FALSE);
5424                                 } else
5425                                         MONO_ADD_INS (bblock, store);
5426                         } else {
5427                                 gboolean is_const = FALSE;
5428                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
5429                                 if (!((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) && 
5430                                     vtable->initialized && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY)) {
5431                                         gpointer addr = (char*)vtable->data + field->offset;
5432                                         int ro_type = field->type->type;
5433                                         if (ro_type == MONO_TYPE_VALUETYPE && field->type->data.klass->enumtype) {
5434                                                 ro_type = field->type->data.klass->enum_basetype->type;
5435                                         }
5436                                         /* g_print ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, field->name);*/
5437                                         is_const = TRUE;
5438                                         switch (ro_type) {
5439                                         case MONO_TYPE_BOOLEAN:
5440                                         case MONO_TYPE_U1:
5441                                                 NEW_ICONST (cfg, *sp, *((guint8 *)addr));
5442                                                 sp++;
5443                                                 break;
5444                                         case MONO_TYPE_I1:
5445                                                 NEW_ICONST (cfg, *sp, *((gint8 *)addr));
5446                                                 sp++;
5447                                                 break;                                          
5448                                         case MONO_TYPE_CHAR:
5449                                         case MONO_TYPE_U2:
5450                                                 NEW_ICONST (cfg, *sp, *((guint16 *)addr));
5451                                                 sp++;
5452                                                 break;
5453                                         case MONO_TYPE_I2:
5454                                                 NEW_ICONST (cfg, *sp, *((gint16 *)addr));
5455                                                 sp++;
5456                                                 break;
5457                                                 break;
5458                                         case MONO_TYPE_I4:
5459                                                 NEW_ICONST (cfg, *sp, *((gint32 *)addr));
5460                                                 sp++;
5461                                                 break;                                          
5462                                         case MONO_TYPE_U4:
5463                                                 NEW_ICONST (cfg, *sp, *((guint32 *)addr));
5464                                                 sp++;
5465                                                 break;
5466                                         case MONO_TYPE_I:
5467                                         case MONO_TYPE_U:
5468                                         case MONO_TYPE_STRING:
5469                                         case MONO_TYPE_OBJECT:
5470                                         case MONO_TYPE_CLASS:
5471                                         case MONO_TYPE_SZARRAY:
5472                                         case MONO_TYPE_PTR:
5473                                         case MONO_TYPE_FNPTR:
5474                                         case MONO_TYPE_ARRAY:
5475                                                 NEW_PCONST (cfg, *sp, *((gpointer *)addr));
5476                                                 type_to_eval_stack_type (field->type, *sp);
5477                                                 sp++;
5478                                                 break;
5479                                         case MONO_TYPE_I8:
5480                                         case MONO_TYPE_U8:
5481                                                 MONO_INST_NEW (cfg, *sp, OP_I8CONST);
5482                                                 sp [0]->type = STACK_I8;
5483                                                 sp [0]->inst_l = *((gint64 *)addr);
5484                                                 sp++;
5485                                                 break;
5486                                         case MONO_TYPE_R4:
5487                                         case MONO_TYPE_R8:
5488                                         case MONO_TYPE_VALUETYPE:
5489                                         default:
5490                                                 is_const = FALSE;
5491                                                 break;
5492                                         }
5493                                 }
5494
5495                                 if (!is_const) {
5496                                         MonoInst *load;
5497                                         CHECK_STACK_OVF (1);
5498                                         MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
5499                                         type_to_eval_stack_type (field->type, load);
5500                                         load->cil_code = ip;
5501                                         load->inst_left = ins;
5502                                         *sp++ = load;
5503                                         load->flags |= ins_flag;
5504                                         ins_flag = 0;
5505                                         /* fixme: dont see the problem why this does not work */
5506                                         //cfg->disable_aot = TRUE;
5507                                 }
5508                         }
5509                         ip += 5;
5510                         break;
5511                 }
5512                 case CEE_STOBJ:
5513                         CHECK_STACK (2);
5514                         sp -= 2;
5515                         CHECK_OPSIZE (5);
5516                         token = read32 (ip + 1);
5517                         klass = mini_get_class (method, token, generic_context);
5518                         if (!klass)
5519                                 goto load_error;
5520                         n = mono_type_to_stind (&klass->byval_arg);
5521                         if (n == CEE_STOBJ) {
5522                                 handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE);
5523                         } else {
5524                                 /* FIXME: should check item at sp [1] is compatible with the type of the store. */
5525                                 MonoInst *store;
5526                                 MONO_INST_NEW (cfg, store, n);
5527                                 store->cil_code = ip;
5528                                 store->inst_left = sp [0];
5529                                 store->inst_right = sp [1];
5530                                 store->flags |= ins_flag;
5531                                 MONO_ADD_INS (bblock, store);
5532                         }
5533                         ins_flag = 0;
5534                         ip += 5;
5535                         inline_costs += 1;
5536                         break;
5537                 case CEE_BOX: {
5538                         MonoInst *val;
5539                         CHECK_STACK (1);
5540                         --sp;
5541                         val = *sp;
5542                         CHECK_OPSIZE (5);
5543                         token = read32 (ip + 1);
5544                         klass = mini_get_class (method, token, generic_context);
5545                         if (!klass)
5546                                 goto load_error;
5547
5548                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
5549                                 *sp++ = val;
5550                                 ip += 5;
5551                                 break;
5552                         }
5553                         *sp++ = handle_box (cfg, bblock, val, ip, klass);
5554                         ip += 5;
5555                         inline_costs += 1;
5556                         break;
5557                 }
5558                 case CEE_NEWARR:
5559                         CHECK_STACK (1);
5560                         MONO_INST_NEW (cfg, ins, *ip);
5561                         ins->cil_code = ip;
5562                         --sp;
5563
5564                         CHECK_OPSIZE (5);
5565                         token = read32 (ip + 1);
5566
5567                         /* allocate the domainvar - becaus this is used in decompose_foreach */
5568                         if (cfg->opt & MONO_OPT_SHARED) {
5569                                 mono_get_domainvar (cfg);
5570                                 /* LAME-IR: Mark it as used since otherwise it will be optimized away */
5571                                 cfg->domainvar->flags |= MONO_INST_VOLATILE;
5572                         }
5573
5574                         /* Ditto */
5575                         mono_get_got_var (cfg);
5576
5577                         klass = mini_get_class (method, token, generic_context);
5578                         if (!klass)
5579                                 goto load_error;
5580                         ins->inst_newa_class = klass;
5581                         ins->inst_newa_len = *sp;
5582                         ins->type = STACK_OBJ;
5583                         ip += 5;
5584                         *sp++ = ins;
5585                         /* 
5586                          * we store the object so calls to create the array are not interleaved
5587                          * with the arguments of other calls.
5588                          */
5589                         if (1) {
5590                                 MonoInst *store, *temp, *load;
5591                                 --sp;
5592                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
5593                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
5594                                 store->cil_code = ins->cil_code;
5595                                 MONO_ADD_INS (bblock, store);
5596                                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
5597                                 load->cil_code = ins->cil_code;
5598                                 *sp++ = load;
5599                         }
5600                         inline_costs += 1;
5601                         break;
5602                 case CEE_LDLEN:
5603                         CHECK_STACK (1);
5604                         MONO_INST_NEW (cfg, ins, *ip);
5605                         ins->cil_code = ip++;
5606                         --sp;
5607                         ins->inst_left = *sp;
5608                         ins->type = STACK_PTR;
5609                         *sp++ = ins;
5610                         break;
5611                 case CEE_LDELEMA:
5612                         CHECK_STACK (2);
5613                         sp -= 2;
5614                         CHECK_OPSIZE (5);
5615
5616                         klass = mini_get_class (method, read32 (ip + 1), generic_context);
5617                         if (!klass)
5618                                 goto load_error;                        
5619                         /* we need to make sure that this array is exactly the type it needs
5620                          * to be for correctness. the wrappers are lax with their usage
5621                          * so we need to ignore them here
5622                          */
5623                         if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE) {
5624                                 MonoInst* check;
5625                                 MONO_INST_NEW (cfg, check, OP_CHECK_ARRAY_TYPE);
5626                                 check->cil_code = ip;
5627                                 check->klass = klass;
5628                                 check->inst_left = sp [0];
5629                                 check->type = STACK_OBJ;
5630                                 sp [0] = check;
5631                         }
5632                         
5633                         mono_class_init (klass);
5634                         NEW_LDELEMA (cfg, ins, sp, klass);
5635                         ins->cil_code = ip;
5636                         *sp++ = ins;
5637                         ip += 5;
5638                         break;
5639                 case CEE_LDELEM_ANY: {
5640                         MonoInst *load;
5641                         CHECK_STACK (2);
5642                         sp -= 2;
5643                         CHECK_OPSIZE (5);
5644                         token = read32 (ip + 1);
5645                         klass = mono_class_get_full (image, token, generic_context);
5646                         if (!klass)
5647                                 goto load_error;
5648                         mono_class_init (klass);
5649                         NEW_LDELEMA (cfg, load, sp, klass);
5650                         load->cil_code = ip;
5651                         MONO_INST_NEW (cfg, ins, mono_type_to_ldind (&klass->byval_arg));
5652                         ins->cil_code = ip;
5653                         ins->inst_left = load;
5654                         *sp++ = ins;
5655                         type_to_eval_stack_type (&klass->byval_arg, ins);
5656                         ip += 5;
5657                         break;
5658                 }
5659                 case CEE_LDELEM_I1:
5660                 case CEE_LDELEM_U1:
5661                 case CEE_LDELEM_I2:
5662                 case CEE_LDELEM_U2:
5663                 case CEE_LDELEM_I4:
5664                 case CEE_LDELEM_U4:
5665                 case CEE_LDELEM_I8:
5666                 case CEE_LDELEM_I:
5667                 case CEE_LDELEM_R4:
5668                 case CEE_LDELEM_R8:
5669                 case CEE_LDELEM_REF: {
5670                         MonoInst *load;
5671                         /*
5672                          * translate to:
5673                          * ldind.x (ldelema (array, index))
5674                          * ldelema does the bounds check
5675                          */
5676                         CHECK_STACK (2);
5677                         sp -= 2;
5678                         klass = array_access_to_klass (*ip);
5679                         NEW_LDELEMA (cfg, load, sp, klass);
5680                         load->cil_code = ip;
5681                         MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
5682                         ins->cil_code = ip;
5683                         ins->inst_left = load;
5684                         *sp++ = ins;
5685                         ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
5686                         ++ip;
5687                         break;
5688                 }
5689                 case CEE_STELEM_I:
5690                 case CEE_STELEM_I1:
5691                 case CEE_STELEM_I2:
5692                 case CEE_STELEM_I4:
5693                 case CEE_STELEM_I8:
5694                 case CEE_STELEM_R4:
5695                 case CEE_STELEM_R8: {
5696                         MonoInst *load;
5697                         /*
5698                          * translate to:
5699                          * stind.x (ldelema (array, index), val)
5700                          * ldelema does the bounds check
5701                          */
5702                         CHECK_STACK (3);
5703                         sp -= 3;
5704                         klass = array_access_to_klass (*ip);
5705                         NEW_LDELEMA (cfg, load, sp, klass);
5706                         load->cil_code = ip;
5707                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
5708                         ins->cil_code = ip;
5709                         ins->inst_left = load;
5710                         ins->inst_right = sp [2];
5711                         ++ip;
5712                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5713                         MONO_ADD_INS (bblock, ins);
5714                         inline_costs += 1;
5715                         break;
5716                 }
5717                 case CEE_STELEM_ANY: {
5718                         MonoInst *load;
5719                         /*
5720                          * translate to:
5721                          * stind.x (ldelema (array, index), val)
5722                          * ldelema does the bounds check
5723                          */
5724                         CHECK_STACK (3);
5725                         sp -= 3;
5726                         CHECK_OPSIZE (5);
5727                         token = read32 (ip + 1);
5728                         klass = mono_class_get_full (image, token, generic_context);
5729                         if (!klass)
5730                                 goto load_error;
5731                         mono_class_init (klass);
5732                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
5733                                 MonoMethod* helper = mono_marshal_get_stelemref ();
5734                                 MonoInst *iargs [3];
5735                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5736
5737                                 iargs [2] = sp [2];
5738                                 iargs [1] = sp [1];
5739                                 iargs [0] = sp [0];
5740                                 
5741                                 mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
5742                         } else {
5743                                 NEW_LDELEMA (cfg, load, sp, klass);
5744                                 load->cil_code = ip;
5745
5746                                 n = mono_type_to_stind (&klass->byval_arg);
5747                                 if (n == CEE_STOBJ)
5748                                         handle_stobj (cfg, bblock, load, sp [2], ip, klass, FALSE, FALSE);
5749                                 else {
5750                                         MONO_INST_NEW (cfg, ins, n);
5751                                         ins->cil_code = ip;
5752                                         ins->inst_left = load;
5753                                         ins->inst_right = sp [2];
5754                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5755                                         MONO_ADD_INS (bblock, ins);
5756                                 }
5757                         }
5758                         ip += 5;
5759                         inline_costs += 1;
5760                         break;
5761                 }
5762                 case CEE_STELEM_REF: {
5763                         MonoInst *iargs [3];
5764                         MonoMethod* helper = mono_marshal_get_stelemref ();
5765
5766                         CHECK_STACK (3);
5767                         sp -= 3;
5768
5769                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5770
5771                         iargs [2] = sp [2];
5772                         iargs [1] = sp [1];
5773                         iargs [0] = sp [0];
5774                         
5775                         mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
5776
5777                         /*
5778                         MonoInst *group;
5779                         NEW_GROUP (cfg, group, sp [0], sp [1]);
5780                         MONO_INST_NEW (cfg, ins, CEE_STELEM_REF);
5781                         ins->cil_code = ip;
5782                         ins->inst_left = group;
5783                         ins->inst_right = sp [2];
5784                         MONO_ADD_INS (bblock, ins);
5785                         */
5786
5787                         ++ip;
5788                         inline_costs += 1;
5789                         break;
5790                 }
5791                 case CEE_CKFINITE: {
5792                         MonoInst *store, *temp;
5793                         CHECK_STACK (1);
5794
5795                         /* this instr. can throw exceptions as side effect,
5796                          * so we cant eliminate dead code which contains CKFINITE opdodes.
5797                          * Spilling to memory makes sure that we always perform
5798                          * this check */
5799
5800                         
5801                         MONO_INST_NEW (cfg, ins, CEE_CKFINITE);
5802                         ins->cil_code = ip;
5803                         ins->inst_left = sp [-1];
5804                         temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
5805
5806                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
5807                         store->cil_code = ip;
5808                         MONO_ADD_INS (bblock, store);
5809
5810                         NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
5811                        
5812                         ++ip;
5813                         break;
5814                 }
5815                 case CEE_REFANYVAL:
5816                         CHECK_STACK (1);
5817                         MONO_INST_NEW (cfg, ins, *ip);
5818                         --sp;
5819                         CHECK_OPSIZE (5);
5820                         klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
5821                         if (!klass)
5822                                 goto load_error;
5823                         mono_class_init (klass);
5824                         ins->type = STACK_MP;
5825                         ins->inst_left = *sp;
5826                         ins->klass = klass;
5827                         ins->inst_newa_class = klass;
5828                         ins->cil_code = ip;
5829                         ip += 5;
5830                         *sp++ = ins;
5831                         break;
5832                 case CEE_MKREFANY: {
5833                         MonoInst *loc, *klassconst;
5834
5835                         CHECK_STACK (1);
5836                         MONO_INST_NEW (cfg, ins, *ip);
5837                         --sp;
5838                         CHECK_OPSIZE (5);
5839                         klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
5840                         if (!klass)
5841                                 goto load_error;
5842                         mono_class_init (klass);
5843                         ins->cil_code = ip;
5844
5845                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
5846                         NEW_TEMPLOADA (cfg, ins->inst_right, loc->inst_c0);
5847
5848                         NEW_PCONST (cfg, klassconst, klass);
5849                         NEW_GROUP (cfg, ins->inst_left, *sp, klassconst);
5850                         
5851                         MONO_ADD_INS (bblock, ins);
5852
5853                         NEW_TEMPLOAD (cfg, *sp, loc->inst_c0);
5854                         ++sp;
5855                         ip += 5;
5856                         break;
5857                 }
5858                 case CEE_LDTOKEN: {
5859                         gpointer handle;
5860                         MonoClass *handle_class;
5861
5862                         CHECK_STACK_OVF (1);
5863
5864                         CHECK_OPSIZE (5);
5865                         n = read32 (ip + 1);
5866
5867                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
5868                                 handle = mono_method_get_wrapper_data (method, n);
5869                                 handle_class = mono_method_get_wrapper_data (method, n + 1);
5870                         }
5871                         else {
5872                                 handle = mono_ldtoken (image, n, &handle_class, generic_context);
5873                         }
5874                         if (!handle)
5875                                 goto load_error;
5876                         mono_class_init (handle_class);
5877
5878                         if (cfg->opt & MONO_OPT_SHARED) {
5879                                 int temp;
5880                                 MonoInst *res, *store, *addr, *vtvar, *iargs [3];
5881
5882                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
5883
5884                                 NEW_IMAGECONST (cfg, iargs [0], image);
5885                                 NEW_ICONST (cfg, iargs [1], n);
5886                                 NEW_PCONST (cfg, iargs [2], generic_context);
5887                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
5888                                 NEW_TEMPLOAD (cfg, res, temp);
5889                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
5890                                 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
5891                                 MONO_ADD_INS (bblock, store);
5892                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
5893                         } else {
5894                                 if ((ip [5] == CEE_CALL) && (cmethod = mini_get_method (method, read32 (ip + 6), NULL, generic_context)) &&
5895                                                 (cmethod->klass == mono_defaults.monotype_class->parent) &&
5896                                                 (strcmp (cmethod->name, "GetTypeFromHandle") == 0) && ip_in_bb (cfg, bblock, ip + 5)) {
5897                                         MonoClass *tclass = mono_class_from_mono_type (handle);
5898                                         mono_class_init (tclass);
5899                                         if (cfg->compile_aot)
5900                                                 NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n);
5901                                         else
5902                                                 NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
5903                                         ins->type = STACK_OBJ;
5904                                         ins->klass = cmethod->klass;
5905                                         ip += 5;
5906                                 } else {
5907                                         MonoInst *store, *addr, *vtvar;
5908
5909                                         if (cfg->compile_aot)
5910                                                 NEW_LDTOKENCONST (cfg, ins, image, n);
5911                                         else
5912                                                 NEW_PCONST (cfg, ins, handle);
5913                                         vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
5914                                         NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
5915                                         NEW_INDSTORE (cfg, store, addr, ins, &mono_defaults.int_class->byval_arg);
5916                                         MONO_ADD_INS (bblock, store);
5917                                         NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
5918                                 }
5919                         }
5920
5921                         *sp++ = ins;
5922                         ip += 5;
5923                         break;
5924                 }
5925                 case CEE_CONV_U2:
5926                 case CEE_CONV_U1:
5927                 case CEE_CONV_I:
5928                         CHECK_STACK (1);
5929                         ADD_UNOP (*ip);
5930                         ip++;
5931                         break;
5932                 case CEE_ADD_OVF:
5933                 case CEE_ADD_OVF_UN:
5934                 case CEE_MUL_OVF:
5935                 case CEE_MUL_OVF_UN:
5936                 case CEE_SUB_OVF:
5937                 case CEE_SUB_OVF_UN:
5938                         CHECK_STACK (2);
5939                         ADD_BINOP (*ip);
5940                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
5941                                 --sp;
5942                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
5943                                 mono_get_got_var (cfg);
5944                         }
5945                         ip++;
5946                         break;
5947                 case CEE_ENDFINALLY:
5948                         MONO_INST_NEW (cfg, ins, *ip);
5949                         MONO_ADD_INS (bblock, ins);
5950                         ins->cil_code = ip++;
5951                         start_new_bblock = 1;
5952
5953                         /*
5954                          * Control will leave the method so empty the stack, otherwise
5955                          * the next basic block will start with a nonempty stack.
5956                          */
5957                         while (sp != stack_start) {
5958                                 MONO_INST_NEW (cfg, ins, CEE_POP);
5959                                 ins->cil_code = ip;
5960                                 sp--;
5961                                 ins->inst_i0 = *sp;
5962                                 MONO_ADD_INS (bblock, ins);
5963                         }
5964                         break;
5965                 case CEE_LEAVE:
5966                 case CEE_LEAVE_S: {
5967                         GList *handlers;
5968
5969                         if (*ip == CEE_LEAVE) {
5970                                 CHECK_OPSIZE (5);
5971                                 target = ip + 5 + (gint32)read32(ip + 1);
5972                         } else {
5973                                 CHECK_OPSIZE (2);
5974                                 target = ip + 2 + (signed char)(ip [1]);
5975                         }
5976
5977                         /* empty the stack */
5978                         while (sp != stack_start) {
5979                                 MONO_INST_NEW (cfg, ins, CEE_POP);
5980                                 ins->cil_code = ip;
5981                                 sp--;
5982                                 ins->inst_i0 = *sp;
5983                                 MONO_ADD_INS (bblock, ins);
5984                         }
5985
5986                         /* 
5987                          * If this leave statement is in a catch block, check for a
5988                          * pending exception, and rethrow it if necessary.
5989                          */
5990                         for (i = 0; i < header->num_clauses; ++i) {
5991                                 MonoExceptionClause *clause = &header->clauses [i];
5992
5993                                 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)) {
5994                                         int temp;
5995                                         MonoInst *load;
5996
5997                                         NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
5998                                         load->cil_code = ip;
5999
6000                                         temp = mono_emit_jit_icall (cfg, bblock, mono_thread_get_pending_exception, NULL, ip);
6001                                         NEW_TEMPLOAD (cfg, *sp, temp);
6002                                 
6003                                         MONO_INST_NEW (cfg, ins, OP_THROW_OR_NULL);
6004                                         ins->inst_left = *sp;
6005                                         ins->inst_right = load;
6006                                         ins->cil_code = ip;
6007                                         MONO_ADD_INS (bblock, ins);
6008                                 }
6009                         }
6010
6011                         /* fixme: call fault handler ? */
6012
6013                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
6014                                 GList *tmp;
6015                                 for (tmp = handlers; tmp; tmp = tmp->next) {
6016                                         tblock = tmp->data;
6017                                         link_bblock (cfg, bblock, tblock);
6018                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
6019                                         ins->cil_code = ip;
6020                                         ins->inst_target_bb = tblock;
6021                                         MONO_ADD_INS (bblock, ins);
6022                                 }
6023                                 g_list_free (handlers);
6024                         } 
6025
6026                         MONO_INST_NEW (cfg, ins, CEE_BR);
6027                         ins->cil_code = ip;
6028                         MONO_ADD_INS (bblock, ins);
6029                         GET_BBLOCK (cfg, bbhash, tblock, target);
6030                         link_bblock (cfg, bblock, tblock);
6031                         CHECK_BBLOCK (target, ip, tblock);
6032                         ins->inst_target_bb = tblock;
6033                         start_new_bblock = 1;
6034
6035                         if (*ip == CEE_LEAVE)
6036                                 ip += 5;
6037                         else
6038                                 ip += 2;
6039
6040                         break;
6041                 }
6042                 case CEE_STIND_I:
6043                         CHECK_STACK (2);
6044                         MONO_INST_NEW (cfg, ins, *ip);
6045                         sp -= 2;
6046                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6047                         MONO_ADD_INS (bblock, ins);
6048                         ins->cil_code = ip++;
6049                         ins->inst_i0 = sp [0];
6050                         ins->inst_i1 = sp [1];
6051                         inline_costs += 1;
6052                         break;
6053                 case CEE_CONV_U:
6054                         CHECK_STACK (1);
6055                         ADD_UNOP (*ip);
6056                         ip++;
6057                         break;
6058                 /* trampoline mono specific opcodes */
6059                 case MONO_CUSTOM_PREFIX: {
6060
6061                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
6062
6063                         CHECK_OPSIZE (2);
6064                         switch (ip [1]) {
6065
6066                         case CEE_MONO_ICALL: {
6067                                 int temp;
6068                                 gpointer func;
6069                                 MonoJitICallInfo *info;
6070
6071                                 token = read32 (ip + 2);
6072                                 func = mono_method_get_wrapper_data (method, token);
6073                                 info = mono_find_jit_icall_by_addr (func);
6074                                 g_assert (info);
6075
6076                                 CHECK_STACK (info->sig->param_count);
6077                                 sp -= info->sig->param_count;
6078
6079                                 temp = mono_emit_jit_icall (cfg, bblock, info->func, sp, ip);
6080                                 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
6081                                         NEW_TEMPLOAD (cfg, *sp, temp);
6082                                         sp++;
6083                                 }
6084
6085                                 ip += 6;
6086                                 inline_costs += 10 * num_calls++;
6087
6088                                 break;
6089                         }
6090                         case CEE_MONO_LDPTR:
6091                                 CHECK_STACK_OVF (1);
6092                                 CHECK_OPSIZE (6);
6093                                 token = read32 (ip + 2);
6094                                 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
6095                                 ins->cil_code = ip;
6096                                 *sp++ = ins;
6097                                 ip += 6;
6098                                 inline_costs += 10 * num_calls++;
6099                                 /* Can't embed random pointers into AOT code */
6100                                 cfg->disable_aot = 1;
6101                                 break;
6102                         case CEE_MONO_VTADDR:
6103                                 CHECK_STACK (1);
6104                                 --sp;
6105                                 MONO_INST_NEW (cfg, ins, OP_VTADDR);
6106                                 ins->cil_code = ip;
6107                                 ins->type = STACK_MP;
6108                                 ins->inst_left = *sp;
6109                                 *sp++ = ins;
6110                                 ip += 2;
6111                                 break;
6112                         case CEE_MONO_NEWOBJ: {
6113                                 MonoInst *iargs [2];
6114                                 int temp;
6115                                 CHECK_STACK_OVF (1);
6116                                 CHECK_OPSIZE (6);
6117                                 token = read32 (ip + 2);
6118                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
6119                                 mono_class_init (klass);
6120                                 NEW_DOMAINCONST (cfg, iargs [0]);
6121                                 NEW_CLASSCONST (cfg, iargs [1], klass);
6122                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
6123                                 NEW_TEMPLOAD (cfg, *sp, temp);
6124                                 sp++;
6125                                 ip += 6;
6126                                 inline_costs += 10 * num_calls++;
6127                                 break;
6128                         }
6129                         case CEE_MONO_OBJADDR:
6130                                 CHECK_STACK (1);
6131                                 --sp;
6132                                 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
6133                                 ins->cil_code = ip;
6134                                 ins->type = STACK_MP;
6135                                 ins->inst_left = *sp;
6136                                 *sp++ = ins;
6137                                 ip += 2;
6138                                 break;
6139                         case CEE_MONO_LDNATIVEOBJ:
6140                                 CHECK_STACK (1);
6141                                 CHECK_OPSIZE (6);
6142                                 token = read32 (ip + 2);
6143                                 klass = mono_method_get_wrapper_data (method, token);
6144                                 g_assert (klass->valuetype);
6145                                 mono_class_init (klass);
6146                                 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
6147                                 sp [-1] = ins;
6148                                 ip += 6;
6149                                 break;
6150                         case CEE_MONO_RETOBJ:
6151                                 g_assert (cfg->ret);
6152                                 g_assert (mono_method_signature (method)->pinvoke); 
6153                                 CHECK_STACK (1);
6154                                 --sp;
6155                                 
6156                                 CHECK_OPSIZE (6);
6157                                 token = read32 (ip + 2);    
6158                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
6159
6160                                 NEW_RETLOADA (cfg, ins);
6161                                 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE);
6162                                 
6163                                 if (sp != stack_start)
6164                                         goto unverified;
6165                                 
6166                                 MONO_INST_NEW (cfg, ins, CEE_BR);
6167                                 ins->cil_code = ip;
6168                                 ins->inst_target_bb = end_bblock;
6169                                 MONO_ADD_INS (bblock, ins);
6170                                 link_bblock (cfg, bblock, end_bblock);
6171                                 start_new_bblock = 1;
6172                                 ip += 6;
6173                                 break;
6174                         case CEE_MONO_CISINST:
6175                         case CEE_MONO_CCASTCLASS: {
6176                                 int token;
6177                                 CHECK_STACK (1);
6178                                 --sp;
6179                                 CHECK_OPSIZE (6);
6180                                 token = read32 (ip + 2);
6181                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
6182                                 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_CISINST) ? OP_CISINST : OP_CCASTCLASS);
6183                                 ins->type = STACK_I4;
6184                                 ins->inst_left = *sp;
6185                                 ins->inst_newa_class = klass;
6186                                 ins->cil_code = ip;
6187                                 *sp++ = emit_tree (cfg, bblock, ins, ip + 6);
6188                                 ip += 6;
6189                                 break;
6190                         }
6191                         case CEE_MONO_SAVE_LMF:
6192                         case CEE_MONO_RESTORE_LMF:
6193 #ifdef MONO_ARCH_HAVE_LMF_OPS
6194                                 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_SAVE_LMF) ? OP_SAVE_LMF : OP_RESTORE_LMF);
6195                                 MONO_ADD_INS (bblock, ins);
6196                                 cfg->need_lmf_area = TRUE;
6197 #endif
6198                                 ip += 2;
6199                                 break;
6200                         case CEE_MONO_CLASSCONST:
6201                                 CHECK_STACK_OVF (1);
6202                                 CHECK_OPSIZE (6);
6203                                 token = read32 (ip + 2);
6204                                 NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
6205                                 ins->cil_code = ip;
6206                                 *sp++ = ins;
6207                                 ip += 6;
6208                                 inline_costs += 10 * num_calls++;
6209                                 break;
6210                         case CEE_MONO_NOT_TAKEN:
6211                                 bblock->out_of_line = TRUE;
6212                                 ip += 2;
6213                                 break;
6214                         default:
6215                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
6216                                 break;
6217                         }
6218                         break;
6219                 }
6220                 case CEE_PREFIX1: {
6221                         CHECK_OPSIZE (2);
6222                         switch (ip [1]) {
6223                         case CEE_ARGLIST: {
6224                                 /* somewhat similar to LDTOKEN */
6225                                 MonoInst *addr, *vtvar;
6226                                 CHECK_STACK_OVF (1);
6227                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
6228
6229                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
6230                                 addr->cil_code = ip;
6231                                 MONO_INST_NEW (cfg, ins, OP_ARGLIST);
6232                                 ins->cil_code = ip;
6233                                 ins->inst_left = addr;
6234                                 MONO_ADD_INS (bblock, ins);
6235                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
6236                                 ins->cil_code = ip;
6237                                 *sp++ = ins;
6238                                 ip += 2;
6239                                 break;
6240                         }
6241                         case CEE_CEQ:
6242                         case CEE_CGT:
6243                         case CEE_CGT_UN:
6244                         case CEE_CLT:
6245                         case CEE_CLT_UN: {
6246                                 MonoInst *cmp;
6247                                 CHECK_STACK (2);
6248                                 /*
6249                                  * The following transforms:
6250                                  *    CEE_CEQ    into OP_CEQ
6251                                  *    CEE_CGT    into OP_CGT
6252                                  *    CEE_CGT_UN into OP_CGT_UN
6253                                  *    CEE_CLT    into OP_CLT
6254                                  *    CEE_CLT_UN into OP_CLT_UN
6255                                  */
6256                                 MONO_INST_NEW (cfg, cmp, 256 + ip [1]);
6257                                 
6258                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
6259                                 sp -= 2;
6260                                 cmp->inst_i0 = sp [0];
6261                                 cmp->inst_i1 = sp [1];
6262                                 cmp->cil_code = ip;
6263                                 type_from_op (cmp);
6264                                 CHECK_TYPE (cmp);
6265                                 if ((sp [0]->type == STACK_I8) || ((sizeof (gpointer) == 8) && ((sp [0]->type == STACK_PTR) || (sp [0]->type == STACK_OBJ) || (sp [0]->type == STACK_MP))))
6266                                         cmp->opcode = OP_LCOMPARE;
6267                                 else
6268                                         cmp->opcode = OP_COMPARE;
6269                                 ins->cil_code = ip;
6270                                 ins->type = STACK_I4;
6271                                 ins->inst_i0 = cmp;
6272                                 *sp++ = ins;
6273                                 /* spill it to reduce the expression complexity
6274                                  * and workaround bug 54209 
6275                                  */
6276                                 if (cmp->inst_left->type == STACK_I8) {
6277                                         --sp;
6278                                         *sp++ = emit_tree (cfg, bblock, ins, ip + 2);
6279                                 }
6280                                 ip += 2;
6281                                 break;
6282                         }
6283                         case CEE_LDFTN: {
6284                                 MonoInst *argconst;
6285                                 int temp;
6286
6287                                 CHECK_STACK_OVF (1);
6288                                 CHECK_OPSIZE (6);
6289                                 n = read32 (ip + 2);
6290                                 cmethod = mini_get_method (method, n, NULL, generic_context);
6291                                 if (!cmethod)
6292                                         goto load_error;
6293                                 mono_class_init (cmethod->klass);
6294
6295                                 if (mono_use_security_manager) {
6296                                         check_linkdemand (cfg, method, cmethod, bblock, ip);
6297                                 }
6298
6299                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
6300
6301                                 NEW_METHODCONST (cfg, argconst, cmethod);
6302                                 if (method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
6303                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
6304                                 else
6305                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn_nosync, &argconst, ip);
6306                                 NEW_TEMPLOAD (cfg, *sp, temp);
6307                                 sp ++;
6308                                 
6309                                 ip += 6;
6310                                 inline_costs += 10 * num_calls++;
6311                                 break;
6312                         }
6313                         case CEE_LDVIRTFTN: {
6314                                 MonoInst *args [2];
6315                                 int temp;
6316
6317                                 CHECK_STACK (1);
6318                                 CHECK_OPSIZE (6);
6319                                 n = read32 (ip + 2);
6320                                 cmethod = mini_get_method (method, n, NULL, generic_context);
6321                                 if (!cmethod)
6322                                         goto load_error;
6323                                 mono_class_init (cmethod->klass);
6324
6325                                 if (mono_use_security_manager) {
6326                                         check_linkdemand (cfg, method, cmethod, bblock, ip);
6327                                 }
6328
6329                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
6330
6331                                 --sp;
6332                                 args [0] = *sp;
6333                                 NEW_METHODCONST (cfg, args [1], cmethod);
6334                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
6335                                 NEW_TEMPLOAD (cfg, *sp, temp);
6336                                 sp ++;
6337
6338                                 ip += 6;
6339                                 inline_costs += 10 * num_calls++;
6340                                 break;
6341                         }
6342                         case CEE_LDARG:
6343                                 CHECK_STACK_OVF (1);
6344                                 CHECK_OPSIZE (4);
6345                                 n = read16 (ip + 2);
6346                                 CHECK_ARG (n);
6347                                 NEW_ARGLOAD (cfg, ins, n);
6348                                 ins->cil_code = ip;
6349                                 *sp++ = ins;
6350                                 ip += 4;
6351                                 break;
6352                         case CEE_LDARGA:
6353                                 CHECK_STACK_OVF (1);
6354                                 CHECK_OPSIZE (4);
6355                                 n = read16 (ip + 2);
6356                                 CHECK_ARG (n);
6357                                 NEW_ARGLOADA (cfg, ins, n);
6358                                 ins->cil_code = ip;
6359                                 *sp++ = ins;
6360                                 ip += 4;
6361                                 break;
6362                         case CEE_STARG:
6363                                 CHECK_STACK (1);
6364                                 --sp;
6365                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
6366                                 CHECK_OPSIZE (4);
6367                                 n = read16 (ip + 2);
6368                                 CHECK_ARG (n);
6369                                 NEW_ARGSTORE (cfg, ins, n, *sp);
6370                                 ins->cil_code = ip;
6371                                 if (ins->opcode == CEE_STOBJ) {
6372                                         NEW_ARGLOADA (cfg, ins, n);
6373                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
6374                                 } else
6375                                         MONO_ADD_INS (bblock, ins);
6376                                 ip += 4;
6377                                 break;
6378                         case CEE_LDLOC:
6379                                 CHECK_STACK_OVF (1);
6380                                 CHECK_OPSIZE (4);
6381                                 n = read16 (ip + 2);
6382                                 CHECK_LOCAL (n);
6383                                 NEW_LOCLOAD (cfg, ins, n);
6384                                 ins->cil_code = ip;
6385                                 *sp++ = ins;
6386                                 ip += 4;
6387                                 break;
6388                         case CEE_LDLOCA:
6389                                 CHECK_STACK_OVF (1);
6390                                 CHECK_OPSIZE (4);
6391                                 n = read16 (ip + 2);
6392                                 CHECK_LOCAL (n);
6393                                 NEW_LOCLOADA (cfg, ins, n);
6394                                 ins->cil_code = ip;
6395                                 *sp++ = ins;
6396                                 ip += 4;
6397                                 break;
6398                         case CEE_STLOC:
6399                                 CHECK_STACK (1);
6400                                 --sp;
6401                                 CHECK_OPSIZE (4);
6402                                 n = read16 (ip + 2);
6403                                 CHECK_LOCAL (n);
6404                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
6405                                 NEW_LOCSTORE (cfg, ins, n, *sp);
6406                                 ins->cil_code = ip;
6407                                 if (ins->opcode == CEE_STOBJ) {
6408                                         NEW_LOCLOADA (cfg, ins, n);
6409                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
6410                                 } else
6411                                         MONO_ADD_INS (bblock, ins);
6412                                 ip += 4;
6413                                 inline_costs += 1;
6414                                 break;
6415                         case CEE_LOCALLOC:
6416                                 CHECK_STACK (1);
6417                                 --sp;
6418                                 if (sp != stack_start) 
6419                                         goto unverified;
6420                                 if (cfg->method != method) 
6421                                         /* 
6422                                          * Inlining this into a loop in a parent could lead to 
6423                                          * stack overflows which is different behavior than the
6424                                          * non-inlined case, thus disable inlining in this case.
6425                                          */
6426                                         goto inline_failure;
6427                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
6428                                 ins->inst_left = *sp;
6429                                 ins->cil_code = ip;
6430                                 ins->type = STACK_MP;
6431
6432                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
6433                                 if (header->init_locals)
6434                                         ins->flags |= MONO_INST_INIT;
6435
6436                                 *sp++ = ins;
6437                                 ip += 2;
6438                                 /* FIXME: set init flag if locals init is set in this method */
6439                                 break;
6440                         case CEE_ENDFILTER: {
6441                                 MonoExceptionClause *clause, *nearest;
6442                                 int cc, nearest_num;
6443
6444                                 CHECK_STACK (1);
6445                                 --sp;
6446                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
6447                                         goto unverified;
6448                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
6449                                 ins->inst_left = *sp;
6450                                 ins->cil_code = ip;
6451                                 MONO_ADD_INS (bblock, ins);
6452                                 start_new_bblock = 1;
6453                                 ip += 2;
6454
6455                                 nearest = NULL;
6456                                 nearest_num = 0;
6457                                 for (cc = 0; cc < header->num_clauses; ++cc) {
6458                                         clause = &header->clauses [cc];
6459                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
6460                                                 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
6461                                             (!nearest || (clause->data.filter_offset < nearest->data.filter_offset))) {
6462                                                 nearest = clause;
6463                                                 nearest_num = cc;
6464                                         }
6465                                 }
6466                                 g_assert (nearest);
6467                                 if ((ip - header->code) != nearest->handler_offset)
6468                                         goto unverified;
6469
6470                                 break;
6471                         }
6472                         case CEE_UNALIGNED_:
6473                                 ins_flag |= MONO_INST_UNALIGNED;
6474                                 /* FIXME: record alignment? we can assume 1 for now */
6475                                 CHECK_OPSIZE (3);
6476                                 ip += 3;
6477                                 break;
6478                         case CEE_VOLATILE_:
6479                                 ins_flag |= MONO_INST_VOLATILE;
6480                                 ip += 2;
6481                                 break;
6482                         case CEE_TAIL_:
6483                                 ins_flag   |= MONO_INST_TAILCALL;
6484                                 cfg->flags |= MONO_CFG_HAS_TAIL;
6485                                 /* Can't inline tail calls at this time */
6486                                 inline_costs += 100000;
6487                                 ip += 2;
6488                                 break;
6489                         case CEE_INITOBJ:
6490                                 CHECK_STACK (1);
6491                                 --sp;
6492                                 CHECK_OPSIZE (6);
6493                                 token = read32 (ip + 2);
6494                                 klass = mini_get_class (method, token, generic_context);
6495                                 if (!klass)
6496                                         goto load_error;
6497                                 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
6498                                         MonoInst *store, *load;
6499                                         NEW_PCONST (cfg, load, NULL);
6500                                         load->cil_code = ip;
6501                                         load->type = STACK_OBJ;
6502                                         MONO_INST_NEW (cfg, store, CEE_STIND_REF);
6503                                         store->cil_code = ip;
6504                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
6505                                         MONO_ADD_INS (bblock, store);
6506                                         store->inst_i0 = sp [0];
6507                                         store->inst_i1 = load;
6508                                 } else {
6509                                         handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
6510                                 }
6511                                 ip += 6;
6512                                 inline_costs += 1;
6513                                 break;
6514                         case CEE_CONSTRAINED_:
6515                                 /* FIXME: implement */
6516                                 CHECK_OPSIZE (6);
6517                                 token = read32 (ip + 2);
6518                                 constrained_call = mono_class_get_full (image, token, generic_context);
6519                                 if (!constrained_call)
6520                                         goto load_error;
6521                                 ip += 6;
6522                                 break;
6523                         case CEE_CPBLK:
6524                         case CEE_INITBLK: {
6525                                 MonoInst *iargs [3];
6526                                 CHECK_STACK (3);
6527                                 sp -= 3;
6528                                 if ((cfg->opt & MONO_OPT_INTRINS) && (ip [1] == CEE_CPBLK) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5)) {
6529                                         MonoInst *copy;
6530                                         MONO_INST_NEW (cfg, copy, OP_MEMCPY);
6531                                         copy->inst_left = sp [0];
6532                                         copy->inst_right = sp [1];
6533                                         copy->cil_code = ip;
6534                                         copy->unused = n;
6535                                         MONO_ADD_INS (bblock, copy);
6536                                         ip += 2;
6537                                         break;
6538                                 }
6539                                 iargs [0] = sp [0];
6540                                 iargs [1] = sp [1];
6541                                 iargs [2] = sp [2];
6542                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
6543                                 if (ip [1] == CEE_CPBLK) {
6544                                         MonoMethod *memcpy_method = get_memcpy_method ();
6545                                         mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6546                                 } else {
6547                                         MonoMethod *memset_method = get_memset_method ();
6548                                         mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
6549                                 }
6550                                 ip += 2;
6551                                 inline_costs += 1;
6552                                 break;
6553                         }
6554                         case CEE_NO_:
6555                                 CHECK_OPSIZE (3);
6556                                 if (ip [2] & 0x1)
6557                                         ins_flag |= MONO_INST_NOTYPECHECK;
6558                                 if (ip [2] & 0x2)
6559                                         ins_flag |= MONO_INST_NORANGECHECK;
6560                                 /* we ignore the no-nullcheck for now since we
6561                                  * really do it explicitly only when doing callvirt->call
6562                                  */
6563                                 ip += 3;
6564                                 break;
6565                         case CEE_RETHROW: {
6566                                 MonoInst *load;
6567                                 int handler_offset = -1;
6568
6569                                 for (i = 0; i < header->num_clauses; ++i) {
6570                                         MonoExceptionClause *clause = &header->clauses [i];
6571                                         if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY))
6572                                                 handler_offset = clause->handler_offset;
6573                                 }
6574
6575                                 bblock->flags |= BB_EXCEPTION_UNSAFE;
6576
6577                                 g_assert (handler_offset != -1);
6578
6579                                 NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
6580                                 load->cil_code = ip;
6581                                 MONO_INST_NEW (cfg, ins, OP_RETHROW);
6582                                 ins->inst_left = load;
6583                                 ins->cil_code = ip;
6584                                 MONO_ADD_INS (bblock, ins);
6585                                 sp = stack_start;
6586                                 link_bblock (cfg, bblock, end_bblock);
6587                                 start_new_bblock = 1;
6588                                 ip += 2;
6589                                 mono_get_got_var (cfg);
6590                                 break;
6591                         }
6592                         case CEE_SIZEOF:
6593                                 CHECK_STACK_OVF (1);
6594                                 CHECK_OPSIZE (6);
6595                                 token = read32 (ip + 2);
6596                                 /* FIXXME: handle generics. */
6597                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
6598                                         MonoType *type = mono_type_create_from_typespec (image, token);
6599                                         token = mono_type_size (type, &align);
6600                                 } else {
6601                                         MonoClass *klass = mono_class_get_full (image, token, generic_context);
6602                                         if (!klass)
6603                                                 goto load_error;
6604                                         mono_class_init (klass);
6605                                         token = mono_class_value_size (klass, &align);
6606                                 }
6607                                 NEW_ICONST (cfg, ins, token);
6608                                 ins->cil_code = ip;
6609                                 *sp++= ins;
6610                                 ip += 6;
6611                                 break;
6612                         case CEE_REFANYTYPE:
6613                                 CHECK_STACK (1);
6614                                 MONO_INST_NEW (cfg, ins, OP_REFANYTYPE);
6615                                 --sp;
6616                                 ins->type = STACK_MP;
6617                                 ins->inst_left = *sp;
6618                                 ins->type = STACK_VTYPE;
6619                                 ins->klass = mono_defaults.typehandle_class;
6620                                 ins->cil_code = ip;
6621                                 ip += 2;
6622                                 *sp++ = ins;
6623                                 break;
6624                         case CEE_READONLY_:
6625                                 ip += 2;
6626                                 break;
6627                         default:
6628                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
6629                         }
6630                         break;
6631                 }
6632                 default:
6633                         g_error ("opcode 0x%02x not handled", *ip);
6634                 }
6635         }
6636         if (start_new_bblock != 1)
6637                 goto unverified;
6638
6639         bblock->cil_length = ip - bblock->cil_code;
6640         bblock->next_bb = end_bblock;
6641
6642         if (cfg->method == method && cfg->domainvar) {
6643                 MonoInst *store;
6644                 MonoInst *get_domain;
6645                 
6646                 if (! (get_domain = mono_arch_get_domain_intrinsic (cfg))) {
6647                         MonoCallInst *call;
6648                         
6649                         MONO_INST_NEW_CALL (cfg, call, CEE_CALL);
6650                         call->signature = helper_sig_domain_get;
6651                         call->inst.type = STACK_PTR;
6652                         call->fptr = mono_domain_get;
6653                         get_domain = (MonoInst*)call;
6654                 }
6655                 
6656                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
6657                 MONO_ADD_INS (init_localsbb, store);
6658         }
6659
6660         if (cfg->method == method && cfg->got_var)
6661                 mono_emit_load_got_addr (cfg);
6662
6663         if (header->init_locals) {
6664                 MonoInst *store;
6665                 for (i = 0; i < header->num_locals; ++i) {
6666                         MonoType *ptype = header->locals [i];
6667                         int t = ptype->type;
6668                         if (t == MONO_TYPE_VALUETYPE && ptype->data.klass->enumtype)
6669                                 t = ptype->data.klass->enum_basetype->type;
6670                         if (ptype->byref) {
6671                                 NEW_PCONST (cfg, ins, NULL);
6672                                 NEW_LOCSTORE (cfg, store, i, ins);
6673                                 MONO_ADD_INS (init_localsbb, store);
6674                         } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
6675                                 NEW_ICONST (cfg, ins, 0);
6676                                 NEW_LOCSTORE (cfg, store, i, ins);
6677                                 MONO_ADD_INS (init_localsbb, store);
6678                         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
6679                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
6680                                 ins->type = STACK_I8;
6681                                 ins->inst_l = 0;
6682                                 NEW_LOCSTORE (cfg, store, i, ins);
6683                                 MONO_ADD_INS (init_localsbb, store);
6684                         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
6685                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
6686                                 ins->type = STACK_R8;
6687                                 ins->inst_p0 = (void*)&r8_0;
6688                                 NEW_LOCSTORE (cfg, store, i, ins);
6689                                 MONO_ADD_INS (init_localsbb, store);
6690                         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
6691                                    ((t == MONO_TYPE_GENERICINST) && mono_metadata_generic_class_is_valuetype (ptype->data.generic_class))) {
6692                                 NEW_LOCLOADA (cfg, ins, i);
6693                                 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (ptype), NULL, NULL);
6694                         } else {
6695                                 NEW_PCONST (cfg, ins, NULL);
6696                                 NEW_LOCSTORE (cfg, store, i, ins);
6697                                 MONO_ADD_INS (init_localsbb, store);
6698                         }
6699                 }
6700         }
6701
6702         /* resolve backward branches in the middle of an existing basic block */
6703         for (tmp = bb_recheck; tmp; tmp = tmp->next) {
6704                 bblock = tmp->data;
6705                 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
6706                 tblock = find_previous (bbhash, start_bblock, bblock->cil_code);
6707                 if (tblock != start_bblock) {
6708                         int l;
6709                         split_bblock (cfg, tblock, bblock);
6710                         l = bblock->cil_code - header->code;
6711                         bblock->cil_length = tblock->cil_length - l;
6712                         tblock->cil_length = l;
6713                 } else {
6714                         g_print ("recheck failed.\n");
6715                 }
6716         }
6717
6718         if (cfg->method == method) {
6719                 MonoBasicBlock *bb;
6720                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
6721                         bb->region = mono_find_block_region (cfg, bb->real_offset);
6722                         if (cfg->spvars)
6723                                 mono_create_spvar_for_region (cfg, bb->region);
6724                         if (cfg->verbose_level > 2)
6725                                 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
6726                 }
6727         } else {
6728                 g_hash_table_destroy (bbhash);
6729         }
6730
6731         g_slist_free (class_inits);
6732         dont_inline = g_list_remove (dont_inline, method);
6733         return inline_costs;
6734
6735  inline_failure:
6736         if (cfg->method != method) 
6737                 g_hash_table_destroy (bbhash);
6738         g_slist_free (class_inits);
6739         dont_inline = g_list_remove (dont_inline, method);
6740         return -1;
6741
6742  load_error:
6743         if (cfg->method != method)
6744                 g_hash_table_destroy (bbhash);
6745         g_slist_free (class_inits);
6746         dont_inline = g_list_remove (dont_inline, method);
6747         return -1;
6748
6749  unverified:
6750         if (cfg->method != method) 
6751                 g_hash_table_destroy (bbhash);
6752         g_slist_free (class_inits);
6753         g_error ("Invalid IL code at IL%04x in %s: %s\n", (int)(ip - header->code), 
6754                  mono_method_full_name (method, TRUE), mono_disasm_code_one (NULL, method, ip, NULL));
6755         dont_inline = g_list_remove (dont_inline, method);
6756         return -1;
6757 }
6758
6759 void
6760 mono_print_tree (MonoInst *tree) {
6761         int arity;
6762
6763         if (!tree)
6764                 return;
6765
6766         arity = mono_burg_arity [tree->opcode];
6767
6768         printf (" %s%s", arity?"(":"",  mono_inst_name (tree->opcode));
6769
6770         switch (tree->opcode) {
6771         case OP_ICONST:
6772                 printf ("[%d]", (int)tree->inst_c0);
6773                 break;
6774         case OP_I8CONST:
6775                 printf ("[%lld]", (long long)tree->inst_l);
6776                 break;
6777         case OP_R8CONST:
6778                 printf ("[%f]", *(double*)tree->inst_p0);
6779                 break;
6780         case OP_R4CONST:
6781                 printf ("[%f]", *(float*)tree->inst_p0);
6782                 break;
6783         case OP_ARG:
6784         case OP_LOCAL:
6785                 printf ("[%d]", (int)tree->inst_c0);
6786                 break;
6787         case OP_REGOFFSET:
6788                 if (tree->inst_offset < 0)
6789                         printf ("[-0x%x(%s)]", (int)(-tree->inst_offset), mono_arch_regname (tree->inst_basereg));
6790                 else
6791                         printf ("[0x%x(%s)]", (int)(tree->inst_offset), mono_arch_regname (tree->inst_basereg));
6792                 break;
6793         case OP_REGVAR:
6794                 printf ("[%s]", mono_arch_regname (tree->dreg));
6795                 break;
6796         case CEE_NEWARR:
6797                 printf ("[%s]",  tree->inst_newa_class->name);
6798                 mono_print_tree (tree->inst_newa_len);
6799                 break;
6800         case CEE_CALL:
6801         case CEE_CALLVIRT:
6802         case OP_FCALL:
6803         case OP_FCALLVIRT:
6804         case OP_LCALL:
6805         case OP_LCALLVIRT:
6806         case OP_VCALL:
6807         case OP_VCALLVIRT:
6808         case OP_VOIDCALL:
6809         case OP_VOIDCALLVIRT: {
6810                 MonoCallInst *call = (MonoCallInst*)tree;
6811                 if (call->method)
6812                         printf ("[%s]", call->method->name);
6813                 else if (call->fptr) {
6814                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (call->fptr);
6815                         if (info)
6816                                 printf ("[%s]", info->name);
6817                 }
6818                 break;
6819         }
6820         case OP_PHI: {
6821                 int i;
6822                 printf ("[%d (", (int)tree->inst_c0);
6823                 for (i = 0; i < tree->inst_phi_args [0]; i++) {
6824                         if (i)
6825                                 printf (", ");
6826                         printf ("%d", tree->inst_phi_args [i + 1]);
6827                 }
6828                 printf (")]");
6829                 break;
6830         }
6831         case OP_RENAME:
6832         case OP_RETARG:
6833         case CEE_NOP:
6834         case CEE_JMP:
6835         case CEE_BREAK:
6836                 break;
6837         case OP_LOAD_MEMBASE:
6838         case OP_LOADI4_MEMBASE:
6839         case OP_LOADU4_MEMBASE:
6840         case OP_LOADU1_MEMBASE:
6841         case OP_LOADI1_MEMBASE:
6842         case OP_LOADU2_MEMBASE:
6843         case OP_LOADI2_MEMBASE:
6844                 printf ("[%s] <- [%s + 0x%x]", mono_arch_regname (tree->dreg), mono_arch_regname (tree->inst_basereg), (int)tree->inst_offset);
6845                 break;
6846         case CEE_BR:
6847         case OP_CALL_HANDLER:
6848                 printf ("[B%d]", tree->inst_target_bb->block_num);
6849                 break;
6850         case CEE_SWITCH:
6851         case CEE_ISINST:
6852         case CEE_CASTCLASS:
6853         case OP_OUTARG:
6854         case OP_CALL_REG:
6855         case OP_FCALL_REG:
6856         case OP_LCALL_REG:
6857         case OP_VCALL_REG:
6858         case OP_VOIDCALL_REG:
6859                 mono_print_tree (tree->inst_left);
6860                 break;
6861         case CEE_BNE_UN:
6862         case CEE_BEQ:
6863         case CEE_BLT:
6864         case CEE_BLT_UN:
6865         case CEE_BGT:
6866         case CEE_BGT_UN:
6867         case CEE_BGE:
6868         case CEE_BGE_UN:
6869         case CEE_BLE:
6870         case CEE_BLE_UN:
6871                 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
6872                 mono_print_tree (tree->inst_left);
6873                 break;
6874         default:
6875                 if (!mono_arch_print_tree(tree, arity)) {
6876                         if (arity) {
6877                                 mono_print_tree (tree->inst_left);
6878                                 if (arity > 1)
6879                                         mono_print_tree (tree->inst_right);
6880                         }
6881                 }
6882                 break;
6883         }
6884
6885         if (arity)
6886                 printf (")");
6887 }
6888
6889 void
6890 mono_print_tree_nl (MonoInst *tree)
6891 {
6892         mono_print_tree (tree);
6893         printf ("\n");
6894 }
6895
6896 static void
6897 create_helper_signature (void)
6898 {
6899         helper_sig_domain_get = mono_create_icall_signature ("ptr");
6900         helper_sig_class_init_trampoline = mono_create_icall_signature ("void");
6901 }
6902
6903 gconstpointer
6904 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
6905 {
6906         char *name;
6907         MonoMethod *wrapper;
6908         gconstpointer code;
6909         
6910         if (callinfo->wrapper)
6911                 return callinfo->wrapper;
6912         
6913         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
6914         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func);
6915         /* Must be domain neutral since there is only one copy */
6916         code = mono_jit_compile_method_with_opt (wrapper, default_opt | MONO_OPT_SHARED);
6917
6918         if (!callinfo->wrapper) {
6919                 callinfo->wrapper = code;
6920                 mono_register_jit_icall_wrapper (callinfo, code);
6921                 mono_debug_add_icall_wrapper (wrapper, callinfo);
6922         }
6923
6924         g_free (name);
6925         return callinfo->wrapper;
6926 }
6927
6928 static void
6929 mono_init_trampolines (void)
6930 {
6931         mono_trampoline_code [MONO_TRAMPOLINE_GENERIC] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_GENERIC);
6932         mono_trampoline_code [MONO_TRAMPOLINE_JUMP] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_JUMP);
6933         mono_trampoline_code [MONO_TRAMPOLINE_CLASS_INIT] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_CLASS_INIT);
6934 #ifdef MONO_ARCH_HAVE_PIC_AOT
6935         mono_trampoline_code [MONO_TRAMPOLINE_AOT] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_AOT);
6936 #endif
6937 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
6938         mono_trampoline_code [MONO_TRAMPOLINE_DELEGATE] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_DELEGATE);
6939 #endif
6940 }
6941
6942 static void
6943 mono_init_exceptions (void)
6944 {
6945 #ifndef CUSTOM_EXCEPTION_HANDLING
6946         mono_arch_get_restore_context ();
6947         mono_arch_get_call_filter ();
6948         mono_arch_get_throw_exception ();
6949         mono_arch_get_rethrow_exception ();
6950 #endif
6951 }
6952
6953 guint8 *
6954 mono_get_trampoline_code (MonoTrampolineType tramp_type)
6955 {
6956         return mono_trampoline_code [tramp_type];
6957 }
6958
6959 gpointer
6960 mono_create_class_init_trampoline (MonoVTable *vtable)
6961 {
6962         gpointer code, ptr;
6963
6964         /* previously created trampoline code */
6965         mono_domain_lock (vtable->domain);
6966         ptr = 
6967                 g_hash_table_lookup (vtable->domain->class_init_trampoline_hash,
6968                                                                   vtable);
6969         mono_domain_unlock (vtable->domain);
6970         if (ptr)
6971                 return ptr;
6972
6973 #ifdef MONO_ARCH_HAVE_CREATE_SPECIFIC_TRAMPOLINE
6974         code = mono_arch_create_specific_trampoline (vtable, MONO_TRAMPOLINE_CLASS_INIT, vtable->domain, NULL);
6975 #else
6976         code = mono_arch_create_class_init_trampoline (vtable);
6977 #endif
6978
6979         ptr = mono_create_ftnptr (vtable->domain, code);
6980
6981         /* store trampoline address */
6982         mono_domain_lock (vtable->domain);
6983         g_hash_table_insert (vtable->domain->class_init_trampoline_hash,
6984                                                           vtable, ptr);
6985         mono_domain_unlock (vtable->domain);
6986
6987         mono_jit_lock ();
6988         if (!class_init_hash_addr)
6989                 class_init_hash_addr = g_hash_table_new (NULL, NULL);
6990         g_hash_table_insert (class_init_hash_addr, ptr, vtable);
6991         mono_jit_unlock ();
6992
6993         return ptr;
6994 }
6995
6996 gpointer
6997 mono_create_jump_trampoline (MonoDomain *domain, MonoMethod *method, 
6998                                                          gboolean add_sync_wrapper)
6999 {
7000         MonoJitInfo *ji;
7001         gpointer code;
7002 #ifdef MONO_ARCH_HAVE_CREATE_SPECIFIC_TRAMPOLINE
7003         guint32 code_size;
7004 #endif
7005
7006         if (add_sync_wrapper && method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
7007                 return mono_create_jump_trampoline (domain, mono_marshal_get_synchronized_wrapper (method), FALSE);
7008
7009         code = mono_jit_find_compiled_method (domain, method);
7010         if (code)
7011                 return code;
7012
7013         mono_domain_lock (domain);
7014         code = g_hash_table_lookup (domain->jump_trampoline_hash, method);
7015         mono_domain_unlock (domain);
7016         if (code)
7017                 return code;
7018
7019 #ifdef MONO_ARCH_HAVE_CREATE_SPECIFIC_TRAMPOLINE
7020         code = mono_arch_create_specific_trampoline (method, MONO_TRAMPOLINE_JUMP, mono_domain_get (), &code_size);
7021
7022         ji = g_new0 (MonoJitInfo, 1);
7023         ji->code_start = code;
7024         ji->code_size = code_size;
7025         ji->method = method;
7026 #else
7027         ji = mono_arch_create_jump_trampoline (method);
7028 #endif
7029
7030         /*
7031          * mono_delegate_ctor needs to find the method metadata from the 
7032          * trampoline address, so we save it here.
7033          */
7034
7035         mono_jit_info_table_add (domain, ji);
7036
7037         mono_domain_lock (domain);
7038         g_hash_table_insert (domain->jump_trampoline_hash, method, ji->code_start);
7039         mono_domain_unlock (domain);
7040
7041         return ji->code_start;
7042 }
7043
7044 gpointer
7045 mono_create_jit_trampoline (MonoMethod *method)
7046 {
7047         MonoDomain *domain = mono_domain_get ();
7048         gpointer tramp;
7049
7050         mono_domain_lock (domain);
7051         tramp = g_hash_table_lookup (domain->jit_trampoline_hash, method);
7052         mono_domain_unlock (domain);
7053         if (tramp)
7054                 return tramp;
7055
7056         if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
7057                 return mono_create_jit_trampoline (mono_marshal_get_synchronized_wrapper (method));
7058
7059 #ifdef MONO_ARCH_HAVE_CREATE_SPECIFIC_TRAMPOLINE
7060         tramp =  mono_arch_create_specific_trampoline (method, MONO_TRAMPOLINE_GENERIC, mono_domain_get (), NULL);
7061 #else
7062         tramp = mono_arch_create_jit_trampoline (method);
7063 #endif
7064         
7065         mono_domain_lock (domain);
7066         g_hash_table_insert (domain->jit_trampoline_hash, method, tramp);
7067         mono_domain_unlock (domain);
7068
7069         mono_jit_stats.method_trampolines++;
7070
7071         return tramp;
7072 }       
7073
7074 #ifdef MONO_ARCH_HAVE_CREATE_TRAMPOLINE_FROM_TOKEN
7075 gpointer
7076 mono_create_jit_trampoline_from_token (MonoImage *image, guint32 token)
7077 {
7078         gpointer tramp;
7079
7080         MonoDomain *domain = mono_domain_get ();
7081         guint8 *buf, *start;
7082
7083         mono_domain_lock (domain);
7084         buf = start = mono_code_manager_reserve (domain->code_mp, 2 * sizeof (gpointer));
7085         mono_domain_unlock (domain);
7086
7087         *(gpointer*)(gpointer)buf = image;
7088         buf += sizeof (gpointer);
7089         *(guint32*)(gpointer)buf = token;
7090
7091         tramp = mono_arch_create_specific_trampoline (start, MONO_TRAMPOLINE_AOT, domain, NULL);
7092
7093         mono_jit_stats.method_trampolines++;
7094
7095         return tramp;
7096 }       
7097 #endif
7098
7099 gpointer
7100 mono_create_delegate_trampoline (MonoMethod *method, gpointer addr)
7101 {
7102 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
7103         gpointer code, ptr;
7104         guint32 code_size;
7105         MonoDomain *domain = mono_domain_get ();
7106
7107 #ifndef __ia64__
7108         code = mono_jit_find_compiled_method (domain, method);
7109         if (code)
7110                 return code;
7111 #else
7112         /* 
7113          * FIXME: We should return a function descriptor here but it is not stored
7114          * anywhere so it would be leaked.
7115          */
7116 #endif
7117
7118         mono_domain_lock (domain);
7119         ptr = g_hash_table_lookup (domain->delegate_trampoline_hash, method);
7120         mono_domain_unlock (domain);
7121         if (ptr)
7122                 return ptr;
7123
7124         code = mono_arch_create_specific_trampoline (method, MONO_TRAMPOLINE_DELEGATE, domain, &code_size);
7125
7126         ptr = mono_create_ftnptr (domain, code);
7127
7128         /* store trampoline address */
7129         mono_domain_lock (domain);
7130         g_hash_table_insert (domain->delegate_trampoline_hash,
7131                                                           method, ptr);
7132         mono_domain_unlock (domain);
7133
7134         return ptr;
7135 #else
7136         return addr;
7137 #endif
7138 }
7139
7140 MonoVTable*
7141 mono_find_class_init_trampoline_by_addr (gconstpointer addr)
7142 {
7143         MonoVTable *res;
7144
7145         mono_jit_lock ();
7146         if (class_init_hash_addr)
7147                 res = g_hash_table_lookup (class_init_hash_addr, addr);
7148         else
7149                 res = NULL;
7150         mono_jit_unlock ();
7151         return res;
7152 }
7153
7154 static void
7155 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
7156 {
7157         if (!domain->dynamic_code_hash)
7158                 domain->dynamic_code_hash = g_hash_table_new (NULL, NULL);
7159         g_hash_table_insert (domain->dynamic_code_hash, method, ji);
7160 }
7161
7162 static MonoJitDynamicMethodInfo*
7163 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
7164 {
7165         MonoJitDynamicMethodInfo *res;
7166
7167         if (domain->dynamic_code_hash)
7168                 res = g_hash_table_lookup (domain->dynamic_code_hash, method);
7169         else
7170                 res = NULL;
7171         return res;
7172 }
7173
7174 typedef struct {
7175         MonoClass *vtype;
7176         GList *active;
7177         GList *slots;
7178 } StackSlotInfo;
7179
7180 /*
7181  * mono_allocate_stack_slots_full:
7182  *
7183  *  Allocate stack slots for all non register allocated variables using a
7184  * linear scan algorithm.
7185  * Returns: an array of stack offsets which the caller should free.
7186  * STACK_SIZE is set to the amount of stack space needed.
7187  * STACK_ALIGN is set to the alignment needed by the locals area.
7188  */
7189 gint32*
7190 mono_allocate_stack_slots_full (MonoCompile *m, gboolean backward, guint32 *stack_size, guint32 *stack_align)
7191 {
7192         int i, slot, offset, size, align;
7193         MonoMethodVar *vmv;
7194         MonoInst *inst;
7195         gint32 *offsets;
7196         GList *vars = NULL, *l;
7197         StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
7198         MonoType *t;
7199         int nvtypes;
7200
7201         scalar_stack_slots = g_new0 (StackSlotInfo, MONO_TYPE_PINNED);
7202         vtype_stack_slots = g_new0 (StackSlotInfo, 256);
7203         nvtypes = 0;
7204
7205         offsets = g_new (gint32, m->num_varinfo);
7206         for (i = 0; i < m->num_varinfo; ++i)
7207                 offsets [i] = -1;
7208
7209         for (i = m->locals_start; i < m->num_varinfo; i++) {
7210                 inst = m->varinfo [i];
7211                 vmv = MONO_VARINFO (m, i);
7212
7213                 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
7214                         continue;
7215
7216                 vars = g_list_prepend (vars, vmv);
7217         }
7218
7219         vars = mono_varlist_sort (m, vars, 0);
7220         offset = 0;
7221         *stack_align = 0;
7222         for (l = vars; l; l = l->next) {
7223                 vmv = l->data;
7224                 inst = m->varinfo [vmv->idx];
7225
7226                 /* inst->unused indicates native sized value types, this is used by the
7227                 * pinvoke wrappers when they call functions returning structures */
7228                 if (inst->unused && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF)
7229                         size = mono_class_native_size (inst->inst_vtype->data.klass, &align);
7230                 else
7231                         size = mono_type_size (inst->inst_vtype, &align);
7232
7233                 t = mono_type_get_underlying_type (inst->inst_vtype);
7234                 switch (t->type) {
7235                 case MONO_TYPE_VALUETYPE:
7236                         for (i = 0; i < nvtypes; ++i)
7237                                 if (t->data.klass == vtype_stack_slots [i].vtype)
7238                                         break;
7239                         if (i < nvtypes)
7240                                 slot_info = &vtype_stack_slots [i];
7241                         else {
7242                                 g_assert (nvtypes < 256);
7243                                 vtype_stack_slots [nvtypes].vtype = t->data.klass;
7244                                 slot_info = &vtype_stack_slots [nvtypes];
7245                                 nvtypes ++;
7246                         }
7247                         break;
7248                 default:
7249                         slot_info = &scalar_stack_slots [t->type];
7250                 }
7251
7252                 slot = 0xffffff;
7253                 if (m->comp_done & MONO_COMP_LIVENESS) {
7254                         //printf ("START  %2d %08x %08x\n",  vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
7255                         
7256                         /* expire old intervals in active */
7257                         while (slot_info->active) {
7258                                 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
7259
7260                                 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
7261                                         break;
7262
7263                                 //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);
7264
7265                                 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
7266                                 slot_info->slots = g_list_prepend (slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
7267                         }
7268
7269                         /* 
7270                          * This also handles the case when the variable is used in an
7271                          * exception region, as liveness info is not computed there.
7272                          */
7273                         /* 
7274                          * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
7275                          * opcodes.
7276                          */
7277                         if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
7278                                 if (slot_info->slots) {
7279                                         slot = GPOINTER_TO_INT (slot_info->slots->data);
7280
7281                                         slot_info->slots = g_list_delete_link (slot_info->slots, slot_info->slots);
7282                                 }
7283
7284                                 slot_info->active = mono_varlist_insert_sorted (m, slot_info->active, vmv, TRUE);
7285                         }
7286                 }
7287
7288                 {
7289                         static int count = 0;
7290                         count ++;
7291
7292                         /*
7293                         if (count == atoi (getenv ("COUNT")))
7294                                 printf ("LAST: %s\n", mono_method_full_name (m->method, TRUE));
7295                         if (count > atoi (getenv ("COUNT")))
7296                                 slot = 0xffffff;
7297                         else {
7298                                 mono_print_tree_nl (inst);
7299                                 }
7300                         */
7301                 }
7302                 if (slot == 0xffffff) {
7303                         /*
7304                          * Allways allocate valuetypes to sizeof (gpointer) to allow more
7305                          * efficient copying (and to work around the fact that OP_MEMCPY
7306                          * and OP_MEMSET ignores alignment).
7307                          */
7308                         if (t->type == MONO_TYPE_VALUETYPE)
7309                                 align = sizeof (gpointer);
7310
7311                         if (backward) {
7312                                 offset += size;
7313                                 offset += align - 1;
7314                                 offset &= ~(align - 1);
7315                                 slot = offset;
7316                         }
7317                         else {
7318                                 offset += align - 1;
7319                                 offset &= ~(align - 1);
7320                                 slot = offset;
7321                                 offset += size;
7322                         }
7323
7324                         if (*stack_align == 0)
7325                                 *stack_align = align;
7326                 }
7327
7328                 offsets [vmv->idx] = slot;
7329         }
7330         g_list_free (vars);
7331         for (i = 0; i < MONO_TYPE_PINNED; ++i) {
7332                 g_list_free (scalar_stack_slots [i].active);
7333                 g_list_free (scalar_stack_slots [i].slots);
7334         }
7335         for (i = 0; i < nvtypes; ++i) {
7336                 g_list_free (vtype_stack_slots [i].active);
7337                 g_list_free (vtype_stack_slots [i].slots);
7338         }
7339         g_free (scalar_stack_slots);
7340         g_free (vtype_stack_slots);
7341
7342         *stack_size = offset;
7343         return offsets;
7344 }
7345
7346 gint32*
7347 mono_allocate_stack_slots (MonoCompile *m, guint32 *stack_size, guint32 *stack_align)
7348 {
7349         return mono_allocate_stack_slots_full (m, TRUE, stack_size, stack_align);
7350 }
7351
7352 void
7353 mono_register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, gboolean no_throw)
7354 {
7355         MonoJitICallInfo *info;
7356         MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
7357
7358         if (!emul_opcode_map)
7359                 emul_opcode_map = g_new0 (MonoJitICallInfo*, OP_LAST + 1);
7360
7361         g_assert (!sig->hasthis);
7362         g_assert (sig->param_count < 3);
7363
7364         info = mono_register_jit_icall (func, name, sig, no_throw);
7365
7366         emul_opcode_map [opcode] = info;
7367 }
7368
7369 static void
7370 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
7371 {
7372         MonoMethodSignature *sig;
7373
7374         if (sigstr)
7375                 sig = mono_create_icall_signature (sigstr);
7376         else
7377                 sig = NULL;
7378
7379         mono_register_jit_icall (func, name, sig, save);
7380 }
7381
7382 static void
7383 decompose_foreach (MonoInst *tree, gpointer data) 
7384 {
7385         static MonoJitICallInfo *newarr_info = NULL;
7386         static MonoJitICallInfo *newarr_specific_info = NULL;
7387         MonoJitICallInfo *info;
7388         int i;
7389
7390         switch (tree->opcode) {
7391         case CEE_NEWARR: {
7392                 MonoCompile *cfg = data;
7393                 MonoInst *iargs [3];
7394
7395                 if (!newarr_info) {
7396                         newarr_info = mono_find_jit_icall_by_addr (mono_array_new);
7397                         g_assert (newarr_info);
7398                         newarr_specific_info = mono_find_jit_icall_by_addr (mono_array_new_specific);
7399                         g_assert (newarr_specific_info);
7400                 }
7401
7402                 if (cfg->opt & MONO_OPT_SHARED) {
7403                         NEW_DOMAINCONST (cfg, iargs [0]);
7404                         NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
7405                         iargs [2] = tree->inst_newa_len;
7406
7407                         info = newarr_info;
7408                 }
7409                 else {
7410                         MonoVTable *vtable = mono_class_vtable (cfg->domain, mono_array_class_get (tree->inst_newa_class, 1));
7411
7412                         NEW_VTABLECONST (cfg, iargs [0], vtable);
7413                         iargs [1] = tree->inst_newa_len;
7414
7415                         info = newarr_specific_info;
7416                 }
7417
7418                 mono_emulate_opcode (cfg, tree, iargs, info);
7419
7420                 /* Need to decompose arguments after the the opcode is decomposed */
7421                 for (i = 0; i < info->sig->param_count; ++i)
7422                         dec_foreach (iargs [i], cfg);
7423                 break;
7424         }
7425
7426         default:
7427                 break;
7428         }
7429 }
7430
7431 void
7432 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
7433
7434         switch (mono_burg_arity [tree->opcode]) {
7435         case 0: break;
7436         case 1: 
7437                 mono_inst_foreach (tree->inst_left, func, data);
7438                 break;
7439         case 2: 
7440                 mono_inst_foreach (tree->inst_left, func, data);
7441                 mono_inst_foreach (tree->inst_right, func, data);
7442                 break;
7443         default:
7444                 g_assert_not_reached ();
7445         }
7446         func (tree, data);
7447 }
7448
7449 G_GNUC_UNUSED
7450 static void
7451 mono_print_bb_code (MonoBasicBlock *bb) {
7452         if (bb->code) {
7453                 MonoInst *c = bb->code;
7454                 while (c) {
7455                         mono_print_tree (c);
7456                         g_print ("\n");
7457                         c = c->next;
7458                 }
7459         }
7460 }
7461
7462 static void
7463 print_dfn (MonoCompile *cfg) {
7464         int i, j;
7465         char *code;
7466         MonoBasicBlock *bb;
7467
7468         g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
7469
7470         for (i = 0; i < cfg->num_bblocks; ++i) {
7471                 bb = cfg->bblocks [i];
7472                 /*if (bb->cil_code) {
7473                         char* code1, *code2;
7474                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
7475                         if (bb->last_ins->cil_code)
7476                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
7477                         else
7478                                 code2 = g_strdup ("");
7479
7480                         code1 [strlen (code1) - 1] = 0;
7481                         code = g_strdup_printf ("%s -> %s", code1, code2);
7482                         g_free (code1);
7483                         g_free (code2);
7484                 } else*/
7485                         code = g_strdup ("\n");
7486                 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
7487                 if (bb->code) {
7488                         MonoInst *c = bb->code;
7489                         while (c) {
7490                                 mono_print_tree (c);
7491                                 g_print ("\n");
7492                                 c = c->next;
7493                         }
7494                 } else {
7495
7496                 }
7497
7498                 g_print ("\tprev:");
7499                 for (j = 0; j < bb->in_count; ++j) {
7500                         g_print (" BB%d", bb->in_bb [j]->block_num);
7501                 }
7502                 g_print ("\t\tsucc:");
7503                 for (j = 0; j < bb->out_count; ++j) {
7504                         g_print (" BB%d", bb->out_bb [j]->block_num);
7505                 }
7506                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
7507
7508                 if (bb->idom)
7509                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
7510
7511                 if (bb->dominators)
7512                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
7513                 if (bb->dfrontier)
7514                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
7515                 g_free (code);
7516         }
7517
7518         g_print ("\n");
7519 }
7520
7521 void
7522 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
7523 {
7524         inst->next = NULL;
7525         if (bb->last_ins) {
7526                 g_assert (bb->code);
7527                 bb->last_ins->next = inst;
7528                 bb->last_ins = inst;
7529         } else {
7530                 bb->last_ins = bb->code = inst;
7531         }
7532 }
7533
7534 void
7535 mono_destroy_compile (MonoCompile *cfg)
7536 {
7537         //mono_mempool_stats (cfg->mempool);
7538         g_hash_table_destroy (cfg->bb_hash);
7539         mono_free_loop_info (cfg);
7540         if (cfg->rs)
7541                 mono_regstate_free (cfg->rs);
7542         if (cfg->spvars)
7543                 g_hash_table_destroy (cfg->spvars);
7544         if (cfg->exvars)
7545                 g_hash_table_destroy (cfg->exvars);
7546         mono_mempool_destroy (cfg->mempool);
7547         g_list_free (cfg->ldstr_list);
7548
7549         g_free (cfg->varinfo);
7550         g_free (cfg->vars);
7551         g_free (cfg);
7552 }
7553
7554 #ifdef HAVE_KW_THREAD
7555 static __thread gpointer mono_lmf_addr MONO_TLS_FAST;
7556 #endif
7557
7558 guint32
7559 mono_get_jit_tls_key (void)
7560 {
7561         return mono_jit_tls_id;
7562 }
7563
7564 gint32
7565 mono_get_lmf_tls_offset (void)
7566 {
7567         int offset;
7568         MONO_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
7569         return offset;
7570 }
7571
7572 MonoLMF **
7573 mono_get_lmf_addr (void)
7574 {
7575 #ifdef HAVE_KW_THREAD
7576         return mono_lmf_addr;
7577 #else
7578         MonoJitTlsData *jit_tls;
7579
7580         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
7581                 return &jit_tls->lmf;
7582
7583         g_assert_not_reached ();
7584         return NULL;
7585 #endif
7586 }
7587
7588 /* Called by native->managed wrappers */
7589 void
7590 mono_jit_thread_attach (MonoDomain *domain)
7591 {
7592 #ifdef HAVE_KW_THREAD
7593         if (!mono_lmf_addr) {
7594                 mono_thread_attach (domain);
7595         }
7596 #else
7597         if (!TlsGetValue (mono_jit_tls_id))
7598                 mono_thread_attach (domain);
7599 #endif
7600 }       
7601
7602 /**
7603  * mono_thread_abort:
7604  * @obj: exception object
7605  *
7606  * abort the thread, print exception information and stack trace
7607  */
7608 static void
7609 mono_thread_abort (MonoObject *obj)
7610 {
7611         /* MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id); */
7612         
7613         /* handle_remove should be eventually called for this thread, too
7614         g_free (jit_tls);*/
7615
7616         mono_thread_exit ();
7617 }
7618
7619 static void*
7620 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
7621 {
7622         MonoJitTlsData *jit_tls;
7623         MonoLMF *lmf;
7624
7625         jit_tls = TlsGetValue (mono_jit_tls_id);
7626         if (jit_tls)
7627                 return jit_tls;
7628
7629         jit_tls = g_new0 (MonoJitTlsData, 1);
7630
7631         TlsSetValue (mono_jit_tls_id, jit_tls);
7632
7633         jit_tls->abort_func = abort_func;
7634         jit_tls->end_of_stack = stack_start;
7635
7636         lmf = g_new0 (MonoLMF, 1);
7637         lmf->ebp = -1;
7638
7639         jit_tls->lmf = jit_tls->first_lmf = lmf;
7640
7641 #ifdef HAVE_KW_THREAD
7642         mono_lmf_addr = &jit_tls->lmf;
7643 #endif
7644
7645         mono_arch_setup_jit_tls_data (jit_tls);
7646
7647 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
7648         mono_setup_altstack (jit_tls);
7649 #endif
7650
7651         return jit_tls;
7652 }
7653
7654 static void
7655 mono_thread_start_cb (gsize tid, gpointer stack_start, gpointer func)
7656 {
7657         MonoThread *thread;
7658         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
7659         thread = mono_thread_current ();
7660         if (thread)
7661                 thread->jit_data = jit_tls;
7662 }
7663
7664 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
7665
7666 static void
7667 mono_thread_abort_dummy (MonoObject *obj)
7668 {
7669   if (mono_thread_attach_aborted_cb)
7670     mono_thread_attach_aborted_cb (obj);
7671   else
7672     mono_thread_abort (obj);
7673 }
7674
7675 static void
7676 mono_thread_attach_cb (gsize tid, gpointer stack_start)
7677 {
7678         MonoThread *thread;
7679         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
7680         thread = mono_thread_current ();
7681         if (thread)
7682                 thread->jit_data = jit_tls;
7683         if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
7684                 setup_stat_profiler ();
7685 }
7686
7687 static void
7688 mini_thread_cleanup (MonoThread *thread)
7689 {
7690         MonoJitTlsData *jit_tls = thread->jit_data;
7691
7692         if (jit_tls) {
7693                 mono_arch_free_jit_tls_data (jit_tls);
7694
7695 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
7696                 mono_free_altstack (jit_tls);
7697 #endif
7698                 g_free (jit_tls->first_lmf);
7699                 g_free (jit_tls);
7700                 thread->jit_data = NULL;
7701         }
7702 }
7703
7704 void
7705 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
7706 {
7707         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
7708
7709         ji->ip.i = ip;
7710         ji->type = type;
7711         ji->data.target = target;
7712         ji->next = cfg->patch_info;
7713
7714         cfg->patch_info = ji;
7715 }
7716
7717 void
7718 mono_remove_patch_info (MonoCompile *cfg, int ip)
7719 {
7720         MonoJumpInfo **ji = &cfg->patch_info;
7721
7722         while (*ji) {
7723                 if ((*ji)->ip.i == ip)
7724                         *ji = (*ji)->next;
7725                 else
7726                         ji = &((*ji)->next);
7727         }
7728 }
7729
7730 gpointer
7731 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
7732 {
7733         unsigned char *ip = patch_info->ip.i + code;
7734         gconstpointer target = NULL;
7735
7736         switch (patch_info->type) {
7737         case MONO_PATCH_INFO_BB:
7738                 target = patch_info->data.bb->native_offset + code;
7739                 break;
7740         case MONO_PATCH_INFO_ABS:
7741                 target = patch_info->data.target;
7742                 break;
7743         case MONO_PATCH_INFO_LABEL:
7744                 target = patch_info->data.inst->inst_c0 + code;
7745                 break;
7746         case MONO_PATCH_INFO_IP:
7747                 target = ip;
7748                 break;
7749         case MONO_PATCH_INFO_METHOD_REL:
7750                 target = code + patch_info->data.offset;
7751                 break;
7752         case MONO_PATCH_INFO_INTERNAL_METHOD: {
7753                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
7754                 if (!mi) {
7755                         g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
7756                         g_assert_not_reached ();
7757                 }
7758                 target = mono_icall_get_wrapper (mi);
7759                 break;
7760         }
7761         case MONO_PATCH_INFO_METHOD_JUMP: {
7762                 GSList *list;
7763
7764                 /* get the trampoline to the method from the domain */
7765                 target = mono_create_jump_trampoline (domain, patch_info->data.method, TRUE);
7766                 if (!domain->jump_target_hash)
7767                         domain->jump_target_hash = g_hash_table_new (NULL, NULL);
7768                 list = g_hash_table_lookup (domain->jump_target_hash, patch_info->data.method);
7769                 list = g_slist_prepend (list, ip);
7770                 g_hash_table_insert (domain->jump_target_hash, patch_info->data.method, list);
7771                 break;
7772         }
7773         case MONO_PATCH_INFO_METHOD:
7774                 if (patch_info->data.method == method) {
7775                         target = code;
7776                 } else
7777                         /* get the trampoline to the method from the domain */
7778                         target = mono_create_jit_trampoline (patch_info->data.method);
7779                 break;
7780         case MONO_PATCH_INFO_SWITCH: {
7781                 gpointer *jump_table;
7782                 int i;
7783
7784                 if (method && method->dynamic) {
7785                         jump_table = mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
7786                 } else {
7787                         mono_domain_lock (domain);
7788                         jump_table = mono_code_manager_reserve (domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
7789                         mono_domain_unlock (domain);
7790                 }
7791
7792                 for (i = 0; i < patch_info->data.table->table_size; i++) {
7793                         jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
7794                 }
7795                 target = jump_table;
7796                 break;
7797         }
7798         case MONO_PATCH_INFO_METHODCONST:
7799         case MONO_PATCH_INFO_CLASS:
7800         case MONO_PATCH_INFO_IMAGE:
7801         case MONO_PATCH_INFO_FIELD:
7802                 target = patch_info->data.target;
7803                 break;
7804         case MONO_PATCH_INFO_IID:
7805                 mono_class_init (patch_info->data.klass);
7806                 target = GINT_TO_POINTER ((int)patch_info->data.klass->interface_id);
7807                 break;
7808         case MONO_PATCH_INFO_VTABLE:
7809                 target = mono_class_vtable (domain, patch_info->data.klass);
7810                 break;
7811         case MONO_PATCH_INFO_CLASS_INIT:
7812                 target = mono_create_class_init_trampoline (mono_class_vtable (domain, patch_info->data.klass));
7813                 break;
7814         case MONO_PATCH_INFO_SFLDA: {
7815                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
7816                 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && (method && mono_class_needs_cctor_run (vtable->klass, method)))
7817                         /* Done by the generated code */
7818                         ;
7819                 else {
7820                         if (run_cctors)
7821                                 mono_runtime_class_init (vtable);
7822                 }
7823                 target = (char*)vtable->data + patch_info->data.field->offset;
7824                 break;
7825         }
7826         case MONO_PATCH_INFO_R4:
7827         case MONO_PATCH_INFO_R8:
7828                 target = patch_info->data.target;
7829                 break;
7830         case MONO_PATCH_INFO_EXC_NAME:
7831                 target = patch_info->data.name;
7832                 break;
7833         case MONO_PATCH_INFO_LDSTR:
7834                 target =
7835                         mono_ldstr (domain, patch_info->data.token->image, 
7836                                                 mono_metadata_token_index (patch_info->data.token->token));
7837                 break;
7838         case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
7839                 gpointer handle;
7840                 MonoClass *handle_class;
7841
7842                 handle = mono_ldtoken (patch_info->data.token->image, 
7843                                        patch_info->data.token->token, &handle_class, NULL);
7844                 mono_class_init (handle_class);
7845                 mono_class_init (mono_class_from_mono_type (handle));
7846
7847                 target =
7848                         mono_type_get_object (domain, handle);
7849                 break;
7850         }
7851         case MONO_PATCH_INFO_LDTOKEN: {
7852                 gpointer handle;
7853                 MonoClass *handle_class;
7854                 
7855                 handle = mono_ldtoken (patch_info->data.token->image,
7856                                        patch_info->data.token->token, &handle_class, NULL);
7857                 mono_class_init (handle_class);
7858                 
7859                 target = handle;
7860                 break;
7861         }
7862         case MONO_PATCH_INFO_DECLSEC:
7863                 target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
7864                 break;
7865         case MONO_PATCH_INFO_BB_OVF:
7866         case MONO_PATCH_INFO_EXC_OVF:
7867         case MONO_PATCH_INFO_GOT_OFFSET:
7868         case MONO_PATCH_INFO_NONE:
7869                 break;
7870         default:
7871                 g_assert_not_reached ();
7872         }
7873
7874         return (gpointer)target;
7875 }
7876
7877 static void
7878 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
7879         MonoJitICallInfo *info;
7880
7881         decompose_foreach (tree, cfg);
7882
7883         switch (mono_burg_arity [tree->opcode]) {
7884         case 0: break;
7885         case 1: 
7886                 dec_foreach (tree->inst_left, cfg);
7887
7888                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
7889                         MonoInst *iargs [2];
7890                 
7891                         iargs [0] = tree->inst_left;
7892
7893                         mono_emulate_opcode (cfg, tree, iargs, info);
7894                         return;
7895                 }
7896
7897                 break;
7898         case 2:
7899 #ifdef MONO_ARCH_BIGMUL_INTRINS
7900                 if (tree->opcode == OP_LMUL
7901                                 && (cfg->opt & MONO_OPT_INTRINS)
7902                                 && (tree->inst_left->opcode == CEE_CONV_I8 
7903                                         || tree->inst_left->opcode == CEE_CONV_U8)
7904                                 && tree->inst_left->inst_left->type == STACK_I4
7905                                 && (tree->inst_right->opcode == CEE_CONV_I8 
7906                                         || tree->inst_right->opcode == CEE_CONV_U8)
7907                                 && tree->inst_right->inst_left->type == STACK_I4
7908                                 && tree->inst_left->opcode == tree->inst_right->opcode) {
7909                         tree->opcode = (tree->inst_left->opcode == CEE_CONV_I8 ? OP_BIGMUL: OP_BIGMUL_UN);
7910                         tree->inst_left = tree->inst_left->inst_left;
7911                         tree->inst_right = tree->inst_right->inst_left;
7912                         dec_foreach (tree, cfg);
7913                 } else 
7914 #endif
7915                         if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
7916                         MonoInst *iargs [2];
7917                 
7918                         iargs [0] = tree->inst_i0;
7919                         iargs [1] = tree->inst_i1;
7920                 
7921                         mono_emulate_opcode (cfg, tree, iargs, info);
7922
7923                         dec_foreach (iargs [0], cfg);
7924                         dec_foreach (iargs [1], cfg);
7925                         return;
7926                 } else {
7927                         dec_foreach (tree->inst_left, cfg);
7928                         dec_foreach (tree->inst_right, cfg);
7929                 }
7930                 break;
7931         default:
7932                 g_assert_not_reached ();
7933         }
7934 }
7935
7936 static void
7937 decompose_pass (MonoCompile *cfg) {
7938         MonoBasicBlock *bb;
7939
7940         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7941                 MonoInst *tree;
7942                 cfg->cbb = bb;
7943                 cfg->prev_ins = NULL;
7944                 for (tree = cfg->cbb->code; tree; tree = tree->next) {
7945                         dec_foreach (tree, cfg);
7946                         cfg->prev_ins = tree;
7947                 }
7948         }
7949 }
7950
7951 static void
7952 nullify_basic_block (MonoBasicBlock *bb) 
7953 {
7954         bb->in_count = 0;
7955         bb->out_count = 0;
7956         bb->in_bb = NULL;
7957         bb->out_bb = NULL;
7958         bb->next_bb = NULL;
7959         bb->code = bb->last_ins = NULL;
7960         bb->cil_code = NULL;
7961 }
7962
7963 static void 
7964 replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
7965 {
7966         int i;
7967
7968         for (i = 0; i < bb->out_count; i++) {
7969                 MonoBasicBlock *ob = bb->out_bb [i];
7970                 if (ob == orig) {
7971                         if (!repl) {
7972                                 if (bb->out_count > 1) {
7973                                         bb->out_bb [i] = bb->out_bb [bb->out_count - 1];
7974                                 }
7975                                 bb->out_count--;
7976                         } else {
7977                                 bb->out_bb [i] = repl;
7978                         }
7979                 }
7980         }
7981 }
7982
7983 static void 
7984 replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
7985 {
7986         int i;
7987
7988         for (i = 0; i < bb->in_count; i++) {
7989                 MonoBasicBlock *ib = bb->in_bb [i];
7990                 if (ib == orig) {
7991                         if (!repl) {
7992                                 if (bb->in_count > 1) {
7993                                         bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
7994                                 }
7995                                 bb->in_count--;
7996                         } else {
7997                                 bb->in_bb [i] = repl;
7998                         }
7999                 }
8000         }
8001 }
8002
8003 static void 
8004 replace_or_add_in_block (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
8005 {
8006         gboolean found = FALSE;
8007         int i;
8008
8009         for (i = 0; i < bb->in_count; i++) {
8010                 MonoBasicBlock *ib = bb->in_bb [i];
8011                 if (ib == orig) {
8012                         if (!repl) {
8013                                 if (bb->in_count > 1) {
8014                                         bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
8015                                 }
8016                                 bb->in_count--;
8017                         } else {
8018                                 bb->in_bb [i] = repl;
8019                         }
8020                         found = TRUE;
8021                 }
8022         }
8023         
8024         if (! found) {
8025                 MonoBasicBlock **new_in_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (bb->in_count + 1));
8026                 for (i = 0; i < bb->in_count; i++) {
8027                         new_in_bb [i] = bb->in_bb [i];
8028                 }
8029                 new_in_bb [i] = repl;
8030                 bb->in_count++;
8031                 bb->in_bb = new_in_bb;
8032         }
8033 }
8034
8035
8036 static void
8037 replace_out_block_in_code (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl) {
8038         MonoInst *inst;
8039         
8040         for (inst = bb->code; inst != NULL; inst = inst->next) {
8041                 if (inst->opcode == OP_CALL_HANDLER) {
8042                         if (inst->inst_target_bb == orig) {
8043                                 inst->inst_target_bb = repl;
8044                         }
8045                 }
8046         }
8047         if (bb->last_ins != NULL) {
8048                 switch (bb->last_ins->opcode) {
8049                 case CEE_BR:
8050                         if (bb->last_ins->inst_target_bb == orig) {
8051                                 bb->last_ins->inst_target_bb = repl;
8052                         }
8053                         break;
8054                 case CEE_SWITCH: {
8055                         int i;
8056                         int n = GPOINTER_TO_INT (bb->last_ins->klass);
8057                         for (i = 0; i < n; i++ ) {
8058                                 if (bb->last_ins->inst_many_bb [i] == orig) {
8059                                         bb->last_ins->inst_many_bb [i] = repl;
8060                                 }
8061                         }
8062                         break;
8063                 }
8064                 case CEE_BNE_UN:
8065                 case CEE_BEQ:
8066                 case CEE_BLT:
8067                 case CEE_BLT_UN:
8068                 case CEE_BGT:
8069                 case CEE_BGT_UN:
8070                 case CEE_BGE:
8071                 case CEE_BGE_UN:
8072                 case CEE_BLE:
8073                 case CEE_BLE_UN:
8074                         if (bb->last_ins->inst_true_bb == orig) {
8075                                 bb->last_ins->inst_true_bb = repl;
8076                         }
8077                         if (bb->last_ins->inst_false_bb == orig) {
8078                                 bb->last_ins->inst_false_bb = repl;
8079                         }
8080                         break;
8081                 default:
8082                         break;
8083                 }
8084         }
8085 }
8086
8087 static void 
8088 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
8089 {
8090         int i, j;
8091
8092         for (i = 0; i < bb->out_count; i++) {
8093                 MonoBasicBlock *ob = bb->out_bb [i];
8094                 for (j = 0; j < ob->in_count; j++) {
8095                         if (ob->in_bb [j] == orig) {
8096                                 ob->in_bb [j] = repl;
8097                         }
8098                 }
8099         }
8100
8101 }
8102
8103 /**
8104   * Check if a bb is useless (is just made of NOPs and ends with an
8105   * unconditional branch, or nothing).
8106   * If it is so, unlink it from the CFG and nullify it, and return TRUE.
8107   * Otherwise, return FALSE;
8108   */
8109 static gboolean
8110 remove_block_if_useless (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *previous_bb) {
8111         MonoBasicBlock *target_bb = NULL;
8112         MonoInst *inst;
8113         
8114         /* Do not touch handlers */
8115         if (bb->region != -1) return FALSE;
8116         
8117         for (inst = bb->code; inst != NULL; inst = inst->next) {
8118                 switch (inst->opcode) {
8119                 case CEE_NOP:
8120                         break;
8121                 case CEE_BR:
8122                         target_bb = inst->inst_target_bb;
8123                         break;
8124                 default:
8125                         return FALSE;
8126                 }
8127         }
8128         
8129         if (target_bb == NULL) {
8130                 if ((bb->out_count == 1) && (bb->out_bb [0] == bb->next_bb)) {
8131                         target_bb = bb->next_bb;
8132                 } else {
8133                         /* Do not touch empty BBs that do not "fall through" to their next BB (like the exit BB) */
8134                         return FALSE;
8135                 }
8136         }
8137         
8138         /* Do not touch BBs following a switch (they are the "default" branch) */
8139         if ((previous_bb->last_ins != NULL) && (previous_bb->last_ins->opcode == CEE_SWITCH)) {
8140                 return FALSE;
8141         }
8142         
8143         /* Do not touch BBs following the entry BB and jumping to something that is not */
8144         /* thiry "next" bb (the entry BB cannot contain the branch) */
8145         if ((previous_bb == cfg->bb_entry) && (bb->next_bb != target_bb)) {
8146                 return FALSE;
8147         }
8148         
8149         /* Check that there is a target BB, and that bb is not an empty loop (Bug 75061) */
8150         if ((target_bb != NULL) && (target_bb != bb)) {
8151                 int i;
8152
8153                 if (cfg->verbose_level > 1) {
8154                         printf ("remove_block_if_useless %s, removed BB%d\n", mono_method_full_name (cfg->method, TRUE), bb->block_num);
8155                 }
8156                 
8157                 for (i = 0; i < bb->in_count; i++) {
8158                         MonoBasicBlock *in_bb = bb->in_bb [i];
8159                         replace_out_block (in_bb, bb, target_bb);
8160                         replace_out_block_in_code (in_bb, bb, target_bb);
8161                         if (bb->in_count == 1) {
8162                                 replace_in_block (target_bb, bb, in_bb);
8163                         } else {
8164                                 replace_or_add_in_block (cfg, target_bb, bb, in_bb);
8165                         }
8166                 }
8167                 
8168                 if ((previous_bb != cfg->bb_entry) &&
8169                                 (previous_bb->region == bb->region) &&
8170                                 ((previous_bb->last_ins == NULL) ||
8171                                 ((previous_bb->last_ins->opcode != CEE_BR) &&
8172                                 (! (MONO_IS_COND_BRANCH_OP (previous_bb->last_ins))) &&
8173                                 (previous_bb->last_ins->opcode != CEE_SWITCH)))) {
8174                         for (i = 0; i < previous_bb->out_count; i++) {
8175                                 if (previous_bb->out_bb [i] == target_bb) {
8176                                         MonoInst *jump;
8177                                         MONO_INST_NEW (cfg, jump, CEE_BR);
8178                                         MONO_ADD_INS (previous_bb, jump);
8179                                         jump->cil_code = previous_bb->cil_code;
8180                                         jump->inst_target_bb = target_bb;
8181                                         break;
8182                                 }
8183                         }
8184                 }
8185                 
8186                 previous_bb->next_bb = bb->next_bb;
8187                 nullify_basic_block (bb);
8188                 
8189                 return TRUE;
8190         } else {
8191                 return FALSE;
8192         }
8193 }
8194
8195 static void
8196 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn) 
8197 {
8198         bb->out_count = bbn->out_count;
8199         bb->out_bb = bbn->out_bb;
8200
8201         replace_basic_block (bb, bbn, bb);
8202
8203         if (bb->last_ins) {
8204                 if (bbn->code) {
8205                         bb->last_ins->next = bbn->code;
8206                         bb->last_ins = bbn->last_ins;
8207                 }
8208         } else {
8209                 bb->code = bbn->code;
8210                 bb->last_ins = bbn->last_ins;
8211         }
8212         bb->next_bb = bbn->next_bb;
8213         nullify_basic_block (bbn);
8214 }
8215
8216 static void
8217 move_basic_block_to_end (MonoCompile *cfg, MonoBasicBlock *bb)
8218 {
8219         MonoBasicBlock *bbn, *next;
8220
8221         next = bb->next_bb;
8222
8223         /* Find the previous */
8224         for (bbn = cfg->bb_entry; bbn->next_bb && bbn->next_bb != bb; bbn = bbn->next_bb)
8225                 ;
8226         if (bbn->next_bb) {
8227                 bbn->next_bb = bb->next_bb;
8228         }
8229
8230         /* Find the last */
8231         for (bbn = cfg->bb_entry; bbn->next_bb; bbn = bbn->next_bb)
8232                 ;
8233         bbn->next_bb = bb;
8234         bb->next_bb = NULL;
8235
8236         /* Add a branch */
8237         if (next && (!bb->last_ins || (bb->last_ins->opcode != OP_NOT_REACHED))) {
8238                 MonoInst *ins;
8239
8240                 MONO_INST_NEW (cfg, ins, CEE_BR);
8241                 MONO_ADD_INS (bb, ins);
8242                 link_bblock (cfg, bb, next);
8243                 ins->inst_target_bb = next;
8244         }               
8245 }
8246
8247 /*
8248  * Optimizes the branches on the Control Flow Graph
8249  *
8250  */
8251 static void
8252 optimize_branches (MonoCompile *cfg)
8253 {
8254         int i, changed = FALSE;
8255         MonoBasicBlock *bb, *bbn;
8256         guint32 niterations;
8257
8258         /*
8259          * Some crazy loops could cause the code below to go into an infinite
8260          * loop, see bug #53003 for an example. To prevent this, we put an upper
8261          * bound on the number of iterations.
8262          */
8263         if (cfg->num_bblocks > 1000)
8264                 niterations = cfg->num_bblocks * 2;
8265         else
8266                 niterations = 1000;
8267         do {
8268                 MonoBasicBlock *previous_bb;
8269                 changed = FALSE;
8270                 niterations --;
8271
8272                 /* we skip the entry block (exit is handled specially instead ) */
8273                 for (previous_bb = cfg->bb_entry, bb = cfg->bb_entry->next_bb; bb; previous_bb = bb, bb = bb->next_bb) {
8274
8275                         /* dont touch code inside exception clauses */
8276                         if (bb->region != -1)
8277                                 continue;
8278
8279                         if (remove_block_if_useless (cfg, bb, previous_bb)) {
8280                                 changed = TRUE;
8281                                 continue;
8282                         }
8283
8284                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
8285                                 if (cfg->verbose_level > 2)
8286                                         g_print ("nullify block triggered %d\n", bbn->block_num);
8287
8288                                 bb->next_bb = bbn->next_bb;
8289
8290                                 for (i = 0; i < bbn->out_count; i++)
8291                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
8292
8293                                 nullify_basic_block (bbn);                      
8294                                 changed = TRUE;
8295                         }
8296
8297                         if (bb->out_count == 1) {
8298                                 bbn = bb->out_bb [0];
8299
8300                                 /* conditional branches where true and false targets are the same can be also replaced with CEE_BR */
8301                                 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins)) {
8302                                         MonoInst *pop;
8303                                         MONO_INST_NEW (cfg, pop, CEE_POP);
8304                                         pop->inst_left = bb->last_ins->inst_left->inst_left;
8305                                         mono_add_ins_to_end (bb, pop);
8306                                         MONO_INST_NEW (cfg, pop, CEE_POP);
8307                                         pop->inst_left = bb->last_ins->inst_left->inst_right;
8308                                         mono_add_ins_to_end (bb, pop);
8309                                         bb->last_ins->opcode = CEE_BR;
8310                                         bb->last_ins->inst_target_bb = bb->last_ins->inst_true_bb;
8311                                         changed = TRUE;
8312                                         if (cfg->verbose_level > 2)
8313                                                 g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count);
8314                                 }
8315
8316                                 if (bb->region == bbn->region && bb->next_bb == bbn) {
8317                                         /* the block are in sequence anyway ... */
8318
8319                                         /* branches to the following block can be removed */
8320                                         if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
8321                                                 bb->last_ins->opcode = CEE_NOP;
8322                                                 changed = TRUE;
8323                                                 if (cfg->verbose_level > 2)
8324                                                         g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
8325                                         }
8326
8327                                         if (bbn->in_count == 1) {
8328
8329                                                 if (bbn != cfg->bb_exit) {
8330                                                         if (cfg->verbose_level > 2)
8331                                                                 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
8332                                                         merge_basic_blocks (bb, bbn);
8333                                                         changed = TRUE;
8334                                                 }
8335
8336                                                 //mono_print_bb_code (bb);
8337                                         }
8338                                 }                               
8339                         }
8340                 }
8341         } while (changed && (niterations > 0));
8342
8343         niterations = 1000;
8344         do {
8345                 changed = FALSE;
8346                 niterations --;
8347
8348                 /* we skip the entry block (exit is handled specially instead ) */
8349                 for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
8350
8351                         /* dont touch code inside exception clauses */
8352                         if (bb->region != -1)
8353                                 continue;
8354
8355                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
8356                                 if (cfg->verbose_level > 2) {
8357                                         g_print ("nullify block triggered %d\n", bbn->block_num);
8358                                 }
8359                                 bb->next_bb = bbn->next_bb;
8360
8361                                 for (i = 0; i < bbn->out_count; i++)
8362                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
8363
8364                                 nullify_basic_block (bbn);                      
8365                                 changed = TRUE;
8366                                 break;
8367                         }
8368
8369
8370                         if (bb->out_count == 1) {
8371                                 bbn = bb->out_bb [0];
8372
8373                                 if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
8374                                         bbn = bb->last_ins->inst_target_bb;
8375                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
8376                                             bbn->code->inst_target_bb->region == bb->region) {
8377                                                 
8378                                                 if (cfg->verbose_level > 2)
8379                                                         g_print ("in %s branch to branch triggered %d -> %d -> %d\n", cfg->method->name, 
8380                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num);
8381
8382                                                 replace_in_block (bbn, bb, NULL);
8383                                                 replace_out_block (bb, bbn, bbn->code->inst_target_bb);
8384                                                 link_bblock (cfg, bb, bbn->code->inst_target_bb);
8385                                                 bb->last_ins->inst_target_bb = bbn->code->inst_target_bb;
8386                                                 changed = TRUE;
8387                                                 break;
8388                                         }
8389                                 }
8390                         } else if (bb->out_count == 2) {
8391                                 if (bb->last_ins && MONO_IS_COND_BRANCH_NOFP (bb->last_ins)) {
8392                                         int branch_result = mono_eval_cond_branch (bb->last_ins);
8393                                         MonoBasicBlock *taken_branch_target = NULL, *untaken_branch_target = NULL;
8394                                         if (branch_result == BRANCH_TAKEN) {
8395                                                 taken_branch_target = bb->last_ins->inst_true_bb;
8396                                                 untaken_branch_target = bb->last_ins->inst_false_bb;
8397                                         } else if (branch_result == BRANCH_NOT_TAKEN) {
8398                                                 taken_branch_target = bb->last_ins->inst_false_bb;
8399                                                 untaken_branch_target = bb->last_ins->inst_true_bb;
8400                                         }
8401                                         if (taken_branch_target) {
8402                                                 /* if mono_eval_cond_branch () is ever taken to handle 
8403                                                  * non-constant values to compare, issue a pop here.
8404                                                  */
8405                                                 bb->last_ins->opcode = CEE_BR;
8406                                                 bb->last_ins->inst_target_bb = taken_branch_target;
8407                                                 replace_out_block (bb, untaken_branch_target, NULL);
8408                                                 replace_in_block (untaken_branch_target, bb, NULL);
8409                                                 changed = TRUE;
8410                                                 break;
8411                                         }
8412                                         bbn = bb->last_ins->inst_true_bb;
8413                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
8414                                             bbn->code->inst_target_bb->region == bb->region) {
8415                                                 if (cfg->verbose_level > 2)             
8416                                                         g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n", 
8417                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num, 
8418                                                                  bbn->code->opcode);
8419
8420                                                 bb->last_ins->inst_true_bb = bbn->code->inst_target_bb;
8421
8422                                                 replace_in_block (bbn, bb, NULL);
8423                                                 if (!bbn->in_count)
8424                                                         replace_in_block (bbn->code->inst_target_bb, bbn, bb);
8425                                                 replace_out_block (bb, bbn, bbn->code->inst_target_bb);
8426
8427                                                 link_bblock (cfg, bb, bbn->code->inst_target_bb);
8428
8429                                                 changed = TRUE;
8430                                                 break;
8431                                         }
8432
8433                                         bbn = bb->last_ins->inst_false_bb;
8434                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
8435                                             bbn->code->inst_target_bb->region == bb->region) {
8436                                                 if (cfg->verbose_level > 2)
8437                                                         g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n", 
8438                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num, 
8439                                                                  bbn->code->opcode);
8440
8441                                                 bb->last_ins->inst_false_bb = bbn->code->inst_target_bb;
8442
8443                                                 replace_in_block (bbn, bb, NULL);
8444                                                 if (!bbn->in_count)
8445                                                         replace_in_block (bbn->code->inst_target_bb, bbn, bb);
8446                                                 replace_out_block (bb, bbn, bbn->code->inst_target_bb);
8447
8448                                                 link_bblock (cfg, bb, bbn->code->inst_target_bb);
8449
8450                                                 changed = TRUE;
8451                                                 break;
8452                                         }
8453                                 }
8454
8455                                 if (bb->last_ins && MONO_IS_COND_BRANCH_NOFP (bb->last_ins)) {
8456                                         if (bb->last_ins->inst_false_bb->out_of_line && (bb->region == bb->last_ins->inst_false_bb->region)) {
8457                                                 /* Reverse the branch */
8458                                                 bb->last_ins->opcode = reverse_branch_op (bb->last_ins->opcode);
8459                                                 bbn = bb->last_ins->inst_false_bb;
8460                                                 bb->last_ins->inst_false_bb = bb->last_ins->inst_true_bb;
8461                                                 bb->last_ins->inst_true_bb = bbn;
8462
8463                                                 move_basic_block_to_end (cfg, bb->last_ins->inst_true_bb);
8464                                                 if (cfg->verbose_level > 2)
8465                                                         g_print ("cbranch to throw block triggered %d.\n", 
8466                                                                          bb->block_num);
8467                                         }
8468                                 }
8469                         }
8470                 }
8471         } while (changed && (niterations > 0));
8472
8473 }
8474
8475 static void
8476 mono_compile_create_vars (MonoCompile *cfg)
8477 {
8478         MonoMethodSignature *sig;
8479         MonoMethodHeader *header;
8480         int i;
8481
8482         header = mono_method_get_header (cfg->method);
8483
8484         sig = mono_method_signature (cfg->method);
8485         
8486         if (!MONO_TYPE_IS_VOID (sig->ret)) {
8487                 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
8488                 cfg->ret->opcode = OP_RETARG;
8489                 cfg->ret->inst_vtype = sig->ret;
8490                 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
8491         }
8492         if (cfg->verbose_level > 2)
8493                 g_print ("creating vars\n");
8494
8495         if (sig->hasthis)
8496                 mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
8497
8498         for (i = 0; i < sig->param_count; ++i) {
8499                 mono_compile_create_var (cfg, sig->params [i], OP_ARG);
8500                 if (sig->params [i]->byref) {
8501                         cfg->disable_ssa = TRUE;
8502                 }
8503         }
8504
8505         cfg->locals_start = cfg->num_varinfo;
8506
8507         if (cfg->verbose_level > 2)
8508                 g_print ("creating locals\n");
8509         for (i = 0; i < header->num_locals; ++i)
8510                 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
8511         if (cfg->verbose_level > 2)
8512                 g_print ("locals done\n");
8513
8514 #ifdef MONO_ARCH_HAVE_CREATE_VARS
8515         mono_arch_create_vars (cfg);
8516 #endif
8517 }
8518
8519 void
8520 mono_print_code (MonoCompile *cfg)
8521 {
8522         MonoBasicBlock *bb;
8523         
8524         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
8525                 MonoInst *tree = bb->code;      
8526
8527                 if (!tree)
8528                         continue;
8529                 
8530                 g_print ("CODE BLOCK %d (nesting %d):\n", bb->block_num, bb->nesting);
8531
8532                 for (; tree; tree = tree->next) {
8533                         mono_print_tree (tree);
8534                         g_print ("\n");
8535                 }
8536
8537                 if (bb->last_ins)
8538                         bb->last_ins->next = NULL;
8539         }
8540 }
8541
8542 extern const char * const mono_burg_rule_string [];
8543
8544 static void
8545 emit_state (MonoCompile *cfg, MBState *state, int goal)
8546 {
8547         MBState *kids [10];
8548         int ern = mono_burg_rule (state, goal);
8549         const guint16 *nts = mono_burg_nts [ern];
8550         MBEmitFunc emit;
8551
8552         //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
8553         switch (goal) {
8554         case MB_NTERM_reg:
8555                 //if (state->reg2)
8556                 //      state->reg1 = state->reg2; /* chain rule */
8557                 //else
8558 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
8559                 if (!state->reg1)
8560 #endif
8561                         state->reg1 = mono_regstate_next_int (cfg->rs);
8562                 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
8563                 break;
8564         case MB_NTERM_lreg:
8565                 state->reg1 = mono_regstate_next_int (cfg->rs);
8566                 state->reg2 = mono_regstate_next_int (cfg->rs);
8567                 break;
8568         case MB_NTERM_freg:
8569                 state->reg1 = mono_regstate_next_float (cfg->rs);
8570                 break;
8571         default:
8572 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
8573                 /*
8574                  * Enabling this might cause bugs to surface in the local register
8575                  * allocators on some architectures like x86.
8576                  */
8577                 if ((state->tree->ssa_op == MONO_SSA_STORE) && (state->left->tree->opcode == OP_REGVAR)) {
8578                         /* Do not optimize away reg-reg moves */
8579                         if (! ((state->right->tree->ssa_op == MONO_SSA_LOAD) && (state->right->left->tree->opcode == OP_REGVAR))) {
8580                                 state->right->reg1 = state->left->tree->dreg;
8581                         }
8582                 }
8583 #endif
8584
8585                 /* do nothing */
8586                 break;
8587         }
8588         if (nts [0]) {
8589                 mono_burg_kids (state, ern, kids);
8590
8591                 emit_state (cfg, kids [0], nts [0]);
8592                 if (nts [1]) {
8593                         emit_state (cfg, kids [1], nts [1]);
8594                         if (nts [2]) {
8595                                 g_assert (!nts [3]);
8596                                 emit_state (cfg, kids [2], nts [2]);
8597                         }
8598                 }
8599         }
8600
8601 //      g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
8602         if ((emit = mono_burg_func [ern]))
8603                 emit (state, state->tree, cfg); 
8604 }
8605
8606 #define DEBUG_SELECTION
8607
8608 static void 
8609 mini_select_instructions (MonoCompile *cfg)
8610 {
8611         MonoBasicBlock *bb;
8612         
8613         cfg->state_pool = mono_mempool_new ();
8614         cfg->rs = mono_regstate_new ();
8615
8616         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
8617                 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
8618                     bb->next_bb != bb->last_ins->inst_false_bb) {
8619
8620                         /* we are careful when inverting, since bugs like #59580
8621                          * could show up when dealing with NaNs.
8622                          */
8623                         if (MONO_IS_COND_BRANCH_NOFP(bb->last_ins) && bb->next_bb == bb->last_ins->inst_true_bb) {
8624                                 MonoBasicBlock *tmp =  bb->last_ins->inst_true_bb;
8625                                 bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb;
8626                                 bb->last_ins->inst_false_bb = tmp;
8627
8628                                 bb->last_ins->opcode = reverse_branch_op (bb->last_ins->opcode);
8629                         } else {                        
8630                                 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
8631                                 inst->opcode = CEE_BR;
8632                                 inst->inst_target_bb = bb->last_ins->inst_false_bb;
8633                                 mono_bblock_add_inst (bb, inst);
8634                         }
8635                 }
8636         }
8637
8638 #ifdef DEBUG_SELECTION
8639         if (cfg->verbose_level >= 4) {
8640         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
8641                 MonoInst *tree = bb->code;      
8642                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
8643                 if (!tree)
8644                         continue;
8645                 for (; tree; tree = tree->next) {
8646                         mono_print_tree (tree);
8647                         g_print ("\n");
8648                 }
8649         }
8650         }
8651 #endif
8652
8653         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
8654                 MonoInst *tree = bb->code, *next;       
8655                 MBState *mbstate;
8656
8657                 if (!tree)
8658                         continue;
8659                 bb->code = NULL;
8660                 bb->last_ins = NULL;
8661                 
8662                 cfg->cbb = bb;
8663                 mono_regstate_reset (cfg->rs);
8664
8665 #ifdef DEBUG_SELECTION
8666                 if (cfg->verbose_level >= 3)
8667                         g_print ("LABEL BLOCK %d:\n", bb->block_num);
8668 #endif
8669                 for (; tree; tree = next) {
8670                         next = tree->next;
8671 #ifdef DEBUG_SELECTION
8672                         if (cfg->verbose_level >= 3) {
8673                                 mono_print_tree (tree);
8674                                 g_print ("\n");
8675                         }
8676 #endif
8677
8678                         if (!(mbstate = mono_burg_label (tree, cfg))) {
8679                                 g_warning ("unable to label tree %p", tree);
8680                                 mono_print_tree (tree);
8681                                 g_print ("\n");                         
8682                                 g_assert_not_reached ();
8683                         }
8684                         emit_state (cfg, mbstate, MB_NTERM_stmt);
8685                 }
8686                 bb->max_ireg = cfg->rs->next_vireg;
8687                 bb->max_freg = cfg->rs->next_vfreg;
8688
8689                 if (bb->last_ins)
8690                         bb->last_ins->next = NULL;
8691
8692                 mono_mempool_empty (cfg->state_pool); 
8693         }
8694         mono_mempool_destroy (cfg->state_pool); 
8695 }
8696
8697 void
8698 mono_codegen (MonoCompile *cfg)
8699 {
8700         MonoJumpInfo *patch_info;
8701         MonoBasicBlock *bb;
8702         int i, max_epilog_size;
8703         guint8 *code;
8704
8705         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
8706                 cfg->spill_count = 0;
8707                 /* we reuse dfn here */
8708                 /* bb->dfn = bb_count++; */
8709                 mono_arch_local_regalloc (cfg, bb);
8710         }
8711
8712         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
8713                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
8714
8715         code = mono_arch_emit_prolog (cfg);
8716
8717         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
8718                 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
8719
8720         cfg->code_len = code - cfg->native_code;
8721         cfg->prolog_end = cfg->code_len;
8722
8723         mono_debug_open_method (cfg);
8724
8725         /* emit code all basic blocks */
8726         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
8727                 bb->native_offset = cfg->code_len;
8728                 mono_arch_output_basic_block (cfg, bb);
8729
8730                 if (bb == cfg->bb_exit) {
8731                         cfg->epilog_begin = cfg->code_len;
8732
8733                         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
8734                                 code = cfg->native_code + cfg->code_len;
8735                                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
8736                                 cfg->code_len = code - cfg->native_code;
8737                         }
8738
8739                         mono_arch_emit_epilog (cfg);
8740                 }
8741         }
8742
8743         mono_arch_emit_exceptions (cfg);
8744
8745         max_epilog_size = 0;
8746
8747         code = cfg->native_code + cfg->code_len;
8748
8749         /* we always allocate code in cfg->domain->code_mp to increase locality */
8750         cfg->code_size = cfg->code_len + max_epilog_size;
8751         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
8752
8753         if (cfg->method->dynamic) {
8754                 /* Allocate the code into a separate memory pool so it can be freed */
8755                 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
8756                 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
8757                 mono_domain_lock (cfg->domain);
8758                 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
8759                 mono_domain_unlock (cfg->domain);
8760
8761                 code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size);
8762         } else {
8763                 mono_domain_lock (cfg->domain);
8764                 code = mono_code_manager_reserve (cfg->domain->code_mp, cfg->code_size);
8765                 mono_domain_unlock (cfg->domain);
8766         }
8767
8768         memcpy (code, cfg->native_code, cfg->code_len);
8769         g_free (cfg->native_code);
8770         cfg->native_code = code;
8771         code = cfg->native_code + cfg->code_len;
8772   
8773         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
8774         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
8775                 switch (patch_info->type) {
8776                 case MONO_PATCH_INFO_ABS: {
8777                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
8778                         if (info) {
8779                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
8780                                 if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && 
8781                                         strstr (cfg->method->name, info->name))
8782                                         /*
8783                                          * This is an icall wrapper, and this is a call to the
8784                                          * wrapped function.
8785                                          */
8786                                         ;
8787                                 else {
8788                                         patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
8789                                         patch_info->data.name = info->name;
8790                                 }
8791                         }
8792                         else {
8793                                 MonoVTable *vtable = mono_find_class_init_trampoline_by_addr (patch_info->data.target);
8794                                 if (vtable) {
8795                                         patch_info->type = MONO_PATCH_INFO_CLASS_INIT;
8796                                         patch_info->data.klass = vtable->klass;
8797                                 }
8798                         }
8799                         break;
8800                 }
8801                 case MONO_PATCH_INFO_SWITCH: {
8802                         gpointer *table;
8803                         if (cfg->method->dynamic) {
8804                                 table = mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
8805                         } else {
8806                                 mono_domain_lock (cfg->domain);
8807                                 table = mono_code_manager_reserve (cfg->domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
8808                                 mono_domain_unlock (cfg->domain);
8809                         }
8810
8811                         if (!cfg->compile_aot)
8812                                 /* In the aot case, the patch already points to the correct location */
8813                                 patch_info->ip.i = patch_info->ip.label->inst_c0;
8814                         for (i = 0; i < patch_info->data.table->table_size; i++) {
8815                                 table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
8816                         }
8817                         patch_info->data.table->table = (MonoBasicBlock**)table;
8818                         break;
8819                 }
8820                 default:
8821                         /* do nothing */
8822                         break;
8823                 }
8824         }
8825        
8826         if (cfg->verbose_level > 0) {
8827                 char* nm = mono_method_full_name (cfg->method, TRUE);
8828                 g_print ("Method %s emitted at %p to %p [%s]\n", 
8829                                  nm, 
8830                                  cfg->native_code, cfg->native_code + cfg->code_len, cfg->domain->friendly_name);
8831                 g_free (nm);
8832         }
8833
8834 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
8835         mono_arch_save_unwind_info (cfg);
8836 #endif
8837         
8838         mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
8839
8840         if (cfg->method->dynamic) {
8841                 mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
8842         } else {
8843                 mono_domain_lock (cfg->domain);
8844                 mono_code_manager_commit (cfg->domain->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
8845                 mono_domain_unlock (cfg->domain);
8846         }
8847         
8848         mono_arch_flush_icache (cfg->native_code, cfg->code_len);
8849
8850         mono_debug_close_method (cfg);
8851 }
8852
8853 static void
8854 mono_cprop_copy_values (MonoCompile *cfg, MonoInst *tree, MonoInst **acp)
8855 {
8856         MonoInst *cp;
8857         int arity;
8858
8859         if (tree->ssa_op == MONO_SSA_LOAD && (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG) && 
8860             (cp = acp [tree->inst_i0->inst_c0]) && !tree->inst_i0->flags) {
8861
8862                 if (cp->opcode == OP_ICONST) {
8863                         if (cfg->opt & MONO_OPT_CONSPROP) {
8864                                 //{ static int c = 0; printf ("CCOPY %d %d %s\n", c++, cp->inst_c0, mono_method_full_name (cfg->method, TRUE)); }
8865                                 *tree = *cp;
8866                         }
8867                 } else {
8868                         if (tree->inst_i0->inst_vtype->type == cp->inst_vtype->type) {
8869                                 if (cfg->opt & MONO_OPT_COPYPROP) {
8870                                         //{ static int c = 0; printf ("VCOPY %d\n", ++c); }
8871                                         tree->inst_i0 = cp;
8872                                 } 
8873                         }
8874                 } 
8875         } else {
8876                 arity = mono_burg_arity [tree->opcode];
8877
8878                 if (arity) {
8879                         mono_cprop_copy_values (cfg, tree->inst_i0, acp);
8880                         if (cfg->opt & MONO_OPT_CFOLD)
8881                                 mono_constant_fold_inst (tree, NULL); 
8882                         /* The opcode may have changed */
8883                         if (mono_burg_arity [tree->opcode] > 1) {
8884                                 mono_cprop_copy_values (cfg, tree->inst_i1, acp);
8885                                 if (cfg->opt & MONO_OPT_CFOLD)
8886                                         mono_constant_fold_inst (tree, NULL); 
8887                         }
8888                         mono_constant_fold_inst (tree, NULL); 
8889                 }
8890         }
8891 }
8892
8893 static void
8894 mono_cprop_invalidate_values (MonoInst *tree, MonoInst **acp, int acp_size)
8895 {
8896         int arity;
8897
8898         switch (tree->opcode) {
8899         case CEE_STIND_I:
8900         case CEE_STIND_I1:
8901         case CEE_STIND_I2:
8902         case CEE_STIND_I4:
8903         case CEE_STIND_REF:
8904         case CEE_STIND_I8:
8905         case CEE_STIND_R4:
8906         case CEE_STIND_R8:
8907         case CEE_STOBJ:
8908                 if (tree->ssa_op == MONO_SSA_NOP) {
8909                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
8910                         return;
8911                 }
8912
8913                 break;
8914         case CEE_CALL:
8915         case OP_CALL_REG:
8916         case CEE_CALLVIRT:
8917         case OP_LCALL_REG:
8918         case OP_LCALLVIRT:
8919         case OP_LCALL:
8920         case OP_FCALL_REG:
8921         case OP_FCALLVIRT:
8922         case OP_FCALL:
8923         case OP_VCALL_REG:
8924         case OP_VCALLVIRT:
8925         case OP_VCALL:
8926         case OP_VOIDCALL_REG:
8927         case OP_VOIDCALLVIRT:
8928         case OP_VOIDCALL: {
8929                 MonoCallInst *call = (MonoCallInst *)tree;
8930                 MonoMethodSignature *sig = call->signature;
8931                 int i, byref = FALSE;
8932
8933                 for (i = 0; i < sig->param_count; i++) {
8934                         if (sig->params [i]->byref) {
8935                                 byref = TRUE;
8936                                 break;
8937                         }
8938                 }
8939
8940                 if (byref)
8941                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
8942
8943                 return;
8944         }
8945         default:
8946                 break;
8947         }
8948
8949         arity = mono_burg_arity [tree->opcode];
8950
8951         switch (arity) {
8952         case 0:
8953                 break;
8954         case 1:
8955                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
8956                 break;
8957         case 2:
8958                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
8959                 mono_cprop_invalidate_values (tree->inst_i1, acp, acp_size);
8960                 break;
8961         default:
8962                 g_assert_not_reached ();
8963         }
8964 }
8965
8966 static void
8967 mono_local_cprop_bb (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **acp, int acp_size)
8968 {
8969         MonoInst *tree = bb->code;      
8970         int i;
8971
8972         if (!tree)
8973                 return;
8974
8975         for (; tree; tree = tree->next) {
8976
8977                 mono_cprop_copy_values (cfg, tree, acp);
8978
8979                 mono_cprop_invalidate_values (tree, acp, acp_size);
8980
8981                 if (tree->ssa_op == MONO_SSA_STORE  && 
8982                     (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG)) {
8983                         MonoInst *i1 = tree->inst_i1;
8984
8985                         acp [tree->inst_i0->inst_c0] = NULL;
8986
8987                         for (i = 0; i < acp_size; i++) {
8988                                 if (acp [i] && acp [i]->opcode != OP_ICONST && 
8989                                     acp [i]->inst_c0 == tree->inst_i0->inst_c0) {
8990                                         acp [i] = NULL;
8991                                 }
8992                         }
8993
8994                         if (i1->opcode == OP_ICONST) {
8995                                 acp [tree->inst_i0->inst_c0] = i1;
8996                                 //printf ("DEF1 BB%d %d\n", bb->block_num,tree->inst_i0->inst_c0);
8997                         }
8998                         if (i1->ssa_op == MONO_SSA_LOAD && 
8999                             (i1->inst_i0->opcode == OP_LOCAL || i1->inst_i0->opcode == OP_ARG) &&
9000                             (i1->inst_i0->inst_c0 != tree->inst_i0->inst_c0)) {
9001                                 acp [tree->inst_i0->inst_c0] = i1->inst_i0;
9002                                 //printf ("DEF2 BB%d %d %d\n", bb->block_num,tree->inst_i0->inst_c0,i1->inst_i0->inst_c0);
9003                         }
9004                 }
9005
9006                 /*
9007                   if (tree->opcode == CEE_BEQ) {
9008                   g_assert (tree->inst_i0->opcode == OP_COMPARE);
9009                   if (tree->inst_i0->inst_i0->opcode == OP_ICONST &&
9010                   tree->inst_i0->inst_i1->opcode == OP_ICONST) {
9011                   
9012                   tree->opcode = CEE_BR;
9013                   if (tree->inst_i0->inst_i0->opcode == tree->inst_i0->inst_i1->opcode) {
9014                   tree->inst_target_bb = tree->inst_true_bb;
9015                   } else {
9016                   tree->inst_target_bb = tree->inst_false_bb;
9017                   }
9018                   }
9019                   }
9020                 */
9021         }
9022 }
9023
9024 static void
9025 mono_local_cprop (MonoCompile *cfg)
9026 {
9027         MonoBasicBlock *bb;
9028         MonoInst **acp;
9029
9030         acp = alloca (sizeof (MonoInst *) * cfg->num_varinfo);
9031
9032         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9033                 memset (acp, 0, sizeof (MonoInst *) * cfg->num_varinfo);
9034                 mono_local_cprop_bb (cfg, bb, acp, cfg->num_varinfo);
9035         }
9036 }
9037
9038 static void
9039 remove_critical_edges (MonoCompile *cfg) {
9040         MonoBasicBlock *bb;
9041         MonoBasicBlock *previous_bb;
9042         
9043         if (cfg->verbose_level > 3) {
9044                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9045                         int i;
9046                         printf ("remove_critical_edges %s, BEFORE BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
9047                         for (i = 0; i < bb->in_count; i++) {
9048                                 printf (" %d", bb->in_bb [i]->block_num);
9049                         }
9050                         printf (") (out:");
9051                         for (i = 0; i < bb->out_count; i++) {
9052                                 printf (" %d", bb->out_bb [i]->block_num);
9053                         }
9054                         printf (")");
9055                         if (bb->last_ins != NULL) {
9056                                 printf (" ");
9057                                 mono_print_tree (bb->last_ins);
9058                         }
9059                         printf ("\n");
9060                 }
9061         }
9062         
9063         for (previous_bb = cfg->bb_entry, bb = previous_bb->next_bb; bb != NULL; previous_bb = previous_bb->next_bb, bb = bb->next_bb) {
9064                 if (bb->in_count > 1) {
9065                         int in_bb_index;
9066                         for (in_bb_index = 0; in_bb_index < bb->in_count; in_bb_index++) {
9067                                 MonoBasicBlock *in_bb = bb->in_bb [in_bb_index];
9068                                 if (in_bb->out_count > 1) {
9069                                         MonoBasicBlock *new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
9070                                         new_bb->block_num = cfg->num_bblocks++;
9071 //                                      new_bb->real_offset = bb->real_offset;
9072                                         new_bb->region = bb->region;
9073                                         
9074                                         /* Do not alter the CFG while altering the BB list */
9075                                         if (previous_bb->region == bb->region) {
9076                                                 if (previous_bb != cfg->bb_entry) {
9077                                                         /* If previous_bb "followed through" to bb, */
9078                                                         /* keep it linked with a CEE_BR */
9079                                                         if ((previous_bb->last_ins == NULL) ||
9080                                                                         ((previous_bb->last_ins->opcode != CEE_BR) &&
9081                                                                         (! (MONO_IS_COND_BRANCH_OP (previous_bb->last_ins))) &&
9082                                                                         (previous_bb->last_ins->opcode != CEE_SWITCH))) {
9083                                                                 int i;
9084                                                                 /* Make sure previous_bb really falls through bb */
9085                                                                 for (i = 0; i < previous_bb->out_count; i++) {
9086                                                                         if (previous_bb->out_bb [i] == bb) {
9087                                                                                 MonoInst *jump;
9088                                                                                 MONO_INST_NEW (cfg, jump, CEE_BR);
9089                                                                                 MONO_ADD_INS (previous_bb, jump);
9090                                                                                 jump->cil_code = previous_bb->cil_code;
9091                                                                                 jump->inst_target_bb = bb;
9092                                                                                 break;
9093                                                                         }
9094                                                                 }
9095                                                         }
9096                                                 } else {
9097                                                         /* We cannot add any inst to the entry BB, so we must */
9098                                                         /* put a new BB in the middle to hold the CEE_BR */
9099                                                         MonoInst *jump;
9100                                                         MonoBasicBlock *new_bb_after_entry = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
9101                                                         new_bb_after_entry->block_num = cfg->num_bblocks++;
9102 //                                                      new_bb_after_entry->real_offset = bb->real_offset;
9103                                                         new_bb_after_entry->region = bb->region;
9104                                                         
9105                                                         MONO_INST_NEW (cfg, jump, CEE_BR);
9106                                                         MONO_ADD_INS (new_bb_after_entry, jump);
9107                                                         jump->cil_code = bb->cil_code;
9108                                                         jump->inst_target_bb = bb;
9109                                                         
9110                                                         previous_bb->next_bb = new_bb_after_entry;
9111                                                         previous_bb = new_bb_after_entry;
9112                                                         
9113                                                         if (cfg->verbose_level > 2) {
9114                                                                 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);
9115                                                         }
9116                                                 }
9117                                         }
9118                                         
9119                                         /* Insert new_bb in the BB list */
9120                                         previous_bb->next_bb = new_bb;
9121                                         new_bb->next_bb = bb;
9122                                         previous_bb = new_bb;
9123                                         
9124                                         /* Setup in_bb and out_bb */
9125                                         new_bb->in_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
9126                                         new_bb->in_bb [0] = in_bb;
9127                                         new_bb->in_count = 1;
9128                                         new_bb->out_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
9129                                         new_bb->out_bb [0] = bb;
9130                                         new_bb->out_count = 1;
9131                                         
9132                                         /* Relink in_bb and bb to (from) new_bb */
9133                                         replace_out_block (in_bb, bb, new_bb);
9134                                         replace_out_block_in_code (in_bb, bb, new_bb);
9135                                         replace_in_block (bb, in_bb, new_bb);
9136                                         
9137                                         if (cfg->verbose_level > 2) {
9138                                                 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);
9139                                         }
9140                                 }
9141                         }
9142                 }
9143         }
9144         
9145         if (cfg->verbose_level > 3) {
9146                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9147                         int i;
9148                         printf ("remove_critical_edges %s, AFTER BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
9149                         for (i = 0; i < bb->in_count; i++) {
9150                                 printf (" %d", bb->in_bb [i]->block_num);
9151                         }
9152                         printf (") (out:");
9153                         for (i = 0; i < bb->out_count; i++) {
9154                                 printf (" %d", bb->out_bb [i]->block_num);
9155                         }
9156                         printf (")");
9157                         if (bb->last_ins != NULL) {
9158                                 printf (" ");
9159                                 mono_print_tree (bb->last_ins);
9160                         }
9161                         printf ("\n");
9162                 }
9163         }
9164 }
9165
9166 MonoCompile*
9167 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
9168 {
9169         MonoMethodHeader *header = mono_method_get_header (method);
9170         guint8 *ip;
9171         MonoCompile *cfg;
9172         MonoJitInfo *jinfo;
9173         int dfn = 0, i, code_size_ratio;
9174
9175         if (!header)
9176                 return NULL;
9177
9178         ip = (guint8 *)header->code;
9179
9180         mono_jit_stats.methods_compiled++;
9181         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
9182                 mono_profiler_method_jit (method);
9183
9184         cfg = g_new0 (MonoCompile, 1);
9185         cfg->method = method;
9186         cfg->mempool = mono_mempool_new ();
9187         cfg->opt = opts;
9188         cfg->prof_options = mono_profiler_get_events ();
9189         cfg->run_cctors = run_cctors;
9190         cfg->bb_hash = g_hash_table_new (NULL, NULL);
9191         cfg->domain = domain;
9192         cfg->verbose_level = mini_verbose;
9193         cfg->compile_aot = compile_aot;
9194         cfg->intvars = mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * 
9195                                             mono_method_get_header (method)->max_stack);
9196
9197         if (cfg->verbose_level > 2)
9198                 g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
9199
9200         /*
9201          * create MonoInst* which represents arguments and local variables
9202          */
9203         mono_compile_create_vars (cfg);
9204
9205         if ((i = mono_method_to_ir (cfg, method, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
9206                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
9207                         mono_profiler_method_end_jit (method, MONO_PROFILE_FAILED);
9208                 mono_destroy_compile (cfg);
9209                 return NULL;
9210         }
9211
9212         mono_jit_stats.basic_blocks += cfg->num_bblocks;
9213         mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
9214
9215         if ((cfg->num_varinfo > 2000) && !mono_compile_aot) {
9216                 /* 
9217                  * we disable some optimizations if there are too many variables
9218                  * because JIT time may become too expensive. The actual number needs 
9219                  * to be tweaked and eventually the non-linear algorithms should be fixed.
9220                  */
9221                 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
9222                 cfg->disable_ssa = TRUE;
9223         }
9224
9225         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
9226
9227         if (cfg->opt & MONO_OPT_BRANCH)
9228                 optimize_branches (cfg);
9229
9230         if (cfg->opt & MONO_OPT_SSAPRE) {
9231                 remove_critical_edges (cfg);
9232         }
9233
9234         /* Depth-first ordering on basic blocks */
9235         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
9236
9237         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
9238         if (cfg->num_bblocks != dfn + 1) {
9239                 MonoBasicBlock *bb;
9240
9241                 cfg->num_bblocks = dfn + 1;
9242
9243                 if (!header->clauses) {
9244                         /* remove unreachable code, because the code in them may be 
9245                          * inconsistent  (access to dead variables for example) */
9246                         for (bb = cfg->bb_entry; bb;) {
9247                                 MonoBasicBlock *bbn = bb->next_bb;
9248
9249                                 if (bbn && bbn->region == -1 && !bbn->dfn) {
9250                                         if (cfg->verbose_level > 1)
9251                                                 g_print ("found unreachabel code in BB%d\n", bbn->block_num);
9252                                         bb->next_bb = bbn->next_bb;
9253                                         nullify_basic_block (bbn);                      
9254                                 } else {
9255                                         bb = bb->next_bb;
9256                                 }
9257                         }
9258                 }
9259         }
9260
9261         if (cfg->opt & MONO_OPT_LOOP) {
9262                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
9263                 mono_compute_natural_loops (cfg);
9264         }
9265
9266         /* after method_to_ir */
9267         if (parts == 1)
9268                 return cfg;
9269
9270 //#define DEBUGSSA "logic_run"
9271 #define DEBUGSSA_CLASS "Tests"
9272 #ifdef DEBUGSSA
9273
9274         if (!header->num_clauses && !cfg->disable_ssa) {
9275                 mono_local_cprop (cfg);
9276                 mono_ssa_compute (cfg);
9277         }
9278 #else 
9279
9280         /* fixme: add all optimizations which requires SSA */
9281         if (cfg->opt & (MONO_OPT_DEADCE | MONO_OPT_ABCREM | MONO_OPT_SSAPRE)) {
9282                 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
9283                         mono_local_cprop (cfg);
9284                         mono_ssa_compute (cfg);
9285
9286                         if (cfg->verbose_level >= 2) {
9287                                 print_dfn (cfg);
9288                         }
9289                 }
9290         }
9291 #endif
9292
9293         /* after SSA translation */
9294         if (parts == 2)
9295                 return cfg;
9296
9297         if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
9298                 if (cfg->comp_done & MONO_COMP_SSA) {
9299                         mono_ssa_cprop (cfg);
9300                 } else {
9301                         mono_local_cprop (cfg);
9302                 }
9303         }
9304
9305         if (cfg->comp_done & MONO_COMP_SSA) {                   
9306                 mono_ssa_deadce (cfg);
9307
9308                 //mono_ssa_strength_reduction (cfg);
9309
9310                 if ((cfg->flags & MONO_CFG_HAS_LDELEMA) && (cfg->opt & MONO_OPT_ABCREM))
9311                         mono_perform_abc_removal (cfg);
9312                 
9313                 if (cfg->opt & MONO_OPT_SSAPRE)
9314                         mono_perform_ssapre (cfg);
9315                 
9316                 mono_ssa_remove (cfg);
9317
9318                 if (cfg->opt & MONO_OPT_BRANCH)
9319                         optimize_branches (cfg);
9320         }
9321
9322         /* after SSA removal */
9323         if (parts == 3)
9324                 return cfg;
9325
9326         decompose_pass (cfg);
9327
9328         if (cfg->got_var) {
9329                 GList *regs;
9330
9331                 g_assert (cfg->got_var_allocated);
9332
9333                 /* 
9334                  * Allways allocate the GOT var to a register, because keeping it
9335                  * in memory will increase the number of live temporaries in some
9336                  * code created by inssel.brg, leading to the well known spills+
9337                  * branches problem. Testcase: mcs crash in 
9338                  * System.MonoCustomAttrs:GetCustomAttributes.
9339                  */
9340                 regs = mono_arch_get_global_int_regs (cfg);
9341                 g_assert (regs);
9342                 cfg->got_var->opcode = OP_REGVAR;
9343                 cfg->got_var->dreg = GPOINTER_TO_INT (regs->data);
9344                 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
9345                 
9346                 g_list_free (regs);
9347         }
9348
9349         if (cfg->opt & MONO_OPT_LINEARS) {
9350                 GList *vars, *regs;
9351
9352                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
9353                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
9354                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
9355                         mono_analyze_liveness (cfg);
9356
9357                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
9358                         regs = mono_arch_get_global_int_regs (cfg);
9359                         if (cfg->got_var)
9360                                 regs = g_list_delete_link (regs, regs);
9361                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
9362                 }
9363         }
9364
9365         //mono_print_code (cfg);
9366
9367     //print_dfn (cfg);
9368         
9369         /* variables are allocated after decompose, since decompose could create temps */
9370         mono_arch_allocate_vars (cfg);
9371
9372         if (cfg->opt & MONO_OPT_CFOLD)
9373                 mono_constant_fold (cfg);
9374
9375         mini_select_instructions (cfg);
9376
9377         mono_codegen (cfg);
9378         if (cfg->verbose_level >= 2) {
9379                 char *id =  mono_method_full_name (cfg->method, FALSE);
9380                 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
9381                 g_free (id);
9382         }
9383         
9384         if (cfg->method->dynamic) {
9385                 jinfo = g_malloc0 (sizeof (MonoJitInfo) + (header->num_clauses * sizeof (MonoJitExceptionInfo)));
9386         } else {
9387                 /* we access cfg->domain->mp */
9388                 mono_domain_lock (cfg->domain);
9389                 jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo) + (header->num_clauses * sizeof (MonoJitExceptionInfo)));
9390                 mono_domain_unlock (cfg->domain);
9391         }
9392
9393         jinfo->method = method;
9394         jinfo->code_start = cfg->native_code;
9395         jinfo->code_size = cfg->code_len;
9396         jinfo->used_regs = cfg->used_int_regs;
9397         jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
9398         jinfo->cas_inited = FALSE; /* initialization delayed at the first stalk walk using this method */
9399
9400         if (header->num_clauses) {
9401                 int i;
9402
9403                 jinfo->num_clauses = header->num_clauses;
9404
9405                 for (i = 0; i < header->num_clauses; i++) {
9406                         MonoExceptionClause *ec = &header->clauses [i];
9407                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
9408                         MonoBasicBlock *tblock;
9409                         MonoInst *exvar;
9410
9411                         ei->flags = ec->flags;
9412
9413                         exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
9414                         ei->exvar_offset = exvar ? exvar->inst_offset : 0;
9415
9416                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
9417                                 tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->data.filter_offset);
9418                                 g_assert (tblock);
9419                                 ei->data.filter = cfg->native_code + tblock->native_offset;
9420                         } else {
9421                                 ei->data.catch_class = ec->data.catch_class;
9422                         }
9423
9424                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset);
9425                         g_assert (tblock);
9426                         ei->try_start = cfg->native_code + tblock->native_offset;
9427                         g_assert (tblock->native_offset);
9428                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset + ec->try_len);
9429                         g_assert (tblock);
9430                         ei->try_end = cfg->native_code + tblock->native_offset;
9431                         g_assert (tblock->native_offset);
9432                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->handler_offset);
9433                         g_assert (tblock);
9434                         ei->handler_start = cfg->native_code + tblock->native_offset;
9435                 }
9436         }
9437
9438         cfg->jit_info = jinfo;
9439 #if defined(__arm__)
9440         mono_arch_fixup_jinfo (cfg);
9441 #endif
9442
9443         mono_domain_lock (cfg->domain);
9444         mono_jit_info_table_add (cfg->domain, jinfo);
9445
9446         if (cfg->method->dynamic)
9447                 mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = jinfo;
9448         mono_domain_unlock (cfg->domain);
9449
9450         /* collect statistics */
9451         mono_jit_stats.allocated_code_size += cfg->code_len;
9452         code_size_ratio = cfg->code_len;
9453         if (code_size_ratio > mono_jit_stats.biggest_method_size) {
9454                         mono_jit_stats.biggest_method_size = code_size_ratio;
9455                         mono_jit_stats.biggest_method = method;
9456         }
9457         code_size_ratio = (code_size_ratio * 100) / mono_method_get_header (method)->code_size;
9458         if (code_size_ratio > mono_jit_stats.max_code_size_ratio) {
9459                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
9460                 mono_jit_stats.max_ratio_method = method;
9461         }
9462         mono_jit_stats.native_code_size += cfg->code_len;
9463
9464         if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
9465                 mono_profiler_method_end_jit (method, MONO_PROFILE_OK);
9466
9467         /* this can only be set if the security manager is active */
9468         if (cfg->exception_type == MONO_EXCEPTION_SECURITY_LINKDEMAND) {
9469                 MonoAssembly *assembly = mono_image_get_assembly (method->klass->image);
9470                 MonoReflectionAssembly *refass = (MonoReflectionAssembly*) mono_assembly_get_object (domain, assembly);
9471                 MonoReflectionMethod *refmet = mono_method_get_object (domain, method, NULL);
9472                 MonoSecurityManager* secman = mono_security_manager_get_methods ();
9473                 MonoObject *exc = NULL;
9474                 gpointer args [3];
9475
9476                 args [0] = &cfg->exception_data;
9477                 args [1] = refass;
9478                 args [2] = refmet;
9479                 mono_runtime_invoke (secman->linkdemandsecurityexception, NULL, args, &exc);
9480
9481                 mono_destroy_compile (cfg);
9482                 cfg = NULL;
9483
9484                 mono_raise_exception ((MonoException*)exc);
9485         }
9486
9487         return cfg;
9488 }
9489
9490 static gpointer
9491 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain)
9492 {
9493         MonoCompile *cfg;
9494         GHashTable *jit_code_hash;
9495         gpointer code = NULL;
9496         guint32 opt;
9497         MonoJitInfo *info;
9498
9499         opt = default_opt;
9500
9501         jit_code_hash = target_domain->jit_code_hash;
9502
9503         method = mono_get_inflated_method (method);
9504
9505 #ifdef MONO_USE_AOT_COMPILER
9506         if (!mono_compile_aot && (opt & MONO_OPT_AOT) && !(mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)) {
9507                 MonoJitInfo *info;
9508                 MonoDomain *domain = mono_domain_get ();
9509
9510                 mono_domain_lock (domain);
9511
9512                 mono_class_init (method->klass);
9513                 if ((info = mono_aot_get_method (domain, method))) {
9514                         g_hash_table_insert (domain->jit_code_hash, method, info);
9515                         mono_domain_unlock (domain);
9516                         mono_runtime_class_init (mono_class_vtable (domain, method->klass));
9517                         return info->code_start;
9518                 }
9519
9520                 mono_domain_unlock (domain);
9521         }
9522 #endif
9523
9524         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
9525             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
9526                 MonoMethod *nm;
9527                 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
9528
9529                 if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
9530                         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);
9531
9532                 if (!piinfo->addr) {
9533                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
9534                                 piinfo->addr = mono_lookup_internal_call (method);
9535                         else
9536                                 if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
9537                                         mono_lookup_pinvoke_call (method, NULL, NULL);
9538                 }
9539                         nm = mono_marshal_get_native_wrapper (method);
9540                         return mono_get_addr_from_ftnptr (mono_compile_method (nm));
9541
9542                         //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE) 
9543                         //mono_debug_add_wrapper (method, nm);
9544         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
9545                 const char *name = method->name;
9546                 MonoMethod *nm;
9547
9548                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
9549                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
9550                                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name ("mono_delegate_ctor");
9551                                 g_assert (mi);
9552                                 return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper (mi));
9553                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
9554                                 nm = mono_marshal_get_delegate_invoke (method);
9555                                         return mono_get_addr_from_ftnptr (mono_compile_method (nm));
9556                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
9557                                 nm = mono_marshal_get_delegate_begin_invoke (method);
9558                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
9559                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
9560                                 nm = mono_marshal_get_delegate_end_invoke (method);
9561                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
9562                         }
9563                 }
9564                 return NULL;
9565         }
9566
9567         cfg = mini_method_compile (method, opt, target_domain, TRUE, FALSE, 0);
9568
9569         if (!cfg) {
9570                 /* Throw a type load exception if needed */
9571                 MonoLoaderError *error = mono_loader_get_last_error ();
9572
9573                 if (error) {
9574                         MonoException *ex = mini_loader_error_to_exception (error);
9575                         mono_loader_clear_error ();
9576                         mono_raise_exception (ex);
9577                 }
9578                 else
9579                         g_assert_not_reached ();
9580         }
9581
9582         mono_domain_lock (target_domain);
9583
9584         /* Check if some other thread already did the job. In this case, we can
9585        discard the code this thread generated. */
9586
9587         if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
9588                 /* We can't use a domain specific method in another domain */
9589                 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
9590                         code = info->code_start;
9591 //                      printf("Discarding code for method %s\n", method->name);
9592                 }
9593         }
9594         
9595         if (code == NULL) {
9596                 g_hash_table_insert (jit_code_hash, method, cfg->jit_info);
9597                 code = cfg->native_code;
9598         }
9599
9600         mono_destroy_compile (cfg);
9601
9602         if (target_domain->jump_target_hash) {
9603                 MonoJumpInfo patch_info;
9604                 GSList *list, *tmp;
9605                 list = g_hash_table_lookup (target_domain->jump_target_hash, method);
9606                 if (list) {
9607                         patch_info.next = NULL;
9608                         patch_info.ip.i = 0;
9609                         patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
9610                         patch_info.data.method = method;
9611                         g_hash_table_remove (target_domain->jump_target_hash, method);
9612                 }
9613                 for (tmp = list; tmp; tmp = tmp->next)
9614                         mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info, TRUE);
9615                 g_slist_free (list);
9616         }
9617
9618         mono_domain_unlock (target_domain);
9619
9620         mono_runtime_class_init (mono_class_vtable (target_domain, method->klass));
9621         return code;
9622 }
9623
9624 static gpointer
9625 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt)
9626 {
9627         /* FIXME: later copy the code from mono */
9628         MonoDomain *target_domain, *domain = mono_domain_get ();
9629         MonoJitInfo *info;
9630         gpointer p;
9631
9632         if (opt & MONO_OPT_SHARED)
9633                 target_domain = mono_get_root_domain ();
9634         else 
9635                 target_domain = domain;
9636
9637         mono_domain_lock (target_domain);
9638
9639         if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
9640                 /* We can't use a domain specific method in another domain */
9641                 if (! ((domain != target_domain) && !info->domain_neutral)) {
9642                         mono_domain_unlock (target_domain);
9643                         mono_jit_stats.methods_lookups++;
9644                         mono_runtime_class_init (mono_class_vtable (domain, method->klass));
9645                         return mono_create_ftnptr (domain, info->code_start);
9646                 }
9647         }
9648
9649         mono_domain_unlock (target_domain);
9650         p = mono_jit_compile_method_inner (method, target_domain);
9651         return mono_create_ftnptr (domain, p);
9652 }
9653
9654 static gpointer
9655 mono_jit_compile_method (MonoMethod *method)
9656 {
9657         return mono_jit_compile_method_with_opt (method, default_opt);
9658 }
9659
9660 static void
9661 invalidated_delegate_trampoline (char *desc)
9662 {
9663         g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
9664                  "See http://www.go-mono.com/delegate.html for an explanation and ways to fix this.",
9665                  desc);
9666 }
9667
9668 /*
9669  * mono_jit_free_method:
9670  *
9671  *  Free all memory allocated by the JIT for METHOD.
9672  */
9673 static void
9674 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
9675 {
9676         MonoJitDynamicMethodInfo *ji;
9677         gboolean destroy = TRUE;
9678
9679         g_assert (method->dynamic);
9680
9681         mono_domain_lock (domain);
9682         ji = mono_dynamic_code_hash_lookup (domain, method);
9683         mono_domain_unlock (domain);
9684
9685         if (!ji)
9686                 return;
9687         mono_domain_lock (domain);
9688         g_hash_table_remove (domain->dynamic_code_hash, method);
9689         g_hash_table_remove (domain->jit_code_hash, method);
9690         mono_domain_unlock (domain);
9691
9692 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
9693         if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
9694                 /*
9695                  * Instead of freeing the code, change it to call an error routine
9696                  * so people can fix their code.
9697                  */
9698                 char *type = mono_type_full_name (&method->klass->byval_arg);
9699                 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
9700
9701                 g_free (type);
9702                 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
9703                 destroy = FALSE;
9704         }
9705 #endif
9706
9707         /* 
9708          * This needs to be done before freeing code_mp, since the code address is the
9709          * key in the table, so if we the code_mp first, another thread can grab the
9710          * same code address and replace our entry in the table.
9711          */
9712         mono_jit_info_table_remove (domain, ji->ji);
9713
9714         if (destroy)
9715                 mono_code_manager_destroy (ji->code_mp);
9716         g_free (ji->ji);
9717         g_free (ji);
9718 }
9719
9720 static gpointer
9721 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
9722 {
9723         MonoDomain *target_domain;
9724         MonoJitInfo *info;
9725
9726         if (default_opt & MONO_OPT_SHARED)
9727                 target_domain = mono_get_root_domain ();
9728         else 
9729                 target_domain = domain;
9730
9731         mono_domain_lock (target_domain);
9732
9733         if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
9734                 /* We can't use a domain specific method in another domain */
9735                 if (! ((domain != target_domain) && !info->domain_neutral)) {
9736                         mono_domain_unlock (target_domain);
9737                         mono_jit_stats.methods_lookups++;
9738                         return info->code_start;
9739                 }
9740         }
9741
9742         mono_domain_unlock (target_domain);
9743
9744         return NULL;
9745 }
9746
9747 /**
9748  * mono_jit_runtime_invoke:
9749  * @method: the method to invoke
9750  * @obj: this pointer
9751  * @params: array of parameter values.
9752  * @exc: used to catch exceptions objects
9753  */
9754 static MonoObject*
9755 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
9756 {
9757         MonoMethod *invoke;
9758         MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
9759         void* compiled_method;
9760
9761         if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
9762                 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
9763                 return NULL;
9764         }
9765
9766         method = mono_get_inflated_method (method);
9767         invoke = mono_marshal_get_runtime_invoke (method);
9768         runtime_invoke = mono_jit_compile_method (invoke);
9769         
9770         /* We need this here becuase mono_marshal_get_runtime_invoke can be place 
9771          * the helper method in System.Object and not the target class
9772          */
9773         mono_runtime_class_init (mono_class_vtable (mono_domain_get (), method->klass));
9774
9775         compiled_method = mono_jit_compile_method (method);
9776         return runtime_invoke (obj, params, exc, compiled_method);
9777 }
9778
9779 #ifdef PLATFORM_WIN32
9780 #define GET_CONTEXT \
9781         struct sigcontext *ctx = (struct sigcontext*)_dummy;
9782 #else
9783 #ifdef __sparc
9784 #define GET_CONTEXT \
9785     void *ctx = context;
9786 #elif defined(sun)    // Solaris x86
9787 #define GET_CONTEXT \
9788     ucontext_t *uctx = context; \
9789     struct sigcontext *ctx = (struct sigcontext *)&(uctx->uc_mcontext);
9790 #elif defined(__ppc__) || defined (__powerpc__) || defined (__s390__) || defined (MONO_ARCH_USE_SIGACTION)
9791 #define GET_CONTEXT \
9792     void *ctx = context;
9793 #else
9794 #define GET_CONTEXT \
9795         void **_p = (void **)&_dummy; \
9796         struct sigcontext *ctx = (struct sigcontext *)++_p;
9797 #endif
9798 #endif
9799
9800 #ifdef MONO_ARCH_USE_SIGACTION
9801 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, siginfo_t *info, void *context)
9802 #else
9803 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy)
9804 #endif
9805
9806 static void
9807 SIG_HANDLER_SIGNATURE (sigfpe_signal_handler)
9808 {
9809         MonoException *exc = NULL;
9810 #ifndef MONO_ARCH_USE_SIGACTION
9811         void *info = NULL;
9812 #endif
9813         GET_CONTEXT;
9814
9815 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
9816         if (mono_arch_is_int_overflow (ctx, info))
9817                 exc = mono_get_exception_arithmetic ();
9818         else
9819                 exc = mono_get_exception_divide_by_zero ();
9820 #else
9821         exc = mono_get_exception_divide_by_zero ();
9822 #endif
9823         
9824         mono_arch_handle_exception (ctx, exc, FALSE);
9825 }
9826
9827 static void
9828 SIG_HANDLER_SIGNATURE (sigill_signal_handler)
9829 {
9830         MonoException *exc;
9831         GET_CONTEXT
9832         exc = mono_get_exception_execution_engine ("SIGILL");
9833         
9834         mono_arch_handle_exception (ctx, exc, FALSE);
9835 }
9836
9837 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
9838
9839 #ifndef MONO_ARCH_USE_SIGACTION
9840 #error "Can't use sigaltstack without sigaction"
9841 #endif
9842
9843 #endif
9844
9845 static void
9846 SIG_HANDLER_SIGNATURE (sigsegv_signal_handler)
9847 {
9848         MonoException *exc = NULL;
9849 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
9850         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
9851 #endif
9852         GET_CONTEXT
9853
9854 #ifdef MONO_ARCH_USE_SIGACTION
9855         if (debug_options.collect_pagefault_stats) {
9856                 if (mono_raw_buffer_is_pagefault (info->si_addr)) {
9857                         mono_raw_buffer_handle_pagefault (info->si_addr);
9858                         return;
9859                 }
9860                 if (mono_aot_is_pagefault (info->si_addr)) {
9861                         mono_aot_handle_pagefault (info->si_addr);
9862                         return;
9863                 }
9864         }
9865 #endif
9866
9867 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
9868         /* Can't allocate memory using Boehm GC on altstack */
9869         if (jit_tls->stack_size && 
9870                 ((guint8*)info->si_addr >= (guint8*)jit_tls->end_of_stack - jit_tls->stack_size) &&
9871                 ((guint8*)info->si_addr < (guint8*)jit_tls->end_of_stack))
9872                 exc = mono_domain_get ()->stack_overflow_ex;
9873         else
9874                 exc = mono_domain_get ()->null_reference_ex;
9875 #endif
9876
9877         if (debug_options.abort_on_sigsegv) {
9878                 MonoJitInfo *ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
9879                 if (!ji) {
9880                         fprintf (stderr, "Got SIGSEGV while in unmanaged code, and the 'abort-on-sigsegv' MONO_DEBUG option is set. Aborting...\n");
9881                         /* Segfault in unmanaged code */
9882                         abort ();
9883                 }
9884         }
9885                         
9886         mono_arch_handle_exception (ctx, exc, FALSE);
9887 }
9888
9889 static void
9890 SIG_HANDLER_SIGNATURE (sigusr1_signal_handler)
9891 {
9892         gboolean running_managed;
9893         MonoException *exc;
9894         void *ji;
9895         
9896         GET_CONTEXT;
9897
9898         /*
9899          * FIXME:
9900          * This is an async signal, so the code below must not call anything which
9901          * is not async safe. That includes the pthread locking functions. If we
9902          * know that we interrupted managed code, then locking is safe.
9903          */
9904         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
9905         running_managed = ji != NULL;
9906         
9907         exc = mono_thread_request_interruption (running_managed); 
9908         if (!exc) return;
9909
9910         mono_arch_handle_exception (ctx, exc, FALSE);
9911 }
9912
9913 static void
9914 SIG_HANDLER_SIGNATURE (sigprof_signal_handler)
9915 {
9916         GET_CONTEXT;
9917
9918         mono_profiler_stat_hit (mono_arch_ip_from_context (ctx), ctx);
9919 }
9920
9921 static void
9922 SIG_HANDLER_SIGNATURE (sigquit_signal_handler)
9923 {
9924        MonoException *exc;
9925        GET_CONTEXT
9926
9927        exc = mono_get_exception_execution_engine ("Interrupted (SIGQUIT).");
9928        
9929        mono_arch_handle_exception (ctx, exc, FALSE);
9930 }
9931
9932 static void
9933 SIG_HANDLER_SIGNATURE (sigint_signal_handler)
9934 {
9935         MonoException *exc;
9936         GET_CONTEXT
9937
9938         exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
9939         
9940         mono_arch_handle_exception (ctx, exc, FALSE);
9941 }
9942
9943 static void
9944 SIG_HANDLER_SIGNATURE (sigusr2_signal_handler)
9945 {
9946         gboolean enabled = mono_trace_is_enabled ();
9947
9948         mono_trace_enable (!enabled);
9949 }
9950
9951 #ifndef PLATFORM_WIN32
9952 static void
9953 add_signal_handler (int signo, gpointer handler)
9954 {
9955         struct sigaction sa;
9956
9957 #ifdef MONO_ARCH_USE_SIGACTION
9958         sa.sa_sigaction = handler;
9959         sigemptyset (&sa.sa_mask);
9960         sa.sa_flags = SA_SIGINFO;
9961 #else
9962         sa.sa_handler = handler;
9963         sigemptyset (&sa.sa_mask);
9964         sa.sa_flags = 0;
9965 #endif
9966         g_assert (sigaction (signo, &sa, NULL) != -1);
9967 }
9968 #endif
9969
9970 static void
9971 mono_runtime_install_handlers (void)
9972 {
9973 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
9974         struct sigaction sa;
9975 #endif
9976
9977 #ifdef PLATFORM_WIN32
9978         win32_seh_init();
9979         win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
9980         win32_seh_set_handler(SIGILL, sigill_signal_handler);
9981         win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
9982         if (debug_options.handle_sigint)
9983                 win32_seh_set_handler(SIGINT, sigint_signal_handler);
9984
9985 #else /* !PLATFORM_WIN32 */
9986
9987         /* libpthreads has its own implementation of sigaction(),
9988          * but it seems to work well with our current exception
9989          * handlers. If not we must call syscall directly instead 
9990          * of sigaction */
9991
9992         if (debug_options.handle_sigint)
9993                 add_signal_handler (SIGINT, sigint_signal_handler);
9994
9995         add_signal_handler (SIGFPE, sigfpe_signal_handler);
9996         add_signal_handler (SIGQUIT, sigquit_signal_handler);
9997         add_signal_handler (SIGILL, sigill_signal_handler);
9998         add_signal_handler (SIGBUS, sigsegv_signal_handler);
9999         if (mono_jit_trace_calls != NULL)
10000                 add_signal_handler (SIGUSR2, sigusr2_signal_handler);
10001
10002         add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
10003         signal (SIGPIPE, SIG_IGN);
10004
10005         /* catch SIGSEGV */
10006 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
10007         sa.sa_sigaction = sigsegv_signal_handler;
10008         sigemptyset (&sa.sa_mask);
10009         sa.sa_flags = SA_SIGINFO | SA_ONSTACK;
10010         g_assert (sigaction (SIGSEGV, &sa, NULL) != -1);
10011 #else
10012         add_signal_handler (SIGSEGV, sigsegv_signal_handler);
10013 #endif
10014
10015 #endif /* PLATFORM_WIN32 */
10016 }
10017
10018
10019 #ifdef HAVE_LINUX_RTC_H
10020 #include <linux/rtc.h>
10021 #include <sys/ioctl.h>
10022 #include <fcntl.h>
10023 static int rtc_fd = -1;
10024
10025 static int
10026 enable_rtc_timer (gboolean enable)
10027 {
10028         int flags;
10029         flags = fcntl (rtc_fd, F_GETFL);
10030         if (flags < 0) {
10031                 perror ("getflags");
10032                 return 0;
10033         }
10034         if (enable)
10035                 flags |= FASYNC;
10036         else
10037                 flags &= ~FASYNC;
10038         if (fcntl (rtc_fd, F_SETFL, flags) == -1) {
10039                 perror ("setflags");
10040                 return 0;
10041         }
10042         return 1;
10043 }
10044 #endif
10045
10046 static void
10047 setup_stat_profiler (void)
10048 {
10049 #ifdef ITIMER_PROF
10050         struct itimerval itval;
10051         static int inited = 0;
10052 #ifdef HAVE_LINUX_RTC_H
10053         const char *rtc_freq;
10054         if (!inited && (rtc_freq = g_getenv ("MONO_RTC"))) {
10055                 int freq = 0;
10056                 inited = 1;
10057                 if (*rtc_freq)
10058                         freq = atoi (rtc_freq);
10059                 if (!freq)
10060                         freq = 1024;
10061                 rtc_fd = open ("/dev/rtc", O_RDONLY);
10062                 if (rtc_fd == -1) {
10063                         perror ("open /dev/rtc");
10064                         return;
10065                 }
10066                 add_signal_handler (SIGPROF, sigprof_signal_handler);
10067                 if (ioctl (rtc_fd, RTC_IRQP_SET, freq) == -1) {
10068                         perror ("set rtc freq");
10069                         return;
10070                 }
10071                 if (ioctl (rtc_fd, RTC_PIE_ON, 0) == -1) {
10072                         perror ("start rtc");
10073                         return;
10074                 }
10075                 if (fcntl (rtc_fd, F_SETSIG, SIGPROF) == -1) {
10076                         perror ("setsig");
10077                         return;
10078                 }
10079                 if (fcntl (rtc_fd, F_SETOWN, getpid ()) == -1) {
10080                         perror ("setown");
10081                         return;
10082                 }
10083                 enable_rtc_timer (TRUE);
10084                 return;
10085         }
10086         if (rtc_fd >= 0)
10087                 return;
10088 #endif
10089
10090         itval.it_interval.tv_usec = 999;
10091         itval.it_interval.tv_sec = 0;
10092         itval.it_value = itval.it_interval;
10093         setitimer (ITIMER_PROF, &itval, NULL);
10094         if (inited)
10095                 return;
10096         inited = 1;
10097         add_signal_handler (SIGPROF, sigprof_signal_handler);
10098 #endif
10099 }
10100
10101 /* mono_jit_create_remoting_trampoline:
10102  * @method: pointer to the method info
10103  *
10104  * Creates a trampoline which calls the remoting functions. This
10105  * is used in the vtable of transparent proxies.
10106  * 
10107  * Returns: a pointer to the newly created code 
10108  */
10109 static gpointer
10110 mono_jit_create_remoting_trampoline (MonoMethod *method, MonoRemotingTarget target)
10111 {
10112         MonoMethod *nm;
10113         guint8 *addr = NULL;
10114
10115         if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || 
10116             (mono_method_signature (method)->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
10117                 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
10118                 addr = mono_compile_method (nm);
10119         } else {
10120                 addr = mono_compile_method (method);
10121         }
10122         return mono_get_addr_from_ftnptr (addr);
10123 }
10124
10125 static void
10126 mini_parse_debug_options (void)
10127 {
10128         char *options = getenv ("MONO_DEBUG");
10129         gchar **args, **ptr;
10130         
10131         if (!options)
10132                 return;
10133
10134         args = g_strsplit (options, ",", -1);
10135
10136         for (ptr = args; ptr && *ptr; ptr++) {
10137                 const char *arg = *ptr;
10138
10139                 if (!strcmp (arg, "handle-sigint"))
10140                         debug_options.handle_sigint = TRUE;
10141                 else if (!strcmp (arg, "keep-delegates"))
10142                         debug_options.keep_delegates = TRUE;
10143                 else if (!strcmp (arg, "abort-on-sigsegv"))
10144                         debug_options.abort_on_sigsegv = TRUE;
10145                 else if (!strcmp (arg, "collect-pagefault-stats"))
10146                         debug_options.collect_pagefault_stats = TRUE;
10147                 else {
10148                         fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
10149                         fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'abort-on-sigsegv', 'collect-pagefault-stats'\n");
10150                         exit (1);
10151                 }
10152         }
10153 }
10154
10155 MonoDomain *
10156 mini_init (const char *filename)
10157 {
10158         MonoDomain *domain;
10159
10160         /* Happens when using the embedding interface */
10161         if (default_opt == 0)
10162                 default_opt = mono_parse_default_optimizations (NULL);
10163
10164         InitializeCriticalSection (&jit_mutex);
10165
10166         global_codeman = mono_code_manager_new ();
10167         jit_icall_name_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
10168
10169         mono_arch_cpu_init ();
10170
10171         mono_init_trampolines ();
10172
10173         mono_init_exceptions ();
10174
10175         if (!g_thread_supported ())
10176                 g_thread_init (NULL);
10177
10178         if (getenv ("MONO_DEBUG") != NULL)
10179                 mini_parse_debug_options ();
10180
10181         if (mono_running_on_valgrind ()) {
10182                 gsize stack_bottom = (gsize)&domain;
10183                 stack_bottom += 4095;
10184                 stack_bottom &= ~4095;
10185                 GC_stackbottom = (char*)stack_bottom;
10186         }
10187         MONO_GC_PRE_INIT ();
10188
10189         mono_jit_tls_id = TlsAlloc ();
10190         setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
10191
10192         mono_burg_init ();
10193
10194         if (default_opt & MONO_OPT_AOT)
10195                 mono_aot_init ();
10196
10197         mono_runtime_install_handlers ();
10198         mono_threads_install_cleanup (mini_thread_cleanup);
10199
10200 #define JIT_TRAMPOLINES_WORK
10201 #ifdef JIT_TRAMPOLINES_WORK
10202         mono_install_compile_method (mono_jit_compile_method);
10203         mono_install_free_method (mono_jit_free_method);
10204         mono_install_trampoline (mono_create_jit_trampoline);
10205         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
10206         mono_install_delegate_trampoline (mono_create_delegate_trampoline);
10207 #endif
10208 #define JIT_INVOKE_WORKS
10209 #ifdef JIT_INVOKE_WORKS
10210         mono_install_runtime_invoke (mono_jit_runtime_invoke);
10211         mono_install_handler (mono_arch_get_throw_exception ());
10212 #endif
10213         mono_install_stack_walk (mono_jit_walk_stack);
10214         mono_install_init_vtable (mono_aot_init_vtable);
10215         mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
10216         mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
10217
10218         if (debug_options.collect_pagefault_stats) {
10219                 mono_raw_buffer_set_make_unreadable (TRUE);
10220                 mono_aot_set_make_unreadable (TRUE);
10221         }
10222
10223         domain = mono_init_from_assembly (filename, filename);
10224         mono_icall_init ();
10225
10226         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info", 
10227                                 ves_icall_get_frame_info);
10228         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace", 
10229                                 ves_icall_get_trace);
10230         mono_add_internal_call ("System.Exception::get_trace", 
10231                                 ves_icall_System_Exception_get_trace);
10232         mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityFrame",
10233                                 ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
10234         mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityStack",
10235                                 ves_icall_System_Security_SecurityFrame_GetSecurityStack);
10236         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers", 
10237                                 mono_runtime_install_handlers);
10238
10239
10240         create_helper_signature ();
10241
10242 #define JIT_CALLS_WORK
10243 #ifdef JIT_CALLS_WORK
10244         /* Needs to be called here since register_jit_icall depends on it */
10245         mono_marshal_init ();
10246
10247         mono_arch_register_lowlevel_calls ();
10248         register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
10249         register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
10250         register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
10251         register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
10252         register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
10253         register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "void", TRUE);
10254         register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
10255
10256         register_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
10257         register_icall (mono_arch_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
10258         register_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", "void ptr", TRUE); 
10259 #if MONO_ARCH_HAVE_THROW_CORLIB_EXCEPTION
10260         register_icall (mono_arch_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception", 
10261                                  "void ptr", TRUE);
10262 #endif
10263         register_icall (mono_thread_get_pending_exception, "mono_thread_get_pending_exception", "object", FALSE);
10264         register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "void", FALSE);
10265         register_icall (mono_thread_force_interruption_checkpoint, "mono_thread_force_interruption_checkpoint", "void", FALSE);
10266         register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
10267         register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
10268
10269         /* 
10270          * NOTE, NOTE, NOTE, NOTE:
10271          * when adding emulation for some opcodes, remember to also add a dummy
10272          * rule to the burg files, because we need the arity information to be correct.
10273          */
10274 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
10275         mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, TRUE);
10276         mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, FALSE);
10277         mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, FALSE);
10278         mono_register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, FALSE);
10279         mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, FALSE);
10280         mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, FALSE);
10281         mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, FALSE);
10282 #endif
10283
10284 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
10285         mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, TRUE);
10286         mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, TRUE);
10287         mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, TRUE);
10288 #endif
10289
10290 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
10291         mono_register_opcode_emulation (CEE_DIV, "__emul_idiv", "int32 int32 int32", mono_idiv, TRUE);
10292         mono_register_opcode_emulation (CEE_DIV_UN, "__emul_idiv_un", "int32 int32 int32", mono_idiv_un, TRUE);
10293         mono_register_opcode_emulation (CEE_REM, "__emul_irem", "int32 int32 int32", mono_irem, TRUE);
10294         mono_register_opcode_emulation (CEE_REM_UN, "__emul_irem_un", "int32 int32 int32", mono_irem_un, TRUE);
10295 #endif
10296
10297 #ifdef MONO_ARCH_EMULATE_MUL_DIV
10298         mono_register_opcode_emulation (CEE_MUL_OVF, "__emul_imul_ovf", "int32 int32 int32", mono_imul_ovf, TRUE);
10299         mono_register_opcode_emulation (CEE_MUL_OVF_UN, "__emul_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, TRUE);
10300         mono_register_opcode_emulation (CEE_MUL, "__emul_imul", "int32 int32 int32", mono_imul, TRUE);
10301         mono_register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, TRUE);
10302 #endif
10303
10304         mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, FALSE);
10305         mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, FALSE);
10306         mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, FALSE);
10307         mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, FALSE);
10308
10309 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
10310         mono_register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, FALSE);
10311 #endif
10312 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
10313         mono_register_opcode_emulation (CEE_CONV_R_UN, "__emul_conv_r_un", "double int32", mono_conv_to_r8_un, FALSE);
10314 #endif
10315 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
10316         mono_register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, FALSE);
10317 #endif
10318 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
10319         mono_register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, FALSE);
10320 #endif
10321 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
10322         mono_register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", "double long", mono_lconv_to_r8_un, FALSE);
10323 #endif
10324 #ifdef MONO_ARCH_EMULATE_FREM
10325         mono_register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, FALSE);
10326 #endif
10327
10328 #if SIZEOF_VOID_P == 4
10329         mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, TRUE);
10330 #endif
10331
10332         /* other jit icalls */
10333         register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
10334         register_icall (mono_class_static_field_address , "mono_class_static_field_address", 
10335                                  "ptr ptr ptr", FALSE);
10336         register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
10337         register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
10338         register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
10339         register_icall (helper_stelem_ref, "helper_stelem_ref", "void ptr int32 object", FALSE);
10340         register_icall (helper_stelem_ref_check, "helper_stelem_ref_check", "void object object", FALSE);
10341         register_icall (mono_object_new, "mono_object_new", "object ptr ptr", FALSE);
10342         register_icall (mono_object_new_specific, "mono_object_new_specific", "object ptr", FALSE);
10343         register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
10344         register_icall (mono_array_new_specific, "mono_array_new_specific", "object ptr int32", FALSE);
10345         register_icall (mono_runtime_class_init, "mono_runtime_class_init", "void ptr", FALSE);
10346         register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
10347         register_icall (mono_ldftn_nosync, "mono_ldftn_nosync", "ptr ptr", FALSE);
10348         register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
10349         register_icall (helper_compile_generic_method, "compile_generic_method", "ptr object ptr ptr", FALSE);
10350         register_icall (helper_ldstr, "helper_ldstr", "object ptr int", FALSE);
10351 #endif
10352
10353 #define JIT_RUNTIME_WORKS
10354 #ifdef JIT_RUNTIME_WORKS
10355         mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
10356         mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
10357 #endif
10358
10359         mono_thread_attach (domain);
10360         return domain;
10361 }
10362
10363 MonoJitStats mono_jit_stats = {0};
10364
10365 static void 
10366 print_jit_stats (void)
10367 {
10368         if (mono_jit_stats.enabled) {
10369                 g_print ("Mono Jit statistics\n");
10370                 g_print ("Compiled methods:       %ld\n", mono_jit_stats.methods_compiled);
10371                 g_print ("Methods from AOT:       %ld\n", mono_jit_stats.methods_aot);
10372                 g_print ("Methods cache lookup:   %ld\n", mono_jit_stats.methods_lookups);
10373                 g_print ("Method trampolines:     %ld\n", mono_jit_stats.method_trampolines);
10374                 g_print ("Basic blocks:           %ld\n", mono_jit_stats.basic_blocks);
10375                 g_print ("Max basic blocks:       %ld\n", mono_jit_stats.max_basic_blocks);
10376                 g_print ("Allocated vars:         %ld\n", mono_jit_stats.allocate_var);
10377                 g_print ("Analyze stack repeat:   %ld\n", mono_jit_stats.analyze_stack_repeat);
10378                 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
10379                 g_print ("Native code size:       %ld\n", mono_jit_stats.native_code_size);
10380                 g_print ("Max code size ratio:    %.2f (%s::%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
10381                                 mono_jit_stats.max_ratio_method->klass->name, mono_jit_stats.max_ratio_method->name);
10382                 g_print ("Biggest method:         %ld (%s::%s)\n", mono_jit_stats.biggest_method_size,
10383                                 mono_jit_stats.biggest_method->klass->name, mono_jit_stats.biggest_method->name);
10384                 g_print ("Code reallocs:          %ld\n", mono_jit_stats.code_reallocs);
10385                 g_print ("Allocated code size:    %ld\n", mono_jit_stats.allocated_code_size);
10386                 g_print ("Inlineable methods:     %ld\n", mono_jit_stats.inlineable_methods);
10387                 g_print ("Inlined methods:        %ld\n", mono_jit_stats.inlined_methods);
10388                 
10389                 g_print ("\nCreated object count:   %ld\n", mono_stats.new_object_count);
10390                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
10391                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
10392                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
10393                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
10394
10395                 g_print ("\nGeneric instances:      %ld\n", mono_stats.generic_instance_count);
10396                 g_print ("Initialized classes:    %ld\n", mono_stats.generic_class_count);
10397                 g_print ("Inflated methods:       %ld / %ld\n", mono_stats.inflated_method_count_2,
10398                          mono_stats.inflated_method_count);
10399                 g_print ("Inflated types:         %ld\n", mono_stats.inflated_type_count);
10400                 g_print ("Generics metadata size: %ld\n", mono_stats.generics_metadata_size);
10401
10402                 if (mono_use_security_manager) {
10403                         g_print ("\nDecl security check   : %ld\n", mono_jit_stats.cas_declsec_check);
10404                         g_print ("LinkDemand (user)     : %ld\n", mono_jit_stats.cas_linkdemand);
10405                         g_print ("LinkDemand (icall)    : %ld\n", mono_jit_stats.cas_linkdemand_icall);
10406                         g_print ("LinkDemand (pinvoke)  : %ld\n", mono_jit_stats.cas_linkdemand_pinvoke);
10407                         g_print ("LinkDemand (aptc)     : %ld\n", mono_jit_stats.cas_linkdemand_aptc);
10408                         g_print ("Demand (code gen)     : %ld\n", mono_jit_stats.cas_demand_generation);
10409                 }
10410                 if (debug_options.collect_pagefault_stats) {
10411                         g_print ("Metadata pagefaults   : %d\n", mono_raw_buffer_get_n_pagefaults ());
10412                         g_print ("AOT pagefaults        : %d\n", mono_aot_get_n_pagefaults ());
10413                 }
10414         }
10415 }
10416
10417 void
10418 mini_cleanup (MonoDomain *domain)
10419 {
10420 #ifdef HAVE_LINUX_RTC_H
10421         if (rtc_fd >= 0)
10422                 enable_rtc_timer (FALSE);
10423 #endif
10424
10425         /* 
10426          * mono_runtime_cleanup() and mono_domain_finalize () need to
10427          * be called early since they need the execution engine still
10428          * fully working (mono_domain_finalize may invoke managed finalizers
10429          * and mono_runtime_cleanup will wait for other threads to finish).
10430          */
10431         mono_domain_finalize (domain, 2000);
10432
10433         mono_runtime_cleanup (domain);
10434
10435         mono_profiler_shutdown ();
10436
10437         mono_debug_cleanup ();
10438
10439         mono_icall_cleanup ();
10440
10441 #ifdef PLATFORM_WIN32
10442         win32_seh_cleanup();
10443 #endif
10444
10445         mono_domain_free (domain, TRUE);
10446
10447         mono_code_manager_destroy (global_codeman);
10448         g_hash_table_destroy (jit_icall_name_hash);
10449         if (class_init_hash_addr)
10450                 g_hash_table_destroy (class_init_hash_addr);
10451
10452         print_jit_stats ();
10453 }
10454
10455 void
10456 mono_set_defaults (int verbose_level, guint32 opts)
10457 {
10458         mini_verbose = verbose_level;
10459         default_opt = opts;
10460 }
10461
10462 static void
10463 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
10464 {
10465         GHashTable *assemblies = (GHashTable*)user_data;
10466         MonoImage *image = mono_assembly_get_image (ass);
10467         MonoMethod *method, *invoke;
10468         int i, count = 0;
10469
10470         if (g_hash_table_lookup (assemblies, ass))
10471                 return;
10472
10473         g_hash_table_insert (assemblies, ass, ass);
10474
10475         if (mini_verbose > 0)
10476                 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
10477
10478         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
10479                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
10480                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
10481                         continue;
10482
10483                 count++;
10484                 if (mini_verbose > 1) {
10485                         char * desc = mono_method_full_name (method, TRUE);
10486                         g_print ("Compiling %d %s\n", count, desc);
10487                         g_free (desc);
10488                 }
10489                 mono_compile_method (method);
10490                 if (strcmp (method->name, "Finalize") == 0) {
10491                         invoke = mono_marshal_get_runtime_invoke (method);
10492                         mono_compile_method (invoke);
10493                 }
10494                 if (method->klass->marshalbyref && mono_method_signature (method)->hasthis) {
10495                         invoke = mono_marshal_get_remoting_invoke_with_check (method);
10496                         mono_compile_method (invoke);
10497                 }
10498         }
10499
10500         /* Load and precompile referenced assemblies as well */
10501         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
10502                 mono_assembly_load_reference (image, i);
10503                 if (image->references [i])
10504                         mono_precompile_assembly (image->references [i], assemblies);
10505         }
10506 }
10507
10508 void mono_precompile_assemblies ()
10509 {
10510         GHashTable *assemblies = g_hash_table_new (NULL, NULL);
10511
10512         mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
10513
10514         g_hash_table_destroy (assemblies);
10515 }