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