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