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