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