2004-11-26 Martin Baulig <martin@ximian.com>
[mono.git] / mono / mini / mini.c
1 /*
2  * mini.c: The new Mono code generator.
3  *
4  * Author:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * (C) 2002 Ximian, Inc.
9  */
10
11 #include <config.h>
12 #include <signal.h>
13 #include <unistd.h>
14 #include <math.h>
15
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                                 MONO_ADD_INS (bblock, store);
3268                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
3269                                 *sp++ = ins;
3270                                 ins->cil_code = ip;
3271                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
3272                                 *sp++ = ins;
3273                                 ins->cil_code = ip;
3274                         }
3275                         ++ip;
3276                         inline_costs += 2;
3277                         break;
3278                 }
3279                 case CEE_POP:
3280                         CHECK_STACK (1);
3281                         MONO_INST_NEW (cfg, ins, CEE_POP);
3282                         MONO_ADD_INS (bblock, ins);
3283                         ins->cil_code = ip++;
3284                         --sp;
3285                         ins->inst_i0 = *sp;
3286                         break;
3287                 case CEE_JMP:
3288                         CHECK_OPSIZE (5);
3289                         if (stack_start != sp)
3290                                 goto unverified;
3291                         MONO_INST_NEW (cfg, ins, CEE_JMP);
3292                         token = read32 (ip + 1);
3293                         /* FIXME: check the signature matches */
3294                         cmethod = mono_get_method_full (image, token, NULL, generic_context);
3295                         ins->inst_p0 = cmethod;
3296                         MONO_ADD_INS (bblock, ins);
3297                         ip += 5;
3298                         start_new_bblock = 1;
3299                         break;
3300                 case CEE_CALLI:
3301                 case CEE_CALL:
3302                 case CEE_CALLVIRT: {
3303                         MonoInst *addr = NULL;
3304                         MonoMethodSignature *fsig = NULL;
3305                         int temp, array_rank = 0;
3306                         int virtual = *ip == CEE_CALLVIRT;
3307
3308                         CHECK_OPSIZE (5);
3309                         token = read32 (ip + 1);
3310
3311                         if (*ip == CEE_CALLI) {
3312                                 cmethod = NULL;
3313                                 CHECK_STACK (1);
3314                                 --sp;
3315                                 addr = *sp;
3316                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
3317                                         fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
3318                                 else
3319                                         fsig = mono_metadata_parse_signature (image, token);
3320
3321                                 n = fsig->param_count + fsig->hasthis;
3322                         } else {
3323                                 if (method->wrapper_type != MONO_WRAPPER_NONE) {
3324                                         cmethod =  (MonoMethod *)mono_method_get_wrapper_data (method, token);
3325                                 } else if (constrained_call) {
3326                                         cmethod = mono_get_method_constrained (image, token, constrained_call, generic_context);
3327                                 } else {
3328                                         cmethod = mono_get_method_full (image, token, NULL, generic_context);
3329                                 }
3330
3331                                 g_assert (cmethod);
3332
3333                                 if (!cmethod->klass->inited)
3334                                         mono_class_init (cmethod->klass);
3335
3336                                 if (cmethod->signature->pinvoke) {
3337                                                 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod);
3338                                                 fsig = wrapper->signature;
3339                                 } else {
3340                                         fsig = mono_method_get_signature (cmethod, image, token);
3341                                 }
3342
3343                                 n = fsig->param_count + fsig->hasthis;
3344
3345                                 if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
3346                                     cmethod->klass->parent == mono_defaults.array_class) {
3347                                         array_rank = cmethod->klass->rank;
3348                                 }
3349
3350                                 if (cmethod->string_ctor)
3351                                         g_assert_not_reached ();
3352
3353                         }
3354
3355                         if (cmethod && cmethod->klass->generic_container)
3356                                 goto unverified;
3357
3358                         CHECK_STACK (n);
3359
3360                         //g_assert (!virtual || fsig->hasthis);
3361
3362                         sp -= n;
3363
3364                         if (constrained_call) {
3365                                 /*
3366                                  * We have the `constrained.' prefix opcode.
3367                                  */
3368                                 if (constrained_call->valuetype && !cmethod->klass->valuetype) {
3369                                         MonoInst *load;
3370                                         /*
3371                                          * The type parameter is instantiated as a valuetype,
3372                                          * but that type doesn't override the method we're
3373                                          * calling, so we need to box `this'.
3374                                          * sp [0] is a pointer to the data: we need the value
3375                                          * in handle_box (), so load it here.
3376                                          */
3377                                         MONO_INST_NEW (cfg, load, mono_type_to_ldind (&constrained_call->byval_arg));
3378                                         type_to_eval_stack_type (&constrained_call->byval_arg, load);
3379                                         load->cil_code = ip;
3380                                         load->inst_left = sp [0];
3381                                         sp [0] = handle_box (cfg, bblock, load, ip, constrained_call);
3382                                 } else if (!constrained_call->valuetype) {
3383                                         MonoInst *ins;
3384
3385                                         /*
3386                                          * The type parameter is instantiated as a reference
3387                                          * type.  We have a managed pointer on the stack, so
3388                                          * we need to dereference it here.
3389                                          */
3390
3391                                         MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
3392                                         ins->cil_code = ip;
3393                                         ins->inst_i0 = sp [0];
3394                                         ins->type = STACK_OBJ;
3395                                         sp [0] = ins;
3396                                 } else if (cmethod->klass->valuetype)
3397                                         virtual = 0;
3398                                 constrained_call = NULL;
3399                         }
3400
3401                         if (*ip != CEE_CALLI && check_call_signature (cfg, fsig, sp))
3402                                 goto unverified;
3403
3404                         if ((ins_flag & MONO_INST_TAILCALL) && cmethod && (*ip == CEE_CALL) && (mono_metadata_signature_equal (method->signature, cmethod->signature))) {
3405                                 int i;
3406                                 /* FIXME: This assumes the two methods has the same number and type of arguments */
3407                                 for (i = 0; i < n; ++i) {
3408                                         /* Check if argument is the same */
3409                                         NEW_ARGLOAD (cfg, ins, i);
3410                                         if ((ins->opcode == sp [i]->opcode) && (ins->inst_i0 == sp [i]->inst_i0))
3411                                                 continue;
3412
3413                                         /* Prevent argument from being register allocated */
3414                                         arg_array [i]->flags |= MONO_INST_VOLATILE;
3415                                         NEW_ARGSTORE (cfg, ins, i, sp [i]);
3416                                         ins->cil_code = ip;
3417                                         if (ins->opcode == CEE_STOBJ) {
3418                                                 NEW_ARGLOADA (cfg, ins, i);
3419                                                 handle_stobj (cfg, bblock, ins, sp [i], sp [i]->cil_code, ins->klass, FALSE, FALSE);
3420                                         }
3421                                         else
3422                                                 MONO_ADD_INS (bblock, ins);
3423                                 }
3424                                 MONO_INST_NEW (cfg, ins, CEE_JMP);
3425                                 ins->cil_code = ip;
3426                                 ins->inst_p0 = cmethod;
3427                                 ins->inst_p1 = arg_array [0];
3428                                 MONO_ADD_INS (bblock, ins);
3429                                 start_new_bblock = 1;
3430                                 /* skip CEE_RET as well */
3431                                 ip += 6;
3432                                 ins_flag = 0;
3433                                 break;
3434                         }
3435                         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_get_opcode_for_method (cfg, cmethod, fsig, sp))) {
3436                                 ins->cil_code = ip;
3437
3438                                 if (MONO_TYPE_IS_VOID (fsig->ret)) {
3439                                         MONO_ADD_INS (bblock, ins);
3440                                 } else {
3441                                         type_to_eval_stack_type (fsig->ret, ins);
3442                                         *sp = ins;
3443                                         sp++;
3444                                 }
3445
3446                                 ip += 5;
3447                                 break;
3448                         }
3449
3450                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3451
3452                         if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
3453                             (!virtual || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || (cmethod->flags & METHOD_ATTRIBUTE_FINAL)) && 
3454                             mono_method_check_inlining (cfg, cmethod) &&
3455                                  !g_list_find (dont_inline, cmethod)) {
3456                                 int costs;
3457                                 MonoBasicBlock *ebblock;
3458                                 gboolean allways = FALSE;
3459
3460                                 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3461                                         (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
3462                                         cmethod = mono_marshal_get_native_wrapper (cmethod);
3463                                         allways = TRUE;
3464                                 }
3465
3466                                 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, allways))) {
3467                                         ip += 5;
3468                                         real_offset += 5;
3469
3470                                         GET_BBLOCK (cfg, bbhash, bblock, ip);
3471                                         ebblock->next_bb = bblock;
3472                                         link_bblock (cfg, ebblock, bblock);
3473
3474                                         if (!MONO_TYPE_IS_VOID (fsig->ret))
3475                                                 sp++;
3476
3477                                         /* indicates start of a new block, and triggers a load of all 
3478                                            stack arguments at bb boundarie */
3479                                         bblock = ebblock;
3480
3481                                         inline_costs += costs;
3482                                         break;
3483                                 }
3484                         }
3485                         
3486                         inline_costs += 10 * num_calls++;
3487
3488                         /* tail recursion elimination */
3489                         if ((cfg->opt & MONO_OPT_TAILC) && *ip == CEE_CALL && cmethod == method && ip [5] == CEE_RET) {
3490                                 gboolean has_vtargs = FALSE;
3491                                 int i;
3492                                 
3493                                 /* keep it simple */
3494                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
3495                                         if (MONO_TYPE_ISSTRUCT (cmethod->signature->params [i])) 
3496                                                 has_vtargs = TRUE;
3497                                 }
3498
3499                                 if (!has_vtargs) {
3500                                         for (i = 0; i < n; ++i) {
3501                                                 NEW_ARGSTORE (cfg, ins, i, sp [i]);
3502                                                 ins->cil_code = ip;
3503                                                 MONO_ADD_INS (bblock, ins);
3504                                         }
3505                                         MONO_INST_NEW (cfg, ins, CEE_BR);
3506                                         ins->cil_code = ip;
3507                                         MONO_ADD_INS (bblock, ins);
3508                                         tblock = start_bblock->out_bb [0];
3509                                         link_bblock (cfg, bblock, tblock);
3510                                         ins->inst_target_bb = tblock;
3511                                         start_new_bblock = 1;
3512                                         ip += 5;
3513                                         
3514                                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
3515                                                 /* just create a dummy - the value is never used */
3516                                                 ins = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
3517                                                 NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
3518                                                 sp++;
3519                                         }
3520
3521                                         break;
3522                                 }
3523                         }
3524
3525                         if (*ip == CEE_CALLI) {
3526
3527                                 if ((temp = mono_emit_calli (cfg, bblock, fsig, sp, addr, ip)) != -1) {
3528                                         NEW_TEMPLOAD (cfg, *sp, temp);
3529                                         sp++;
3530                                 }
3531                                         
3532                         } else if (array_rank) {
3533                                 MonoInst *addr;
3534
3535                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
3536                                         if (sp [fsig->param_count]->type == STACK_OBJ) {
3537                                                 MonoInst *iargs [2];
3538                                                 MonoInst *array, *to_store, *store;
3539
3540                                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
3541                                                 
3542                                                 array = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
3543                                                 NEW_TEMPSTORE (cfg, store, array->inst_c0, sp [0]);
3544                                                 store->cil_code = ip;
3545                                                 MONO_ADD_INS (bblock, store);
3546                                                 NEW_TEMPLOAD (cfg, iargs [0], array->inst_c0);
3547
3548                                                 to_store = mono_compile_create_var (cfg, type_from_stack_type (sp [fsig->param_count]), OP_LOCAL);
3549                                                 NEW_TEMPSTORE (cfg, store, to_store->inst_c0, sp [fsig->param_count]);
3550                                                 store->cil_code = ip;
3551                                                 MONO_ADD_INS (bblock, store);
3552                                                 NEW_TEMPLOAD (cfg, iargs [1], to_store->inst_c0);
3553
3554                                                 /*
3555                                                  * We first save the args for the call so that the args are copied to the stack
3556                                                  * and a new instruction tree for them is created. If we don't do this,
3557                                                  * the same MonoInst is added to two different trees and this is not 
3558                                                  * allowed by burg.
3559                                                  */
3560                                                 mono_emit_jit_icall (cfg, bblock, helper_stelem_ref_check, iargs, ip);
3561
3562                                                 NEW_TEMPLOAD (cfg, sp [0], array->inst_c0);
3563                                                 NEW_TEMPLOAD (cfg, sp [fsig->param_count], to_store->inst_c0);
3564                                         }
3565
3566                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, TRUE);
3567                                         NEW_INDSTORE (cfg, ins, addr, sp [fsig->param_count], fsig->params [fsig->param_count - 1]);
3568                                         ins->cil_code = ip;
3569                                         if (ins->opcode == CEE_STOBJ) {
3570                                                 handle_stobj (cfg, bblock, addr, sp [fsig->param_count], ip, mono_class_from_mono_type (fsig->params [fsig->param_count-1]), FALSE, FALSE);
3571                                         } else {
3572                                                 MONO_ADD_INS (bblock, ins);
3573                                         }
3574
3575                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
3576                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
3577                                         NEW_INDLOAD (cfg, ins, addr, fsig->ret);
3578                                         ins->cil_code = ip;
3579
3580                                         *sp++ = ins;
3581                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
3582                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
3583                                         *sp++ = addr;
3584                                 } else {
3585                                         g_assert_not_reached ();
3586                                 }
3587
3588                         } else {
3589                                 if (0 && CODE_IS_STLOC (ip + 5) && (!MONO_TYPE_ISSTRUCT (fsig->ret)) && (!MONO_TYPE_IS_VOID (fsig->ret) || cmethod->string_ctor)) {
3590                                         /* no need to spill */
3591                                         ins = (MonoInst*)mono_emit_method_call (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL);
3592                                         *sp++ = ins;
3593                                 } else {
3594                                         if ((temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL)) != -1) {
3595                                                 NEW_TEMPLOAD (cfg, *sp, temp);
3596                                                 sp++;
3597                                         }
3598                                 }
3599                         }
3600
3601                         ip += 5;
3602                         break;
3603                 }
3604                 case CEE_RET:
3605                         if (cfg->method != method) {
3606                                 /* return from inlined methode */
3607                                 if (return_var) {
3608                                         MonoInst *store;
3609                                         CHECK_STACK (1);
3610                                         --sp;
3611                                         //g_assert (returnvar != -1);
3612                                         NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
3613                                         store->cil_code = sp [0]->cil_code;
3614                                         if (store->opcode == CEE_STOBJ) {
3615                                                 g_assert_not_reached ();
3616                                                 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
3617                                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, return_var->klass, FALSE, FALSE);
3618                                         } else
3619                                                 MONO_ADD_INS (bblock, store);
3620                                 } 
3621                         } else {
3622                                 if (cfg->ret) {
3623                                         g_assert (!return_var);
3624                                         CHECK_STACK (1);
3625                                         --sp;
3626                                         MONO_INST_NEW (cfg, ins, CEE_NOP);
3627                                         ins->opcode = mono_type_to_stind (method->signature->ret);
3628                                         if (ins->opcode == CEE_STOBJ) {
3629                                                 NEW_RETLOADA (cfg, ins);
3630                                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
3631                                         } else {
3632                                                 ins->opcode = OP_SETRET;
3633                                                 ins->cil_code = ip;
3634                                                 ins->inst_i0 = *sp;;
3635                                                 ins->inst_i1 = NULL;
3636                                                 MONO_ADD_INS (bblock, ins);
3637                                         }
3638                                 }
3639                         }
3640                         if (sp != stack_start)
3641                                 goto unverified;
3642                         MONO_INST_NEW (cfg, ins, CEE_BR);
3643                         ins->cil_code = ip++;
3644                         ins->inst_target_bb = end_bblock;
3645                         MONO_ADD_INS (bblock, ins);
3646                         link_bblock (cfg, bblock, end_bblock);
3647                         start_new_bblock = 1;
3648                         break;
3649                 case CEE_BR_S:
3650                         CHECK_OPSIZE (2);
3651                         MONO_INST_NEW (cfg, ins, CEE_BR);
3652                         ins->cil_code = ip++;
3653                         MONO_ADD_INS (bblock, ins);
3654                         target = ip + 1 + (signed char)(*ip);
3655                         ++ip;
3656                         GET_BBLOCK (cfg, bbhash, tblock, target);
3657                         link_bblock (cfg, bblock, tblock);
3658                         CHECK_BBLOCK (target, ip, tblock);
3659                         ins->inst_target_bb = tblock;
3660                         if (sp != stack_start) {
3661                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3662                                 sp = stack_start;
3663                         }
3664                         start_new_bblock = 1;
3665                         inline_costs += 10;
3666                         break;
3667                 case CEE_BRFALSE_S:
3668                 case CEE_BRTRUE_S:
3669                         CHECK_OPSIZE (2);
3670                         CHECK_STACK (1);
3671                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
3672                         ins->cil_code = ip++;
3673                         target = ip + 1 + *(signed char*)ip;
3674                         ip++;
3675                         ADD_UNCOND (ins->opcode == CEE_BRTRUE);
3676                         if (sp != stack_start) {
3677                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3678                                 sp = stack_start;
3679                         }
3680                         inline_costs += 10;
3681                         break;
3682                 case CEE_BEQ_S:
3683                 case CEE_BGE_S:
3684                 case CEE_BGT_S:
3685                 case CEE_BLE_S:
3686                 case CEE_BLT_S:
3687                 case CEE_BNE_UN_S:
3688                 case CEE_BGE_UN_S:
3689                 case CEE_BGT_UN_S:
3690                 case CEE_BLE_UN_S:
3691                 case CEE_BLT_UN_S:
3692                         CHECK_OPSIZE (2);
3693                         CHECK_STACK (2);
3694                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
3695                         ins->cil_code = ip++;
3696                         target = ip + 1 + *(signed char*)ip;
3697                         ip++;
3698                         ADD_BINCOND (NULL);
3699                         if (sp != stack_start) {
3700                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3701                                 sp = stack_start;
3702                         }
3703                         inline_costs += 10;
3704                         break;
3705                 case CEE_BR:
3706                         CHECK_OPSIZE (5);
3707                         MONO_INST_NEW (cfg, ins, CEE_BR);
3708                         ins->cil_code = ip++;
3709                         MONO_ADD_INS (bblock, ins);
3710                         target = ip + 4 + (gint32)read32(ip);
3711                         ip += 4;
3712                         GET_BBLOCK (cfg, bbhash, tblock, target);
3713                         link_bblock (cfg, bblock, tblock);
3714                         CHECK_BBLOCK (target, ip, tblock);
3715                         ins->inst_target_bb = tblock;
3716                         if (sp != stack_start) {
3717                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3718                                 sp = stack_start;
3719                         }
3720                         start_new_bblock = 1;
3721                         inline_costs += 10;
3722                         break;
3723                 case CEE_BRFALSE:
3724                 case CEE_BRTRUE:
3725                         CHECK_OPSIZE (5);
3726                         CHECK_STACK (1);
3727                         MONO_INST_NEW (cfg, ins, *ip);
3728                         ins->cil_code = ip++;
3729                         target = ip + 4 + (gint32)read32(ip);
3730                         ip += 4;
3731                         ADD_UNCOND(ins->opcode == CEE_BRTRUE);
3732                         if (sp != stack_start) {
3733                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3734                                 sp = stack_start;
3735                         }
3736                         inline_costs += 10;
3737                         break;
3738                 case CEE_BEQ:
3739                 case CEE_BGE:
3740                 case CEE_BGT:
3741                 case CEE_BLE:
3742                 case CEE_BLT:
3743                 case CEE_BNE_UN:
3744                 case CEE_BGE_UN:
3745                 case CEE_BGT_UN:
3746                 case CEE_BLE_UN:
3747                 case CEE_BLT_UN:
3748                         CHECK_OPSIZE (5);
3749                         CHECK_STACK (2);
3750                         MONO_INST_NEW (cfg, ins, *ip);
3751                         ins->cil_code = ip++;
3752                         target = ip + 4 + (gint32)read32(ip);
3753                         ip += 4;
3754                         ADD_BINCOND(NULL);
3755                         if (sp != stack_start) {
3756                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3757                                 sp = stack_start;
3758                         }
3759                         inline_costs += 10;
3760                         break;
3761                 case CEE_SWITCH:
3762                         CHECK_OPSIZE (5);
3763                         CHECK_STACK (1);
3764                         n = read32 (ip + 1);
3765                         MONO_INST_NEW (cfg, ins, *ip);
3766                         --sp;
3767                         ins->inst_left = *sp;
3768                         if (ins->inst_left->type != STACK_I4) goto unverified;
3769                         ins->cil_code = ip;
3770                         ip += 5;
3771                         CHECK_OPSIZE (n * sizeof (guint32));
3772                         target = ip + n * sizeof (guint32);
3773                         MONO_ADD_INS (bblock, ins);
3774                         GET_BBLOCK (cfg, bbhash, tblock, target);
3775                         link_bblock (cfg, bblock, tblock);
3776                         ins->klass = GUINT_TO_POINTER (n);
3777                         ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (n + 1));
3778                         ins->inst_many_bb [n] = tblock;
3779
3780                         for (i = 0; i < n; ++i) {
3781                                 GET_BBLOCK (cfg, bbhash, tblock, target + (gint32)read32(ip));
3782                                 link_bblock (cfg, bblock, tblock);
3783                                 ins->inst_many_bb [i] = tblock;
3784                                 ip += 4;
3785                         }
3786                         if (sp != stack_start) {
3787                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3788                                 sp = stack_start;
3789                         }
3790                         inline_costs += 20;
3791                         break;
3792                 case CEE_LDIND_I1:
3793                 case CEE_LDIND_U1:
3794                 case CEE_LDIND_I2:
3795                 case CEE_LDIND_U2:
3796                 case CEE_LDIND_I4:
3797                 case CEE_LDIND_U4:
3798                 case CEE_LDIND_I8:
3799                 case CEE_LDIND_I:
3800                 case CEE_LDIND_R4:
3801                 case CEE_LDIND_R8:
3802                 case CEE_LDIND_REF:
3803                         CHECK_STACK (1);
3804                         MONO_INST_NEW (cfg, ins, *ip);
3805                         ins->cil_code = ip;
3806                         --sp;
3807                         ins->inst_i0 = *sp;
3808                         *sp++ = ins;
3809                         ins->type = ldind_type [*ip - CEE_LDIND_I1];
3810                         ins->flags |= ins_flag;
3811                         ins_flag = 0;
3812                         ++ip;
3813                         break;
3814                 case CEE_STIND_REF:
3815                 case CEE_STIND_I1:
3816                 case CEE_STIND_I2:
3817                 case CEE_STIND_I4:
3818                 case CEE_STIND_I8:
3819                 case CEE_STIND_R4:
3820                 case CEE_STIND_R8:
3821                         CHECK_STACK (2);
3822                         MONO_INST_NEW (cfg, ins, *ip);
3823                         ins->cil_code = ip++;
3824                         sp -= 2;
3825                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3826                         MONO_ADD_INS (bblock, ins);
3827                         ins->inst_i0 = sp [0];
3828                         ins->inst_i1 = sp [1];
3829                         ins->flags |= ins_flag;
3830                         ins_flag = 0;
3831                         inline_costs += 1;
3832                         break;
3833                 case CEE_ADD:
3834                 case CEE_SUB:
3835                 case CEE_MUL:
3836                 case CEE_DIV:
3837                 case CEE_DIV_UN:
3838                 case CEE_REM:
3839                 case CEE_REM_UN:
3840                 case CEE_AND:
3841                 case CEE_OR:
3842                 case CEE_XOR:
3843                 case CEE_SHL:
3844                 case CEE_SHR:
3845                 case CEE_SHR_UN:
3846                         CHECK_STACK (2);
3847                         ADD_BINOP (*ip);
3848                         /* special case that gives a nice speedup and happens to workaorund a ppc jit but (for the release)
3849                          * later apply the speedup to the left shift as well
3850                          * See BUG# 57957.
3851                          */
3852                         if ((ins->opcode == OP_LSHR_UN) && (ins->type == STACK_I8) 
3853                                         && (ins->inst_right->opcode == OP_ICONST) && (ins->inst_right->inst_c0 == 32)) {
3854                                 ins->opcode = OP_LONG_SHRUN_32;
3855                                 /*g_print ("applied long shr speedup to %s\n", cfg->method->name);*/
3856                                 ip++;
3857                                 break;
3858                         }
3859                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
3860                                 --sp;
3861                                 *sp++ = emit_tree (cfg, bblock, ins);
3862                         }
3863                         ip++;
3864                         break;
3865                 case CEE_NEG:
3866                 case CEE_NOT:
3867                 case CEE_CONV_I1:
3868                 case CEE_CONV_I2:
3869                 case CEE_CONV_I4:
3870                 case CEE_CONV_R4:
3871                 case CEE_CONV_R8:
3872                 case CEE_CONV_U4:
3873                 case CEE_CONV_I8:
3874                 case CEE_CONV_U8:
3875                 case CEE_CONV_OVF_I8:
3876                 case CEE_CONV_OVF_U8:
3877                 case CEE_CONV_R_UN:
3878                         CHECK_STACK (1);
3879                         ADD_UNOP (*ip);
3880                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
3881                                 --sp;
3882                                 *sp++ = emit_tree (cfg, bblock, ins);
3883                         }
3884                         ip++;                   
3885                         break;
3886                 case CEE_CONV_OVF_I4:
3887                 case CEE_CONV_OVF_I1:
3888                 case CEE_CONV_OVF_I2:
3889                 case CEE_CONV_OVF_I:
3890                 case CEE_CONV_OVF_U:
3891                         CHECK_STACK (1);
3892
3893                         if (sp [-1]->type == STACK_R8) {
3894                                 ADD_UNOP (CEE_CONV_OVF_I8);
3895                                 ADD_UNOP (*ip);
3896                         } else {
3897                                 ADD_UNOP (*ip);
3898                         }
3899
3900                         ip++;
3901                         break;
3902                 case CEE_CONV_OVF_U1:
3903                 case CEE_CONV_OVF_U2:
3904                 case CEE_CONV_OVF_U4:
3905                         CHECK_STACK (1);
3906
3907                         if (sp [-1]->type == STACK_R8) {
3908                                 ADD_UNOP (CEE_CONV_OVF_U8);
3909                                 ADD_UNOP (*ip);
3910                         } else {
3911                                 ADD_UNOP (*ip);
3912                         }
3913
3914                         ip++;
3915                         break;
3916                 case CEE_CONV_OVF_I1_UN:
3917                 case CEE_CONV_OVF_I2_UN:
3918                 case CEE_CONV_OVF_I4_UN:
3919                 case CEE_CONV_OVF_I8_UN:
3920                 case CEE_CONV_OVF_U1_UN:
3921                 case CEE_CONV_OVF_U2_UN:
3922                 case CEE_CONV_OVF_U4_UN:
3923                 case CEE_CONV_OVF_U8_UN:
3924                 case CEE_CONV_OVF_I_UN:
3925                 case CEE_CONV_OVF_U_UN:
3926                         CHECK_STACK (1);
3927                         ADD_UNOP (*ip);
3928                         ip++;
3929                         break;
3930                 case CEE_CPOBJ:
3931                         CHECK_OPSIZE (5);
3932                         CHECK_STACK (2);
3933                         token = read32 (ip + 1);
3934                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3935                                 klass = mono_method_get_wrapper_data (method, token);
3936                         else
3937                                 klass = mono_class_get_full (image, token, generic_context);
3938
3939                         mono_class_init (klass);
3940                         sp -= 2;
3941                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
3942                                 MonoInst *store, *load;
3943                                 MONO_INST_NEW (cfg, load, CEE_LDIND_REF);
3944                                 load->cil_code = ip;
3945                                 load->inst_i0 = sp [1];
3946                                 load->type = STACK_OBJ;
3947                                 load->flags |= ins_flag;
3948                                 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
3949                                 store->cil_code = ip;
3950                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
3951                                 MONO_ADD_INS (bblock, store);
3952                                 store->inst_i0 = sp [0];
3953                                 store->inst_i1 = load;
3954                                 store->flags |= ins_flag;
3955                         } else {
3956                                 n = mono_class_value_size (klass, NULL);
3957                                 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
3958                                         MonoInst *copy;
3959                                         MONO_INST_NEW (cfg, copy, OP_MEMCPY);
3960                                         copy->inst_left = sp [0];
3961                                         copy->inst_right = sp [1];
3962                                         copy->cil_code = ip;
3963                                         copy->unused = n;
3964                                         MONO_ADD_INS (bblock, copy);
3965                                 } else {
3966                                         MonoInst *iargs [3];
3967                                         iargs [0] = sp [0];
3968                                         iargs [1] = sp [1];
3969                                         NEW_ICONST (cfg, iargs [2], n);
3970                                         iargs [2]->cil_code = ip;
3971
3972                                         mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
3973                                 }
3974                         }
3975                         ins_flag = 0;
3976                         ip += 5;
3977                         break;
3978                 case CEE_LDOBJ: {
3979                         MonoInst *iargs [3];
3980                         CHECK_OPSIZE (5);
3981                         CHECK_STACK (1);
3982                         --sp;
3983                         token = read32 (ip + 1);
3984                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3985                                 klass = mono_method_get_wrapper_data (method, token);
3986                         else
3987                                 klass = mono_class_get_full (image, token, generic_context);
3988
3989                         mono_class_init (klass);
3990                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
3991                                 MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
3992                                 ins->cil_code = ip;
3993                                 ins->inst_i0 = sp [0];
3994                                 ins->type = STACK_OBJ;
3995                                 ins->flags |= ins_flag;
3996                                 ins_flag = 0;
3997                                 *sp++ = ins;
3998                                 ip += 5;
3999                                 break;
4000                         }
4001                         n = mono_class_value_size (klass, NULL);
4002                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
4003                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
4004                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
4005                                 MonoInst *copy;
4006                                 MONO_INST_NEW (cfg, copy, OP_MEMCPY);
4007                                 copy->inst_left = iargs [0];
4008                                 copy->inst_right = *sp;
4009                                 copy->cil_code = ip;
4010                                 copy->unused = n;
4011                                 MONO_ADD_INS (bblock, copy);
4012                         } else {
4013                                 iargs [1] = *sp;
4014                                 NEW_ICONST (cfg, iargs [2], n);
4015                                 iargs [2]->cil_code = ip;
4016
4017                                 mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
4018                         }
4019                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
4020                         ++sp;
4021                         ip += 5;
4022                         ins_flag = 0;
4023                         inline_costs += 1;
4024                         break;
4025                 }
4026                 case CEE_LDSTR:
4027                         CHECK_STACK_OVF (1);
4028                         CHECK_OPSIZE (5);
4029                         n = read32 (ip + 1);
4030
4031                         if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
4032                                 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));                                                                
4033                                 ins->cil_code = ip;
4034                                 ins->type = STACK_OBJ;
4035                                 *sp = ins;
4036                         }
4037                         else if (method->wrapper_type != MONO_WRAPPER_NONE) {
4038                                 int temp;
4039                                 MonoInst *iargs [1];
4040
4041                                 NEW_PCONST (cfg, iargs [0], mono_method_get_wrapper_data (method, n));                          
4042                                 temp = mono_emit_jit_icall (cfg, bblock, mono_string_new_wrapper, iargs, ip);
4043                                 NEW_TEMPLOAD (cfg, *sp, temp);
4044
4045                         } else {
4046
4047                                 if (cfg->opt & MONO_OPT_SHARED) {
4048                                         int temp;
4049                                         MonoInst *iargs [3];
4050
4051                                         if (mono_compile_aot) {
4052                                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, (gpointer)n);
4053                                         }
4054
4055                                         NEW_TEMPLOAD (cfg, iargs [0], mono_get_domainvar (cfg)->inst_c0);
4056                                         NEW_IMAGECONST (cfg, iargs [1], image);
4057                                         NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
4058                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldstr, iargs, ip);
4059                                         NEW_TEMPLOAD (cfg, *sp, temp);
4060                                         mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
4061                                 } else {
4062                                         if (mono_compile_aot)
4063                                                 NEW_LDSTRCONST (cfg, ins, image, n);
4064                                         else {
4065                                                 NEW_PCONST (cfg, ins, NULL);
4066                                                 ins->cil_code = ip;
4067                                                 ins->type = STACK_OBJ;
4068                                                 ins->inst_p0 = mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
4069                                         }
4070                                         *sp = ins;
4071                                 }
4072                         }
4073
4074                         sp++;
4075                         ip += 5;
4076                         break;
4077                 case CEE_NEWOBJ: {
4078                         MonoInst *iargs [2];
4079                         MonoMethodSignature *fsig;
4080                         int temp;
4081
4082                         CHECK_OPSIZE (5);
4083                         token = read32 (ip + 1);
4084                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
4085                                 cmethod = mono_method_get_wrapper_data (method, token);
4086                         } else
4087                                 cmethod = mono_get_method_full (image, token, NULL, generic_context);
4088                         fsig = mono_method_get_signature (cmethod, image, token);
4089
4090                         mono_class_init (cmethod->klass);
4091
4092                         n = fsig->param_count;
4093                         CHECK_STACK (n);
4094
4095                         /* move the args to allow room for 'this' in the first position */
4096                         while (n--) {
4097                                 --sp;
4098                                 sp [1] = sp [0];
4099                         }
4100
4101                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4102                         
4103
4104                         if (cmethod->klass->parent == mono_defaults.array_class) {
4105                                 NEW_METHODCONST (cfg, *sp, cmethod);
4106                                 temp = handle_array_new (cfg, bblock, fsig->param_count, sp, ip);
4107                         } else if (cmethod->string_ctor) {
4108                                 /* we simply pass a null pointer */
4109                                 NEW_PCONST (cfg, *sp, NULL); 
4110                                 /* now call the string ctor */
4111                                 temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, NULL);
4112                         } else {
4113                                 if (cmethod->klass->valuetype) {
4114                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
4115                                         temp = iargs [0]->inst_c0;
4116                                         NEW_TEMPLOADA (cfg, *sp, temp);
4117                                 } else {
4118                                         temp = handle_alloc (cfg, bblock, cmethod->klass, ip);
4119                                         NEW_TEMPLOAD (cfg, *sp, temp);
4120                                 }
4121
4122                                 if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
4123                                     mono_method_check_inlining (cfg, cmethod) &&
4124                                     !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE) &&
4125                                     !g_list_find (dont_inline, cmethod)) {
4126                                         int costs;
4127                                         MonoBasicBlock *ebblock;
4128                                         if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, FALSE))) {
4129
4130                                                 ip += 5;
4131                                                 real_offset += 5;
4132                                                 
4133                                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
4134                                                 ebblock->next_bb = bblock;
4135                                                 link_bblock (cfg, ebblock, bblock);
4136
4137                                                 NEW_TEMPLOAD (cfg, *sp, temp);
4138                                                 sp++;
4139
4140                                                 /* indicates start of a new block, and triggers a load 
4141                                                    of all stack arguments at bb boundarie */
4142                                                 bblock = ebblock;
4143
4144                                                 inline_costs += costs;
4145                                                 break;
4146                                                 
4147                                         } else {
4148                                                 mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, sp[0]);
4149                                         }
4150                                 } else {
4151                                         /* now call the actual ctor */
4152                                         mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, sp[0]);
4153                                 }
4154                         }
4155
4156                         NEW_TEMPLOAD (cfg, *sp, temp);
4157                         sp++;
4158                         
4159                         ip += 5;
4160                         inline_costs += 5;
4161                         break;
4162                 }
4163                 case CEE_ISINST:
4164                         CHECK_STACK (1);
4165                         --sp;
4166                         CHECK_OPSIZE (5);
4167                         token = read32 (ip + 1);
4168                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4169                                 klass = mono_method_get_wrapper_data (method, token);
4170                         else
4171                                 klass = mono_class_get_full (image, token, generic_context);
4172                         mono_class_init (klass);
4173                 
4174                         if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4175                         
4176                                 MonoMethod *mono_isinst;
4177                                 MonoInst *iargs [1];
4178                                 MonoBasicBlock *ebblock;
4179                                 int costs;
4180                                 int temp;
4181                                 
4182                                 mono_isinst = mono_marshal_get_isinst (klass); 
4183                                 iargs [0] = sp [0];
4184                                 
4185                                 costs = inline_method (cfg, mono_isinst, mono_isinst->signature, bblock, 
4186                                                            iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
4187                         
4188                                 g_assert (costs > 0);
4189                                 
4190                                 ip += 5;
4191                                 real_offset += 5;
4192                         
4193                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
4194                                 ebblock->next_bb = bblock;
4195                                 link_bblock (cfg, ebblock, bblock);
4196
4197                                 temp = iargs [0]->inst_i0->inst_c0;
4198                                 NEW_TEMPLOAD (cfg, *sp, temp);
4199                                 
4200                                 sp++;
4201                                 bblock = ebblock;
4202                                 inline_costs += costs;
4203
4204                         }
4205                         else {
4206                                 MONO_INST_NEW (cfg, ins, *ip);
4207                                 ins->type = STACK_OBJ;
4208                                 ins->inst_left = *sp;
4209                                 ins->inst_newa_class = klass;
4210                                 ins->cil_code = ip;
4211                                 *sp++ = emit_tree (cfg, bblock, ins);
4212                                 ip += 5;
4213                         }
4214                         break;
4215                 case CEE_UNBOX_ANY: {
4216                         MonoInst *add, *vtoffset;
4217                         MonoInst *iargs [3];
4218
4219                         CHECK_STACK (1);
4220                         --sp;
4221                         CHECK_OPSIZE (5);
4222                         token = read32 (ip + 1);
4223                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4224                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
4225                         else 
4226                                 klass = mono_class_get_full (image, token, generic_context);
4227                         mono_class_init (klass);
4228
4229                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
4230                                 /* CASTCLASS */
4231                                 if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4232                                         MonoMethod *mono_castclass;
4233                                         MonoInst *iargs [1];
4234                                         MonoBasicBlock *ebblock;
4235                                         int costs;
4236                                         int temp;
4237                                         
4238                                         mono_castclass = mono_marshal_get_castclass (klass); 
4239                                         iargs [0] = sp [0];
4240                                         
4241                                         costs = inline_method (cfg, mono_castclass, mono_castclass->signature, bblock, 
4242                                                                    iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
4243                                 
4244                                         g_assert (costs > 0);
4245                                         
4246                                         ip += 5;
4247                                         real_offset += 5;
4248                                 
4249                                         GET_BBLOCK (cfg, bbhash, bblock, ip);
4250                                         ebblock->next_bb = bblock;
4251                                         link_bblock (cfg, ebblock, bblock);
4252         
4253                                         temp = iargs [0]->inst_i0->inst_c0;
4254                                         NEW_TEMPLOAD (cfg, *sp, temp);
4255                                         
4256                                         sp++;
4257                                         bblock = ebblock;
4258                                         inline_costs += costs;                          
4259                                 }
4260                                 else {
4261                                         MONO_INST_NEW (cfg, ins, CEE_CASTCLASS);
4262                                         ins->type = STACK_OBJ;
4263                                         ins->inst_left = *sp;
4264                                         ins->klass = klass;
4265                                         ins->inst_newa_class = klass;
4266                                         ins->cil_code = ip;
4267                                         *sp++ = ins;
4268                                 }
4269                                 ip += 5;
4270                                 break;
4271                         }
4272
4273                         MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
4274                         ins->type = STACK_OBJ;
4275                         ins->inst_left = *sp;
4276                         ins->klass = klass;
4277                         ins->inst_newa_class = klass;
4278                         ins->cil_code = ip;
4279
4280                         MONO_INST_NEW (cfg, add, OP_PADD);
4281                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
4282                         add->inst_left = ins;
4283                         add->inst_right = vtoffset;
4284                         add->type = STACK_MP;
4285                         *sp = add;
4286                         ip += 5;
4287                         /* LDOBJ impl */
4288                         n = mono_class_value_size (klass, NULL);
4289                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
4290                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
4291                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
4292                                 MonoInst *copy;
4293                                 MONO_INST_NEW (cfg, copy, OP_MEMCPY);
4294                                 copy->inst_left = iargs [0];
4295                                 copy->inst_right = *sp;
4296                                 copy->cil_code = ip;
4297                                 copy->unused = n;
4298                                 MONO_ADD_INS (bblock, copy);
4299                         } else {
4300                                 iargs [1] = *sp;
4301                                 NEW_ICONST (cfg, iargs [2], n);
4302                                 iargs [2]->cil_code = ip;
4303
4304                                 mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
4305                         }
4306                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
4307                         ++sp;
4308                         inline_costs += 2;
4309                         break;
4310                 }
4311                 case CEE_UNBOX: {
4312                         MonoInst *add, *vtoffset;
4313
4314                         CHECK_STACK (1);
4315                         --sp;
4316                         CHECK_OPSIZE (5);
4317                         token = read32 (ip + 1);
4318                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4319                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
4320                         else 
4321                                 klass = mono_class_get_full (image, token, generic_context);
4322                         mono_class_init (klass);
4323
4324                         MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
4325                         ins->type = STACK_OBJ;
4326                         ins->inst_left = *sp;
4327                         ins->klass = klass;
4328                         ins->inst_newa_class = klass;
4329                         ins->cil_code = ip;
4330
4331                         MONO_INST_NEW (cfg, add, OP_PADD);
4332                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
4333                         add->inst_left = ins;
4334                         add->inst_right = vtoffset;
4335                         add->type = STACK_MP;
4336                         *sp++ = add;
4337                         ip += 5;
4338                         inline_costs += 2;
4339                         break;
4340                 }
4341                 case CEE_CASTCLASS:
4342                         CHECK_STACK (1);
4343                         --sp;
4344                         CHECK_OPSIZE (5);
4345                         token = read32 (ip + 1);
4346                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4347                                 klass = mono_method_get_wrapper_data (method, token);
4348                         else
4349                                 klass = mono_class_get_full (image, token, generic_context);
4350                         mono_class_init (klass);
4351                 
4352                         if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4353                                 
4354                                 MonoMethod *mono_castclass;
4355                                 MonoInst *iargs [1];
4356                                 MonoBasicBlock *ebblock;
4357                                 int costs;
4358                                 int temp;
4359                                 
4360                                 mono_castclass = mono_marshal_get_castclass (klass); 
4361                                 iargs [0] = sp [0];
4362                                 
4363                                 costs = inline_method (cfg, mono_castclass, mono_castclass->signature, bblock, 
4364                                                            iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
4365                         
4366                                 g_assert (costs > 0);
4367                                 
4368                                 ip += 5;
4369                                 real_offset += 5;
4370                         
4371                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
4372                                 ebblock->next_bb = bblock;
4373                                 link_bblock (cfg, ebblock, bblock);
4374
4375                                 temp = iargs [0]->inst_i0->inst_c0;
4376                                 NEW_TEMPLOAD (cfg, *sp, temp);
4377                                 
4378                                 sp++;
4379                                 bblock = ebblock;
4380                                 inline_costs += costs;
4381                         }
4382                         else {
4383                                 MONO_INST_NEW (cfg, ins, *ip);
4384                                 ins->type = STACK_OBJ;
4385                                 ins->inst_left = *sp;
4386                                 ins->klass = klass;
4387                                 ins->inst_newa_class = klass;
4388                                 ins->cil_code = ip;
4389                                 *sp++ = emit_tree (cfg, bblock, ins);
4390                                 ip += 5;
4391                         }
4392                         break;
4393                 case CEE_THROW:
4394                         CHECK_STACK (1);
4395                         MONO_INST_NEW (cfg, ins, *ip);
4396                         --sp;
4397                         ins->inst_left = *sp;
4398                         ins->cil_code = ip++;
4399                         MONO_ADD_INS (bblock, ins);
4400                         sp = stack_start;
4401                         start_new_bblock = 1;
4402                         break;
4403                 case CEE_LDFLD:
4404                 case CEE_LDFLDA:
4405                 case CEE_STFLD: {
4406                         MonoInst *offset_ins;
4407                         MonoClassField *field;
4408                         MonoBasicBlock *ebblock;
4409                         int costs;
4410                         guint foffset;
4411
4412                         if (*ip == CEE_STFLD) {
4413                                 CHECK_STACK (2);
4414                                 sp -= 2;
4415                         } else {
4416                                 CHECK_STACK (1);
4417                                 --sp;
4418                         }
4419                         // FIXME: enable this test later.
4420                         //if (sp [0]->type != STACK_OBJ && sp [0]->type != STACK_MP)
4421                         //      goto unverified;
4422                         CHECK_OPSIZE (5);
4423                         token = read32 (ip + 1);
4424                         field = mono_field_from_token (image, token, &klass, generic_context);
4425                         mono_class_init (klass);
4426
4427                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
4428                         /* FIXME: mark instructions for use in SSA */
4429                         if (*ip == CEE_STFLD) {
4430                                 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
4431                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
4432                                         MonoInst *iargs [5];
4433
4434                                         iargs [0] = sp [0];
4435                                         NEW_CLASSCONST (cfg, iargs [1], klass);
4436                                         NEW_FIELDCONST (cfg, iargs [2], field);
4437                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
4438                                                     field->offset);
4439                                         iargs [4] = sp [1];
4440
4441                                         if (cfg->opt & MONO_OPT_INLINE) {
4442                                                 costs = inline_method (cfg, stfld_wrapper, stfld_wrapper->signature, bblock, 
4443                                                                        iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
4444                                                 g_assert (costs > 0);
4445                                                       
4446                                                 ip += 5;
4447                                                 real_offset += 5;
4448
4449                                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
4450                                                 ebblock->next_bb = bblock;
4451                                                 link_bblock (cfg, ebblock, bblock);
4452
4453                                                 /* indicates start of a new block, and triggers a load 
4454                                                    of all stack arguments at bb boundarie */
4455                                                 bblock = ebblock;
4456
4457                                                 inline_costs += costs;
4458                                                 break;
4459                                         } else {
4460                                                 mono_emit_method_call_spilled (cfg, bblock, stfld_wrapper, stfld_wrapper->signature, iargs, ip, NULL);
4461                                         }
4462                                 } else {
4463                                         MonoInst *store;
4464                                         NEW_ICONST (cfg, offset_ins, foffset);
4465                                         MONO_INST_NEW (cfg, ins, OP_PADD);
4466                                         ins->cil_code = ip;
4467                                         ins->inst_left = *sp;
4468                                         ins->inst_right = offset_ins;
4469                                         ins->type = STACK_MP;
4470
4471                                         MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
4472                                         store->cil_code = ip;
4473                                         store->inst_left = ins;
4474                                         store->inst_right = sp [1];
4475                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4476                                         store->flags |= ins_flag;
4477                                         ins_flag = 0;
4478                                         if (store->opcode == CEE_STOBJ) {
4479                                                 handle_stobj (cfg, bblock, ins, sp [1], ip, 
4480                                                               mono_class_from_mono_type (field->type), FALSE, FALSE);
4481                                         } else
4482                                                 MONO_ADD_INS (bblock, store);
4483                                 }
4484                         } else {
4485                                 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
4486                                         /* fixme: we need to inline that call somehow */
4487                                         MonoMethod *ldfld_wrapper = mono_marshal_get_ldfld_wrapper (field->type); 
4488                                         MonoInst *iargs [4];
4489                                         int temp;
4490                                         
4491                                         iargs [0] = sp [0];
4492                                         NEW_CLASSCONST (cfg, iargs [1], klass);
4493                                         NEW_FIELDCONST (cfg, iargs [2], field);
4494                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
4495                                         if (cfg->opt & MONO_OPT_INLINE) {
4496                                                 costs = inline_method (cfg, ldfld_wrapper, ldfld_wrapper->signature, bblock, 
4497                                                                        iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
4498                                                 g_assert (costs > 0);
4499                                                       
4500                                                 ip += 5;
4501                                                 real_offset += 5;
4502
4503                                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
4504                                                 ebblock->next_bb = bblock;
4505                                                 link_bblock (cfg, ebblock, bblock);
4506
4507                                                 temp = iargs [0]->inst_i0->inst_c0;
4508
4509                                                 if (*ip == CEE_LDFLDA) {
4510                                                         /* not sure howto handle this */
4511                                                         NEW_TEMPLOADA (cfg, *sp, temp);
4512                                                 } else {
4513                                                         NEW_TEMPLOAD (cfg, *sp, temp);
4514                                                 }
4515                                                 sp++;
4516
4517                                                 /* indicates start of a new block, and triggers a load of
4518                                                    all stack arguments at bb boundarie */
4519                                                 bblock = ebblock;
4520                                                 
4521                                                 inline_costs += costs;
4522                                                 break;
4523                                         } else {
4524                                                 temp = mono_emit_method_call_spilled (cfg, bblock, ldfld_wrapper, ldfld_wrapper->signature, iargs, ip, NULL);
4525                                                 if (*ip == CEE_LDFLDA) {
4526                                                         /* not sure howto handle this */
4527                                                         NEW_TEMPLOADA (cfg, *sp, temp);
4528                                                 } else {
4529                                                         NEW_TEMPLOAD (cfg, *sp, temp);
4530                                                 }
4531                                                 sp++;
4532                                         }
4533                                 } else {
4534                                         NEW_ICONST (cfg, offset_ins, foffset);
4535                                         MONO_INST_NEW (cfg, ins, OP_PADD);
4536                                         ins->cil_code = ip;
4537                                         ins->inst_left = *sp;
4538                                         ins->inst_right = offset_ins;
4539                                         ins->type = STACK_MP;
4540
4541                                         if (*ip == CEE_LDFLDA) {
4542                                                 *sp++ = ins;
4543                                         } else {
4544                                                 MonoInst *load;
4545                                                 MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
4546                                                 type_to_eval_stack_type (field->type, load);
4547                                                 load->cil_code = ip;
4548                                                 load->inst_left = ins;
4549                                                 load->flags |= ins_flag;
4550                                                 ins_flag = 0;
4551                                                 *sp++ = load;
4552                                         }
4553                                 }
4554                         }
4555                         ip += 5;
4556                         break;
4557                 }
4558                 case CEE_LDSFLD:
4559                 case CEE_LDSFLDA:
4560                 case CEE_STSFLD: {
4561                         MonoClassField *field;
4562                         gpointer addr = NULL;
4563
4564                         CHECK_OPSIZE (5);
4565                         token = read32 (ip + 1);
4566
4567                         field = mono_field_from_token (image, token, &klass, generic_context);
4568                         mono_class_init (klass);
4569
4570                         if ((*ip) == CEE_STSFLD)
4571                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4572
4573                         if (cfg->domain->special_static_fields)
4574                                 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
4575
4576                         if ((cfg->opt & MONO_OPT_SHARED) || (mono_compile_aot && addr)) {
4577                                 int temp;
4578                                 MonoInst *iargs [2];
4579                                 g_assert (field->parent);
4580                                 NEW_TEMPLOAD (cfg, iargs [0], mono_get_domainvar (cfg)->inst_c0);
4581                                 NEW_FIELDCONST (cfg, iargs [1], field);
4582                                 temp = mono_emit_jit_icall (cfg, bblock, mono_class_static_field_address, iargs, ip);
4583                                 NEW_TEMPLOAD (cfg, ins, temp);
4584                         } else {
4585                                 MonoVTable *vtable;
4586                                 vtable = mono_class_vtable (cfg->domain, klass);
4587                                 if (!addr) {
4588                                         if ((!vtable->initialized || mono_compile_aot) && !(klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && mono_class_needs_cctor_run (klass, method)) {
4589                                                 guint8 *tramp = mono_create_class_init_trampoline (vtable);
4590                                                 mono_emit_native_call (cfg, bblock, tramp, 
4591                                                                                            helper_sig_class_init_trampoline,
4592                                                                                            NULL, ip, FALSE, FALSE);
4593                                                 if (cfg->verbose_level > 2)
4594                                                         g_print ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, field->name);
4595                                         } else {
4596                                                 if (cfg->run_cctors)
4597                                                         mono_runtime_class_init (vtable);
4598                                         }
4599                                         addr = (char*)vtable->data + field->offset;
4600
4601                                         if (mono_compile_aot)
4602                                                 NEW_SFLDACONST (cfg, ins, field);
4603                                         else
4604                                                 NEW_PCONST (cfg, ins, addr);
4605                                         ins->cil_code = ip;
4606                                 } else {
4607                                         /* 
4608                                          * insert call to mono_threads_get_static_data (GPOINTER_TO_UINT (addr)) 
4609                                          * This could be later optimized to do just a couple of
4610                                          * memory dereferences with constant offsets.
4611                                          */
4612                                         int temp;
4613                                         MonoInst *iargs [1];
4614                                         NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
4615                                         temp = mono_emit_jit_icall (cfg, bblock, mono_get_special_static_data, iargs, ip);
4616                                         NEW_TEMPLOAD (cfg, ins, temp);
4617                                 }
4618                         }
4619
4620                         /* FIXME: mark instructions for use in SSA */
4621                         if (*ip == CEE_LDSFLDA) {
4622                                 *sp++ = ins;
4623                         } else if (*ip == CEE_STSFLD) {
4624                                 MonoInst *store;
4625                                 CHECK_STACK (1);
4626                                 sp--;
4627                                 MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
4628                                 store->cil_code = ip;
4629                                 store->inst_left = ins;
4630                                 store->inst_right = sp [0];
4631                                 store->flags |= ins_flag;
4632                                 ins_flag = 0;
4633
4634                                 if (store->opcode == CEE_STOBJ) {
4635                                         handle_stobj (cfg, bblock, ins, sp [0], ip, mono_class_from_mono_type (field->type), FALSE, FALSE);
4636                                 } else
4637                                         MONO_ADD_INS (bblock, store);
4638                         } else {
4639                                 gboolean is_const = FALSE;
4640                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
4641                                 if (!((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot) && 
4642                                     vtable->initialized && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY)) {
4643                                         gpointer addr = (char*)vtable->data + field->offset;
4644                                         /* g_print ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, field->name);*/
4645                                         is_const = TRUE;
4646                                         switch (field->type->type) {
4647                                         case MONO_TYPE_BOOLEAN:
4648                                         case MONO_TYPE_U1:
4649                                                 NEW_ICONST (cfg, *sp, *((guint8 *)addr));
4650                                                 sp++;
4651                                                 break;
4652                                         case MONO_TYPE_I1:
4653                                                 NEW_ICONST (cfg, *sp, *((gint8 *)addr));
4654                                                 sp++;
4655                                                 break;                                          
4656                                         case MONO_TYPE_CHAR:
4657                                         case MONO_TYPE_U2:
4658                                                 NEW_ICONST (cfg, *sp, *((guint16 *)addr));
4659                                                 sp++;
4660                                                 break;
4661                                         case MONO_TYPE_I2:
4662                                                 NEW_ICONST (cfg, *sp, *((gint16 *)addr));
4663                                                 sp++;
4664                                                 break;
4665                                                 break;
4666                                         case MONO_TYPE_I4:
4667                                                 NEW_ICONST (cfg, *sp, *((gint32 *)addr));
4668                                                 sp++;
4669                                                 break;                                          
4670                                         case MONO_TYPE_U4:
4671                                                 NEW_ICONST (cfg, *sp, *((guint32 *)addr));
4672                                                 sp++;
4673                                                 break;
4674                                         case MONO_TYPE_I:
4675                                         case MONO_TYPE_U:
4676                                         case MONO_TYPE_STRING:
4677                                         case MONO_TYPE_OBJECT:
4678                                         case MONO_TYPE_CLASS:
4679                                         case MONO_TYPE_SZARRAY:
4680                                         case MONO_TYPE_PTR:
4681                                         case MONO_TYPE_FNPTR:
4682                                         case MONO_TYPE_ARRAY:
4683                                                 NEW_PCONST (cfg, *sp, *((gpointer *)addr));
4684                                                 type_to_eval_stack_type (field->type, *sp);
4685                                                 sp++;
4686                                                 break;
4687                                         case MONO_TYPE_I8:
4688                                         case MONO_TYPE_U8:
4689                                                 MONO_INST_NEW (cfg, *sp, OP_I8CONST);
4690                                                 sp [0]->type = STACK_I8;
4691                                                 sp [0]->inst_l = *((gint64 *)addr);
4692                                                 sp++;
4693                                                 break;
4694                                         case MONO_TYPE_R4:
4695                                         case MONO_TYPE_R8:
4696                                         case MONO_TYPE_VALUETYPE:
4697                                         default:
4698                                                 is_const = FALSE;
4699                                                 break;
4700                                         }
4701                                 }
4702
4703                                 if (!is_const) {
4704                                         MonoInst *load;
4705                                         CHECK_STACK_OVF (1);
4706                                         MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
4707                                         type_to_eval_stack_type (field->type, load);
4708                                         load->cil_code = ip;
4709                                         load->inst_left = ins;
4710                                         *sp++ = load;
4711                                         load->flags |= ins_flag;
4712                                         ins_flag = 0;
4713                                         /* fixme: dont see the problem why this does not work */
4714                                         //cfg->disable_aot = TRUE;
4715                                 }
4716                         }
4717                         ip += 5;
4718                         break;
4719                 }
4720                 case CEE_STOBJ:
4721                         CHECK_STACK (2);
4722                         sp -= 2;
4723                         CHECK_OPSIZE (5);
4724                         token = read32 (ip + 1);
4725                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4726                                 klass = mono_method_get_wrapper_data (method, token);
4727                         else
4728                                 klass = mono_class_get_full (image, token, generic_context);
4729                         mono_class_init (klass);
4730                         n = mono_type_to_stind (&klass->byval_arg);
4731                         if (n == CEE_STOBJ) {
4732                                 handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE);
4733                         } else {
4734                                 /* FIXME: should check item at sp [1] is compatible with the type of the store. */
4735                                 MonoInst *store;
4736                                 MONO_INST_NEW (cfg, store, n);
4737                                 store->cil_code = ip;
4738                                 store->inst_left = sp [0];
4739                                 store->inst_right = sp [1];
4740                                 store->flags |= ins_flag;
4741                                 MONO_ADD_INS (bblock, store);
4742                         }
4743                         ins_flag = 0;
4744                         ip += 5;
4745                         inline_costs += 1;
4746                         break;
4747                 case CEE_BOX: {
4748                         MonoInst *val;
4749                         CHECK_STACK (1);
4750                         --sp;
4751                         val = *sp;
4752                         CHECK_OPSIZE (5);
4753                         token = read32 (ip + 1);
4754                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4755                                 klass = mono_method_get_wrapper_data (method, token);
4756                         else
4757                                 klass = mono_class_get_full (image, token, generic_context);
4758                         mono_class_init (klass);
4759
4760                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
4761                                 *sp++ = val;
4762                                 ip += 5;
4763                                 break;
4764                         }
4765                         *sp++ = handle_box (cfg, bblock, val, ip, klass);
4766                         ip += 5;
4767                         inline_costs += 1;
4768                         break;
4769                 }
4770                 case CEE_NEWARR:
4771                         CHECK_STACK (1);
4772                         MONO_INST_NEW (cfg, ins, *ip);
4773                         ins->cil_code = ip;
4774                         --sp;
4775
4776                         CHECK_OPSIZE (5);
4777                         token = read32 (ip + 1);
4778
4779                         /* allocate the domainvar - becaus this is used in decompose_foreach */
4780                         if (cfg->opt & MONO_OPT_SHARED) {
4781                                 mono_get_domainvar (cfg);
4782                                 /* LAME-IR: Mark it as used since otherwise it will be optimized away */
4783                                 cfg->domainvar->flags |= MONO_INST_VOLATILE;
4784                         }
4785                         
4786                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4787                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
4788                         else
4789                                 klass = mono_class_get_full (image, token, generic_context);
4790
4791                         mono_class_init (klass);
4792                         ins->inst_newa_class = klass;
4793                         ins->inst_newa_len = *sp;
4794                         ins->type = STACK_OBJ;
4795                         ip += 5;
4796                         *sp++ = ins;
4797                         /* 
4798                          * we store the object so calls to create the array are not interleaved
4799                          * with the arguments of other calls.
4800                          */
4801                         if (1) {
4802                                 MonoInst *store, *temp, *load;
4803                                 --sp;
4804                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
4805                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
4806                                 store->cil_code = ins->cil_code;
4807                                 MONO_ADD_INS (bblock, store);
4808                                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
4809                                 load->cil_code = ins->cil_code;
4810                                 *sp++ = load;
4811                         }
4812                         inline_costs += 1;
4813                         break;
4814                 case CEE_LDLEN:
4815                         CHECK_STACK (1);
4816                         MONO_INST_NEW (cfg, ins, *ip);
4817                         ins->cil_code = ip++;
4818                         --sp;
4819                         ins->inst_left = *sp;
4820                         ins->type = STACK_PTR;
4821                         *sp++ = ins;
4822                         break;
4823                 case CEE_LDELEMA:
4824                         CHECK_STACK (2);
4825                         sp -= 2;
4826                         CHECK_OPSIZE (5);
4827
4828                         if (method->wrapper_type != MONO_WRAPPER_NONE)
4829                                 klass = (MonoClass*)mono_method_get_wrapper_data (method, read32 (ip + 1));
4830                         else
4831                                 klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
4832                         mono_class_init (klass);
4833                         NEW_LDELEMA (cfg, ins, sp, klass);
4834                         ins->cil_code = ip;
4835                         *sp++ = ins;
4836                         ip += 5;
4837                         break;
4838                 case CEE_LDELEM_ANY: {
4839                         MonoInst *load;
4840                         CHECK_STACK (2);
4841                         sp -= 2;
4842                         CHECK_OPSIZE (5);
4843                         token = read32 (ip + 1);
4844                         klass = mono_class_get_full (image, token, generic_context);
4845                         mono_class_init (klass);
4846                         NEW_LDELEMA (cfg, load, sp, klass);
4847                         load->cil_code = ip;
4848                         MONO_INST_NEW (cfg, ins, mono_type_to_ldind (&klass->byval_arg));
4849                         ins->cil_code = ip;
4850                         ins->inst_left = load;
4851                         *sp++ = ins;
4852                         type_to_eval_stack_type (&klass->byval_arg, ins);
4853                         ip += 5;
4854                         break;
4855                 }
4856                 case CEE_LDELEM_I1:
4857                 case CEE_LDELEM_U1:
4858                 case CEE_LDELEM_I2:
4859                 case CEE_LDELEM_U2:
4860                 case CEE_LDELEM_I4:
4861                 case CEE_LDELEM_U4:
4862                 case CEE_LDELEM_I8:
4863                 case CEE_LDELEM_I:
4864                 case CEE_LDELEM_R4:
4865                 case CEE_LDELEM_R8:
4866                 case CEE_LDELEM_REF: {
4867                         MonoInst *load;
4868                         /*
4869                          * translate to:
4870                          * ldind.x (ldelema (array, index))
4871                          * ldelema does the bounds check
4872                          */
4873                         CHECK_STACK (2);
4874                         sp -= 2;
4875                         klass = array_access_to_klass (*ip);
4876                         NEW_LDELEMA (cfg, load, sp, klass);
4877                         load->cil_code = ip;
4878                         MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
4879                         ins->cil_code = ip;
4880                         ins->inst_left = load;
4881                         *sp++ = ins;
4882                         ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
4883                         ++ip;
4884                         break;
4885                 }
4886                 case CEE_STELEM_I:
4887                 case CEE_STELEM_I1:
4888                 case CEE_STELEM_I2:
4889                 case CEE_STELEM_I4:
4890                 case CEE_STELEM_I8:
4891                 case CEE_STELEM_R4:
4892                 case CEE_STELEM_R8: {
4893                         MonoInst *load;
4894                         /*
4895                          * translate to:
4896                          * stind.x (ldelema (array, index), val)
4897                          * ldelema does the bounds check
4898                          */
4899                         CHECK_STACK (3);
4900                         sp -= 3;
4901                         klass = array_access_to_klass (*ip);
4902                         NEW_LDELEMA (cfg, load, sp, klass);
4903                         load->cil_code = ip;
4904                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
4905                         ins->cil_code = ip;
4906                         ins->inst_left = load;
4907                         ins->inst_right = sp [2];
4908                         ++ip;
4909                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4910                         MONO_ADD_INS (bblock, ins);
4911                         inline_costs += 1;
4912                         break;
4913                 }
4914                 case CEE_STELEM_ANY: {
4915                         MonoInst *load;
4916                         /*
4917                          * translate to:
4918                          * stind.x (ldelema (array, index), val)
4919                          * ldelema does the bounds check
4920                          */
4921                         CHECK_STACK (3);
4922                         sp -= 3;
4923                         CHECK_OPSIZE (5);
4924                         token = read32 (ip + 1);
4925                         klass = mono_class_get_full (image, token, generic_context);
4926                         mono_class_init (klass);
4927                         if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
4928                                 MonoMethod* helper = mono_marshal_get_stelemref ();
4929                                 MonoInst *iargs [3];
4930                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4931
4932                                 iargs [2] = sp [2];
4933                                 iargs [1] = sp [1];
4934                                 iargs [0] = sp [0];
4935                                 
4936                                 mono_emit_method_call_spilled (cfg, bblock, helper, helper->signature, iargs, ip, NULL);
4937                         } else {
4938                                 NEW_LDELEMA (cfg, load, sp, klass);
4939                                 load->cil_code = ip;
4940
4941                                 n = mono_type_to_stind (&klass->byval_arg);
4942                                 if (n == CEE_STOBJ)
4943                                         handle_stobj (cfg, bblock, load, sp [2], ip, klass, FALSE, FALSE);
4944                                 else {
4945                                         MONO_INST_NEW (cfg, ins, n);
4946                                         ins->cil_code = ip;
4947                                         ins->inst_left = load;
4948                                         ins->inst_right = sp [2];
4949                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4950                                         MONO_ADD_INS (bblock, ins);
4951                                 }
4952                         }
4953                         ip += 5;
4954                         inline_costs += 1;
4955                         break;
4956                 }
4957                 case CEE_STELEM_REF: {
4958                         MonoInst *iargs [3];
4959                         MonoMethod* helper = mono_marshal_get_stelemref ();
4960
4961                         CHECK_STACK (3);
4962                         sp -= 3;
4963
4964                         handle_loaded_temps (cfg, bblock, stack_start, sp);
4965
4966                         iargs [2] = sp [2];
4967                         iargs [1] = sp [1];
4968                         iargs [0] = sp [0];
4969                         
4970                         mono_emit_method_call_spilled (cfg, bblock, helper, helper->signature, iargs, ip, NULL);
4971
4972                         /*
4973                         MonoInst *group;
4974                         NEW_GROUP (cfg, group, sp [0], sp [1]);
4975                         MONO_INST_NEW (cfg, ins, CEE_STELEM_REF);
4976                         ins->cil_code = ip;
4977                         ins->inst_left = group;
4978                         ins->inst_right = sp [2];
4979                         MONO_ADD_INS (bblock, ins);
4980                         */
4981
4982                         ++ip;
4983                         inline_costs += 1;
4984                         break;
4985                 }
4986                 case CEE_CKFINITE: {
4987                         MonoInst *store, *temp;
4988                         CHECK_STACK (1);
4989
4990                         /* this instr. can throw exceptions as side effect,
4991                          * so we cant eliminate dead code which contains CKFINITE opdodes.
4992                          * Spilling to memory makes sure that we always perform
4993                          * this check */
4994
4995                         
4996                         MONO_INST_NEW (cfg, ins, CEE_CKFINITE);
4997                         ins->cil_code = ip;
4998                         ins->inst_left = sp [-1];
4999                         temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
5000
5001                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
5002                         store->cil_code = ip;
5003                         MONO_ADD_INS (bblock, store);
5004
5005                         NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
5006                        
5007                         ++ip;
5008                         break;
5009                 }
5010                 case CEE_REFANYVAL:
5011                         CHECK_STACK (1);
5012                         MONO_INST_NEW (cfg, ins, *ip);
5013                         --sp;
5014                         CHECK_OPSIZE (5);
5015                         klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
5016                         mono_class_init (klass);
5017                         ins->type = STACK_MP;
5018                         ins->inst_left = *sp;
5019                         ins->klass = klass;
5020                         ins->inst_newa_class = klass;
5021                         ins->cil_code = ip;
5022                         ip += 5;
5023                         *sp++ = ins;
5024                         break;
5025                 case CEE_MKREFANY: {
5026                         MonoInst *loc, *klassconst;
5027
5028                         CHECK_STACK (1);
5029                         MONO_INST_NEW (cfg, ins, *ip);
5030                         --sp;
5031                         CHECK_OPSIZE (5);
5032                         klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
5033                         mono_class_init (klass);
5034                         ins->cil_code = ip;
5035
5036                         loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
5037                         NEW_TEMPLOADA (cfg, ins->inst_right, loc->inst_c0);
5038
5039                         NEW_PCONST (cfg, klassconst, klass);
5040                         NEW_GROUP (cfg, ins->inst_left, *sp, klassconst);
5041                         
5042                         MONO_ADD_INS (bblock, ins);
5043
5044                         NEW_TEMPLOAD (cfg, *sp, loc->inst_c0);
5045                         ++sp;
5046                         ip += 5;
5047                         break;
5048                 }
5049                 case CEE_LDTOKEN: {
5050                         gpointer handle;
5051                         MonoClass *handle_class;
5052
5053                         CHECK_STACK_OVF (1);
5054
5055                         CHECK_OPSIZE (5);
5056                         n = read32 (ip + 1);
5057
5058                         handle = mono_ldtoken (image, n, &handle_class, generic_context);
5059                         mono_class_init (handle_class);
5060
5061                         if (cfg->opt & MONO_OPT_SHARED) {
5062                                 int temp;
5063                                 MonoInst *res, *store, *addr, *vtvar, *iargs [2];
5064
5065                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
5066
5067                                 NEW_IMAGECONST (cfg, iargs [0], image);
5068                                 NEW_ICONST (cfg, iargs [1], n);
5069                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
5070                                 NEW_TEMPLOAD (cfg, res, temp);
5071                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
5072                                 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
5073                                 MONO_ADD_INS (bblock, store);
5074                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
5075                         } else {
5076                                 if ((ip [5] == CEE_CALL) && (cmethod = mono_get_method_full (image, read32 (ip + 6), NULL, generic_context)) &&
5077                                                 (cmethod->klass == mono_defaults.monotype_class->parent) &&
5078                                                 (strcmp (cmethod->name, "GetTypeFromHandle") == 0) && 
5079                                         ((g_hash_table_lookup (bbhash, ip + 5) == NULL) ||
5080                                          (g_hash_table_lookup (bbhash, ip + 5) == bblock))) {
5081                                         MonoClass *tclass = mono_class_from_mono_type (handle);
5082                                         mono_class_init (tclass);
5083                                         if (mono_compile_aot)
5084                                                 NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n);
5085                                         else
5086                                                 NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
5087                                         ins->type = STACK_OBJ;
5088                                         ins->klass = cmethod->klass;
5089                                         ip += 5;
5090                                 } else {
5091                                         MonoInst *store, *addr, *vtvar;
5092
5093                                         if (mono_compile_aot)
5094                                                 NEW_LDTOKENCONST (cfg, ins, image, n);
5095                                         else
5096                                                 NEW_PCONST (cfg, ins, handle);
5097                                         vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
5098                                         NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
5099                                         NEW_INDSTORE (cfg, store, addr, ins, &mono_defaults.int_class->byval_arg);
5100                                         MONO_ADD_INS (bblock, store);
5101                                         NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
5102                                 }
5103                         }
5104
5105                         *sp++ = ins;
5106                         ip += 5;
5107                         break;
5108                 }
5109                 case CEE_CONV_U2:
5110                 case CEE_CONV_U1:
5111                 case CEE_CONV_I:
5112                         CHECK_STACK (1);
5113                         ADD_UNOP (*ip);
5114                         ip++;
5115                         break;
5116                 case CEE_ADD_OVF:
5117                 case CEE_ADD_OVF_UN:
5118                 case CEE_MUL_OVF:
5119                 case CEE_MUL_OVF_UN:
5120                 case CEE_SUB_OVF:
5121                 case CEE_SUB_OVF_UN:
5122                         CHECK_STACK (2);
5123                         ADD_BINOP (*ip);
5124                         if (mono_find_jit_opcode_emulation (ins->opcode)) {
5125                                 --sp;
5126                                 *sp++ = emit_tree (cfg, bblock, ins);
5127                         }
5128                         ip++;
5129                         break;
5130                 case CEE_ENDFINALLY:
5131                         MONO_INST_NEW (cfg, ins, *ip);
5132                         MONO_ADD_INS (bblock, ins);
5133                         ins->cil_code = ip++;
5134                         start_new_bblock = 1;
5135
5136                         /*
5137                          * Control will leave the method so empty the stack, otherwise
5138                          * the next basic block will start with a nonempty stack.
5139                          */
5140                         while (sp != stack_start) {
5141                                 MONO_INST_NEW (cfg, ins, CEE_POP);
5142                                 ins->cil_code = ip;
5143                                 sp--;
5144                                 ins->inst_i0 = *sp;
5145                                 MONO_ADD_INS (bblock, ins);
5146                         }
5147                         break;
5148                 case CEE_LEAVE:
5149                 case CEE_LEAVE_S: {
5150                         GList *handlers;
5151                         if (*ip == CEE_LEAVE) {
5152                                 CHECK_OPSIZE (5);
5153                                 target = ip + 5 + (gint32)read32(ip + 1);
5154                         } else {
5155                                 CHECK_OPSIZE (2);
5156                                 target = ip + 2 + (signed char)(ip [1]);
5157                         }
5158
5159                         /* empty the stack */
5160                         while (sp != stack_start) {
5161                                 MONO_INST_NEW (cfg, ins, CEE_POP);
5162                                 ins->cil_code = ip;
5163                                 sp--;
5164                                 ins->inst_i0 = *sp;
5165                                 MONO_ADD_INS (bblock, ins);
5166                         }
5167
5168                         /* 
5169                          * If this leave statement is in a catch block, check for a
5170                          * pending exception, and rethrow it if necessary.
5171                          */
5172                         for (i = 0; i < header->num_clauses; ++i) {
5173                                 MonoExceptionClause *clause = &header->clauses [i];
5174                                 if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code)) {
5175                                         int temp;
5176
5177                                         temp = mono_emit_jit_icall (cfg, bblock, mono_thread_get_pending_exception, NULL, ip);
5178                                         NEW_TEMPLOAD (cfg, *sp, temp);
5179
5180                                         MONO_INST_NEW (cfg, ins, OP_THROW_OR_NULL);
5181                                         ins->inst_left = *sp;
5182                                         ins->cil_code = ip;
5183                                         MONO_ADD_INS (bblock, ins);
5184                                 }
5185                         }
5186
5187                         /* fixme: call fault handler ? */
5188
5189                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
5190                                 GList *tmp;
5191                                 for (tmp = handlers; tmp; tmp = tmp->next) {
5192                                         tblock = tmp->data;
5193                                         link_bblock (cfg, bblock, tblock);
5194                                         MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
5195                                         ins->cil_code = ip;
5196                                         ins->inst_target_bb = tblock;
5197                                         MONO_ADD_INS (bblock, ins);
5198                                 }
5199                                 g_list_free (handlers);
5200                         } 
5201
5202                         MONO_INST_NEW (cfg, ins, CEE_BR);
5203                         ins->cil_code = ip;
5204                         MONO_ADD_INS (bblock, ins);
5205                         GET_BBLOCK (cfg, bbhash, tblock, target);
5206                         link_bblock (cfg, bblock, tblock);
5207                         CHECK_BBLOCK (target, ip, tblock);
5208                         ins->inst_target_bb = tblock;
5209                         start_new_bblock = 1;
5210
5211                         if (*ip == CEE_LEAVE)
5212                                 ip += 5;
5213                         else
5214                                 ip += 2;
5215
5216                         break;
5217                 }
5218                 case CEE_STIND_I:
5219                         CHECK_STACK (2);
5220                         MONO_INST_NEW (cfg, ins, *ip);
5221                         sp -= 2;
5222                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5223                         MONO_ADD_INS (bblock, ins);
5224                         ins->cil_code = ip++;
5225                         ins->inst_i0 = sp [0];
5226                         ins->inst_i1 = sp [1];
5227                         inline_costs += 1;
5228                         break;
5229                 case CEE_CONV_U:
5230                         CHECK_STACK (1);
5231                         ADD_UNOP (*ip);
5232                         ip++;
5233                         break;
5234                 /* trampoline mono specific opcodes */
5235                 case MONO_CUSTOM_PREFIX: {
5236
5237                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
5238
5239                         CHECK_OPSIZE (2);
5240                         switch (ip [1]) {
5241
5242                         case CEE_MONO_ICALL: {
5243                                 int temp;
5244                                 gpointer func;
5245                                 MonoJitICallInfo *info;
5246
5247                                 token = read32 (ip + 2);
5248                                 func = mono_method_get_wrapper_data (method, token);
5249                                 info = mono_find_jit_icall_by_addr (func);
5250                                 g_assert (info);
5251
5252                                 CHECK_STACK (info->sig->param_count);
5253                                 sp -= info->sig->param_count;
5254
5255                                 temp = mono_emit_jit_icall (cfg, bblock, info->func, sp, ip);
5256                                 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
5257                                         NEW_TEMPLOAD (cfg, *sp, temp);
5258                                         sp++;
5259                                 }
5260
5261                                 ip += 6;
5262                                 inline_costs += 10 * num_calls++;
5263
5264                                 break;
5265                         }
5266                         case CEE_MONO_LDPTR:
5267                                 CHECK_STACK_OVF (1);
5268                                 CHECK_OPSIZE (6);
5269                                 token = read32 (ip + 2);
5270                                 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
5271                                 ins->cil_code = ip;
5272                                 *sp++ = ins;
5273                                 ip += 6;
5274                                 inline_costs += 10 * num_calls++;
5275                                 break;
5276                         case CEE_MONO_VTADDR:
5277                                 CHECK_STACK (1);
5278                                 --sp;
5279                                 MONO_INST_NEW (cfg, ins, OP_VTADDR);
5280                                 ins->cil_code = ip;
5281                                 ins->type = STACK_MP;
5282                                 ins->inst_left = *sp;
5283                                 *sp++ = ins;
5284                                 ip += 2;
5285                                 break;
5286                         case CEE_MONO_NEWOBJ: {
5287                                 MonoInst *iargs [2];
5288                                 int temp;
5289                                 CHECK_STACK_OVF (1);
5290                                 CHECK_OPSIZE (6);
5291                                 token = read32 (ip + 2);
5292                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
5293                                 mono_class_init (klass);
5294                                 NEW_DOMAINCONST (cfg, iargs [0]);
5295                                 NEW_CLASSCONST (cfg, iargs [1], klass);
5296                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
5297                                 NEW_TEMPLOAD (cfg, *sp, temp);
5298                                 sp++;
5299                                 ip += 6;
5300                                 inline_costs += 10 * num_calls++;
5301                                 break;
5302                         }
5303                         case CEE_MONO_OBJADDR:
5304                                 CHECK_STACK (1);
5305                                 --sp;
5306                                 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
5307                                 ins->cil_code = ip;
5308                                 ins->type = STACK_MP;
5309                                 ins->inst_left = *sp;
5310                                 *sp++ = ins;
5311                                 ip += 2;
5312                                 break;
5313                         case CEE_MONO_LDNATIVEOBJ:
5314                                 CHECK_STACK (1);
5315                                 CHECK_OPSIZE (6);
5316                                 token = read32 (ip + 2);
5317                                 klass = mono_method_get_wrapper_data (method, token);
5318                                 g_assert (klass->valuetype);
5319                                 mono_class_init (klass);
5320                                 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
5321                                 sp [-1] = ins;
5322                                 ip += 6;
5323                                 break;
5324                         case CEE_MONO_RETOBJ:
5325                                 g_assert (cfg->ret);
5326                                 g_assert (method->signature->pinvoke); 
5327                                 CHECK_STACK (1);
5328                                 --sp;
5329                                 
5330                                 CHECK_OPSIZE (6);
5331                                 token = read32 (ip + 2);    
5332                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
5333
5334                                 NEW_RETLOADA (cfg, ins);
5335                                 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE);
5336                                 
5337                                 if (sp != stack_start)
5338                                         goto unverified;
5339                                 
5340                                 MONO_INST_NEW (cfg, ins, CEE_BR);
5341                                 ins->cil_code = ip;
5342                                 ins->inst_target_bb = end_bblock;
5343                                 MONO_ADD_INS (bblock, ins);
5344                                 link_bblock (cfg, bblock, end_bblock);
5345                                 start_new_bblock = 1;
5346                                 ip += 6;
5347                                 break;
5348                         case CEE_MONO_CISINST:
5349                         case CEE_MONO_CCASTCLASS: {
5350                                 int token;
5351                                 CHECK_STACK (1);
5352                                 --sp;
5353                                 CHECK_OPSIZE (6);
5354                                 token = read32 (ip + 2);
5355                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
5356                                 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_CISINST) ? OP_CISINST : OP_CCASTCLASS);
5357                                 ins->type = STACK_I4;
5358                                 ins->inst_left = *sp;
5359                                 ins->inst_newa_class = klass;
5360                                 ins->cil_code = ip;
5361                                 *sp++ = emit_tree (cfg, bblock, ins);
5362                                 ip += 6;
5363                                 break;
5364                         }
5365                         case CEE_MONO_SAVE_LMF:
5366                         case CEE_MONO_RESTORE_LMF:
5367 #ifdef MONO_ARCH_HAVE_LMF_OPS
5368                                 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_SAVE_LMF) ? OP_SAVE_LMF : OP_RESTORE_LMF);
5369                                 MONO_ADD_INS (bblock, ins);
5370                                 cfg->need_lmf_area = TRUE;
5371 #endif
5372                                 ip += 2;
5373                                 break;
5374                         default:
5375                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
5376                                 break;
5377                         }
5378                         break;
5379                 }
5380                 case CEE_PREFIX1: {
5381                         CHECK_OPSIZE (2);
5382                         switch (ip [1]) {
5383                         case CEE_ARGLIST: {
5384                                 /* somewhat similar to LDTOKEN */
5385                                 MonoInst *addr, *vtvar;
5386                                 CHECK_STACK_OVF (1);
5387                                 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL); 
5388
5389                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
5390                                 addr->cil_code = ip;
5391                                 MONO_INST_NEW (cfg, ins, OP_ARGLIST);
5392                                 ins->cil_code = ip;
5393                                 ins->inst_left = addr;
5394                                 MONO_ADD_INS (bblock, ins);
5395                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
5396                                 ins->cil_code = ip;
5397                                 *sp++ = ins;
5398                                 ip += 2;
5399                                 break;
5400                         }
5401                         case CEE_CEQ:
5402                         case CEE_CGT:
5403                         case CEE_CGT_UN:
5404                         case CEE_CLT:
5405                         case CEE_CLT_UN: {
5406                                 MonoInst *cmp;
5407                                 CHECK_STACK (2);
5408                                 /*
5409                                  * The following transforms:
5410                                  *    CEE_CEQ    into OP_CEQ
5411                                  *    CEE_CGT    into OP_CGT
5412                                  *    CEE_CGT_UN into OP_CGT_UN
5413                                  *    CEE_CLT    into OP_CLT
5414                                  *    CEE_CLT_UN into OP_CLT_UN
5415                                  */
5416                                 MONO_INST_NEW (cfg, cmp, 256 + ip [1]);
5417                                 
5418                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
5419                                 sp -= 2;
5420                                 cmp->inst_i0 = sp [0];
5421                                 cmp->inst_i1 = sp [1];
5422                                 cmp->cil_code = ip;
5423                                 type_from_op (cmp);
5424                                 CHECK_TYPE (cmp);
5425                                 if ((sp [0]->type == STACK_I8) || ((sizeof (gpointer) == 8) && ((sp [0]->type == STACK_PTR) || (sp [0]->type == STACK_OBJ) || (sp [0]->type == STACK_MP))))
5426                                         cmp->opcode = OP_LCOMPARE;
5427                                 else
5428                                         cmp->opcode = OP_COMPARE;
5429                                 ins->cil_code = ip;
5430                                 ins->type = STACK_I4;
5431                                 ins->inst_i0 = cmp;
5432                                 *sp++ = ins;
5433                                 /* spill it to reduce the expression complexity
5434                                  * and workaround bug 54209 
5435                                  */
5436                                 if (cmp->inst_left->type == STACK_I8) {
5437                                         --sp;
5438                                         *sp++ = emit_tree (cfg, bblock, ins);
5439                                 }
5440                                 ip += 2;
5441                                 break;
5442                         }
5443                         case CEE_LDFTN: {
5444                                 MonoInst *argconst;
5445                                 int temp;
5446
5447                                 CHECK_STACK_OVF (1);
5448                                 CHECK_OPSIZE (6);
5449                                 n = read32 (ip + 2);
5450                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
5451                                         cmethod = mono_method_get_wrapper_data (method, n);
5452                                 else {
5453                                         cmethod = mono_get_method_full (image, n, NULL, generic_context);
5454                                 }
5455
5456                                 mono_class_init (cmethod->klass);
5457                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5458
5459                                 NEW_METHODCONST (cfg, argconst, cmethod);
5460                                 if (method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
5461                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
5462                                 else
5463                                         temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn_nosync, &argconst, ip);
5464                                 NEW_TEMPLOAD (cfg, *sp, temp);
5465                                 sp ++;
5466                                 
5467                                 ip += 6;
5468                                 inline_costs += 10 * num_calls++;
5469                                 break;
5470                         }
5471                         case CEE_LDVIRTFTN: {
5472                                 MonoInst *args [2];
5473                                 int temp;
5474
5475                                 CHECK_STACK (1);
5476                                 CHECK_OPSIZE (6);
5477                                 n = read32 (ip + 2);
5478                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
5479                                         cmethod = mono_method_get_wrapper_data (method, n);
5480                                 else
5481                                         cmethod = mono_get_method_full (image, n, NULL, generic_context);
5482
5483                                 mono_class_init (cmethod->klass);
5484                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5485
5486                                 --sp;
5487                                 args [0] = *sp;
5488                                 NEW_METHODCONST (cfg, args [1], cmethod);
5489                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
5490                                 NEW_TEMPLOAD (cfg, *sp, temp);
5491                                 sp ++;
5492
5493                                 ip += 6;
5494                                 inline_costs += 10 * num_calls++;
5495                                 break;
5496                         }
5497                         case CEE_LDARG:
5498                                 CHECK_STACK_OVF (1);
5499                                 CHECK_OPSIZE (4);
5500                                 n = read16 (ip + 2);
5501                                 CHECK_ARG (n);
5502                                 NEW_ARGLOAD (cfg, ins, n);
5503                                 ins->cil_code = ip;
5504                                 *sp++ = ins;
5505                                 ip += 4;
5506                                 break;
5507                         case CEE_LDARGA:
5508                                 CHECK_STACK_OVF (1);
5509                                 CHECK_OPSIZE (4);
5510                                 n = read16 (ip + 2);
5511                                 CHECK_ARG (n);
5512                                 NEW_ARGLOADA (cfg, ins, n);
5513                                 ins->cil_code = ip;
5514                                 *sp++ = ins;
5515                                 ip += 4;
5516                                 break;
5517                         case CEE_STARG:
5518                                 CHECK_STACK (1);
5519                                 --sp;
5520                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5521                                 CHECK_OPSIZE (4);
5522                                 n = read16 (ip + 2);
5523                                 CHECK_ARG (n);
5524                                 NEW_ARGSTORE (cfg, ins, n, *sp);
5525                                 ins->cil_code = ip;
5526                                 if (ins->opcode == CEE_STOBJ) {
5527                                         NEW_ARGLOADA (cfg, ins, n);
5528                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
5529                                 } else
5530                                         MONO_ADD_INS (bblock, ins);
5531                                 ip += 4;
5532                                 break;
5533                         case CEE_LDLOC:
5534                                 CHECK_STACK_OVF (1);
5535                                 CHECK_OPSIZE (4);
5536                                 n = read16 (ip + 2);
5537                                 CHECK_LOCAL (n);
5538                                 NEW_LOCLOAD (cfg, ins, n);
5539                                 ins->cil_code = ip;
5540                                 *sp++ = ins;
5541                                 ip += 4;
5542                                 break;
5543                         case CEE_LDLOCA:
5544                                 CHECK_STACK_OVF (1);
5545                                 CHECK_OPSIZE (4);
5546                                 n = read16 (ip + 2);
5547                                 CHECK_LOCAL (n);
5548                                 NEW_LOCLOADA (cfg, ins, n);
5549                                 ins->cil_code = ip;
5550                                 *sp++ = ins;
5551                                 ip += 4;
5552                                 break;
5553                         case CEE_STLOC:
5554                                 CHECK_STACK (1);
5555                                 --sp;
5556                                 CHECK_OPSIZE (4);
5557                                 n = read16 (ip + 2);
5558                                 CHECK_LOCAL (n);
5559                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5560                                 NEW_LOCSTORE (cfg, ins, n, *sp);
5561                                 ins->cil_code = ip;
5562                                 if (ins->opcode == CEE_STOBJ) {
5563                                         NEW_LOCLOADA (cfg, ins, n);
5564                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
5565                                 } else
5566                                         MONO_ADD_INS (bblock, ins);
5567                                 ip += 4;
5568                                 inline_costs += 1;
5569                                 break;
5570                         case CEE_LOCALLOC:
5571                                 CHECK_STACK (1);
5572                                 --sp;
5573                                 if (sp != stack_start) 
5574                                         goto unverified;
5575                                 if (cfg->method != method) 
5576                                         /* 
5577                                          * Inlining this into a loop in a parent could lead to 
5578                                          * stack overflows which is different behavior than the
5579                                          * non-inlined case, thus disable inlining in this case.
5580                                          */
5581                                         goto inline_failure;
5582                                 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
5583                                 ins->inst_left = *sp;
5584                                 ins->cil_code = ip;
5585                                 ins->type = STACK_MP;
5586
5587                                 cfg->flags |= MONO_CFG_HAS_ALLOCA;
5588                                 if (header->init_locals)
5589                                         ins->flags |= MONO_INST_INIT;
5590
5591                                 *sp++ = ins;
5592                                 ip += 2;
5593                                 /* FIXME: set init flag if locals init is set in this method */
5594                                 break;
5595                         case CEE_ENDFILTER: {
5596                                 MonoExceptionClause *clause, *nearest;
5597                                 int cc, nearest_num;
5598
5599                                 CHECK_STACK (1);
5600                                 --sp;
5601                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
5602                                         goto unverified;
5603                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
5604                                 ins->inst_left = *sp;
5605                                 ins->cil_code = ip;
5606                                 MONO_ADD_INS (bblock, ins);
5607                                 start_new_bblock = 1;
5608                                 ip += 2;
5609
5610                                 nearest = NULL;
5611                                 nearest_num = 0;
5612                                 for (cc = 0; cc < header->num_clauses; ++cc) {
5613                                         clause = &header->clauses [cc];
5614                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
5615                                             (!nearest || (clause->data.filter_offset > nearest->data.filter_offset))) {
5616                                                 nearest = clause;
5617                                                 nearest_num = cc;
5618                                         }
5619                                 }
5620                                 g_assert (nearest);
5621                                 filter_lengths [nearest_num] = (ip - header->code) -  nearest->data.filter_offset;
5622
5623                                 break;
5624                         }
5625                         case CEE_UNALIGNED_:
5626                                 ins_flag |= MONO_INST_UNALIGNED;
5627                                 /* FIXME: record alignment? we can assume 1 for now */
5628                                 CHECK_OPSIZE (3);
5629                                 ip += 3;
5630                                 break;
5631                         case CEE_VOLATILE_:
5632                                 ins_flag |= MONO_INST_VOLATILE;
5633                                 ip += 2;
5634                                 break;
5635                         case CEE_TAIL_:
5636                                 ins_flag   |= MONO_INST_TAILCALL;
5637                                 cfg->flags |= MONO_CFG_HAS_TAIL;
5638                                 /* Can't inline tail calls at this time */
5639                                 inline_costs += 100000;
5640                                 ip += 2;
5641                                 break;
5642                         case CEE_INITOBJ:
5643                                 CHECK_STACK (1);
5644                                 --sp;
5645                                 CHECK_OPSIZE (6);
5646                                 token = read32 (ip + 2);
5647                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
5648                                         klass = mono_method_get_wrapper_data (method, token);
5649                                 else
5650                                         klass = mono_class_get_full (image, token, generic_context);
5651                                 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
5652                                         MonoInst *store, *load;
5653                                         NEW_PCONST (cfg, load, NULL);
5654                                         load->cil_code = ip;
5655                                         load->type = STACK_OBJ;
5656                                         MONO_INST_NEW (cfg, store, CEE_STIND_REF);
5657                                         store->cil_code = ip;
5658                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
5659                                         MONO_ADD_INS (bblock, store);
5660                                         store->inst_i0 = sp [0];
5661                                         store->inst_i1 = load;
5662                                 } else {
5663                                         handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
5664                                 }
5665                                 ip += 6;
5666                                 inline_costs += 1;
5667                                 break;
5668                         case CEE_CONSTRAINED_:
5669                                 /* FIXME: implement */
5670                                 CHECK_OPSIZE (6);
5671                                 token = read32 (ip + 2);
5672                                 constrained_call = mono_class_get_full (image, token, generic_context);
5673                                 ip += 6;
5674                                 break;
5675                         case CEE_CPBLK:
5676                         case CEE_INITBLK: {
5677                                 MonoInst *iargs [3];
5678                                 CHECK_STACK (3);
5679                                 sp -= 3;
5680                                 if ((cfg->opt & MONO_OPT_INTRINS) && (ip [1] == CEE_CPBLK) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5)) {
5681                                         MonoInst *copy;
5682                                         MONO_INST_NEW (cfg, copy, OP_MEMCPY);
5683                                         copy->inst_left = sp [0];
5684                                         copy->inst_right = sp [1];
5685                                         copy->cil_code = ip;
5686                                         copy->unused = n;
5687                                         MONO_ADD_INS (bblock, copy);
5688                                         ip += 2;
5689                                         break;
5690                                 }
5691                                 iargs [0] = sp [0];
5692                                 iargs [1] = sp [1];
5693                                 iargs [2] = sp [2];
5694                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
5695                                 if (ip [1] == CEE_CPBLK) {
5696                                         mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
5697                                 } else {
5698                                         mono_emit_jit_icall (cfg, bblock, helper_memset, iargs, ip);
5699                                 }
5700                                 ip += 2;
5701                                 inline_costs += 1;
5702                                 break;
5703                         }
5704                         case CEE_NO_:
5705                                 CHECK_OPSIZE (3);
5706                                 if (ip [2] & 0x1)
5707                                         ins_flag |= MONO_INST_NOTYPECHECK;
5708                                 if (ip [2] & 0x2)
5709                                         ins_flag |= MONO_INST_NORANGECHECK;
5710                                 /* we ignore the no-nullcheck for now since we
5711                                  * really do it explicitly only when doing callvirt->call
5712                                  */
5713                                 ip += 3;
5714                                 break;
5715                         case CEE_RETHROW: {
5716                                 MonoInst *load;
5717                                 /* FIXME: check we are in a catch handler */
5718                                 NEW_TEMPLOAD (cfg, load, cfg->exvar->inst_c0);
5719                                 load->cil_code = ip;
5720                                 MONO_INST_NEW (cfg, ins, OP_RETHROW);
5721                                 ins->inst_left = load;
5722                                 ins->cil_code = ip;
5723                                 MONO_ADD_INS (bblock, ins);
5724                                 sp = stack_start;
5725                                 start_new_bblock = 1;
5726                                 ip += 2;
5727                                 break;
5728                         }
5729                         case CEE_SIZEOF:
5730                                 CHECK_STACK_OVF (1);
5731                                 CHECK_OPSIZE (6);
5732                                 token = read32 (ip + 2);
5733                                 /* FIXXME: handle generics. */
5734                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
5735                                         MonoType *type = mono_type_create_from_typespec (image, token);
5736                                         token = mono_type_size (type, &align);
5737                                 } else {
5738                                         MonoClass *szclass = mono_class_get_full (image, token, generic_context);
5739                                         mono_class_init (szclass);
5740                                         token = mono_class_value_size (szclass, &align);
5741                                 }
5742                                 NEW_ICONST (cfg, ins, token);
5743                                 ins->cil_code = ip;
5744                                 *sp++= ins;
5745                                 ip += 6;
5746                                 break;
5747                         case CEE_REFANYTYPE:
5748                                 CHECK_STACK (1);
5749                                 MONO_INST_NEW (cfg, ins, OP_REFANYTYPE);
5750                                 --sp;
5751                                 ins->type = STACK_MP;
5752                                 ins->inst_left = *sp;
5753                                 ins->type = STACK_VTYPE;
5754                                 ins->klass = mono_defaults.typehandle_class;
5755                                 ins->cil_code = ip;
5756                                 ip += 2;
5757                                 *sp++ = ins;
5758                                 break;
5759                         case CEE_READONLY_:
5760                                 ip += 2;
5761                                 break;
5762                         default:
5763                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
5764                         }
5765                         break;
5766                 }
5767                 default:
5768                         g_error ("opcode 0x%02x not handled", *ip);
5769                 }
5770         }
5771         if (start_new_bblock != 1)
5772                 goto unverified;
5773
5774         bblock->cil_length = ip - bblock->cil_code;
5775         bblock->next_bb = end_bblock;
5776         link_bblock (cfg, bblock, end_bblock);
5777
5778         if (cfg->method == method && cfg->domainvar) {
5779                 
5780                 
5781                 MonoInst *store;
5782                 MonoInst *get_domain;
5783                 
5784                 if (! (get_domain = mono_arch_get_domain_intrinsic (cfg))) {
5785                         MonoCallInst *call;
5786                         
5787                         MONO_INST_NEW_CALL (cfg, call, CEE_CALL);
5788                         call->signature = helper_sig_domain_get;
5789                         call->inst.type = STACK_PTR;
5790                         call->fptr = mono_domain_get;
5791                         get_domain = (MonoInst*)call;
5792                 }
5793                 
5794                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
5795                 MONO_ADD_INS (init_localsbb, store);
5796         }
5797
5798         if (header->init_locals) {
5799                 MonoInst *store;
5800                 for (i = 0; i < header->num_locals; ++i) {
5801                         MonoType *ptype = header->locals [i];
5802                         int t = ptype->type;
5803                         if (t == MONO_TYPE_VALUETYPE && ptype->data.klass->enumtype)
5804                                 t = ptype->data.klass->enum_basetype->type;
5805                         /* FIXME: use initobj for valuetypes, handle pointers, long, float. */
5806                         if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
5807                                 NEW_ICONST (cfg, ins, 0);
5808                                 NEW_LOCSTORE (cfg, store, i, ins);
5809                                 MONO_ADD_INS (init_localsbb, store);
5810                         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
5811                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
5812                                 ins->type = STACK_I8;
5813                                 ins->inst_l = 0;
5814                                 NEW_LOCSTORE (cfg, store, i, ins);
5815                                 MONO_ADD_INS (init_localsbb, store);
5816                         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
5817                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
5818                                 ins->type = STACK_R8;
5819                                 ins->inst_p0 = (void*)&r8_0;
5820                                 NEW_LOCSTORE (cfg, store, i, ins);
5821                                 MONO_ADD_INS (init_localsbb, store);
5822                         } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
5823                                    ((t == MONO_TYPE_GENERICINST) && mono_metadata_generic_inst_is_valuetype (ptype->data.generic_inst))) {
5824                                 NEW_LOCLOADA (cfg, ins, i);
5825                                 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (ptype), NULL, NULL);
5826                                 break;
5827                         } else {
5828                                 NEW_PCONST (cfg, ins, NULL);
5829                                 NEW_LOCSTORE (cfg, store, i, ins);
5830                                 MONO_ADD_INS (init_localsbb, store);
5831                         }
5832                 }
5833         }
5834
5835         
5836         /* resolve backward branches in the middle of an existing basic block */
5837         for (tmp = bb_recheck; tmp; tmp = tmp->next) {
5838                 bblock = tmp->data;
5839                 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
5840                 tblock = find_previous (bbhash, start_bblock, bblock->cil_code);
5841                 if (tblock != start_bblock) {
5842                         int l;
5843                         split_bblock (cfg, tblock, bblock);
5844                         l = bblock->cil_code - header->code;
5845                         bblock->cil_length = tblock->cil_length - l;
5846                         tblock->cil_length = l;
5847                 } else {
5848                         g_print ("recheck failed.\n");
5849                 }
5850         }
5851
5852         /*
5853          * we compute regions here, because the length of filter clauses is not known in advance.
5854          * It is computed in the CEE_ENDFILTER case in the above switch statement
5855          */
5856         if (cfg->method == method) {
5857                 MonoBasicBlock *bb;
5858                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5859                         bb->region = mono_find_block_region (cfg, bb->real_offset, filter_lengths);
5860                         if (cfg->spvars)
5861                                 mono_create_spvar_for_region (cfg, bb->region);
5862                         if (cfg->verbose_level > 2)
5863                                 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
5864                 }
5865         } else {
5866                 g_hash_table_destroy (bbhash);
5867         }
5868
5869         dont_inline = g_list_remove (dont_inline, method);
5870         return inline_costs;
5871
5872  inline_failure:
5873         if (cfg->method != method) 
5874                 g_hash_table_destroy (bbhash);
5875         dont_inline = g_list_remove (dont_inline, method);
5876         return -1;
5877
5878  unverified:
5879         if (cfg->method != method) 
5880                 g_hash_table_destroy (bbhash);
5881         g_error ("Invalid IL code at IL%04x in %s: %s\n", ip - header->code, 
5882                  mono_method_full_name (method, TRUE), mono_disasm_code_one (NULL, method, ip, NULL));
5883         dont_inline = g_list_remove (dont_inline, method);
5884         return -1;
5885 }
5886
5887 void
5888 mono_print_tree (MonoInst *tree) {
5889         int arity;
5890
5891         if (!tree)
5892                 return;
5893
5894         arity = mono_burg_arity [tree->opcode];
5895
5896         printf (" %s%s", arity?"(":"",  mono_inst_name (tree->opcode));
5897
5898         switch (tree->opcode) {
5899         case OP_ICONST:
5900                 printf ("[%d]", tree->inst_c0);
5901                 break;
5902         case OP_I8CONST:
5903                 printf ("[%lld]", tree->inst_l);
5904                 break;
5905         case OP_R8CONST:
5906                 printf ("[%f]", *(double*)tree->inst_p0);
5907                 break;
5908         case OP_R4CONST:
5909                 printf ("[%f]", *(float*)tree->inst_p0);
5910                 break;
5911         case OP_ARG:
5912         case OP_LOCAL:
5913                 printf ("[%d]", tree->inst_c0);
5914                 break;
5915         case OP_REGOFFSET:
5916                 if (tree->inst_offset < 0)
5917                         printf ("[-0x%x(%s)]", -tree->inst_offset, mono_arch_regname (tree->inst_basereg));
5918                 else
5919                         printf ("[0x%x(%s)]", tree->inst_offset, mono_arch_regname (tree->inst_basereg));
5920                 break;
5921         case OP_REGVAR:
5922                 printf ("[%s]", mono_arch_regname (tree->dreg));
5923                 break;
5924         case CEE_NEWARR:
5925                 printf ("[%s]",  tree->inst_newa_class->name);
5926                 mono_print_tree (tree->inst_newa_len);
5927                 break;
5928         case CEE_CALL:
5929         case CEE_CALLVIRT:
5930         case OP_FCALL:
5931         case OP_FCALLVIRT:
5932         case OP_LCALL:
5933         case OP_LCALLVIRT:
5934         case OP_VCALL:
5935         case OP_VCALLVIRT:
5936         case OP_VOIDCALL:
5937         case OP_VOIDCALLVIRT: {
5938                 MonoCallInst *call = (MonoCallInst*)tree;
5939                 if (call->method)
5940                         printf ("[%s]", call->method->name);
5941                 break;
5942         }
5943         case OP_PHI: {
5944                 int i;
5945                 printf ("[%d (", tree->inst_c0);
5946                 for (i = 0; i < tree->inst_phi_args [0]; i++) {
5947                         if (i)
5948                                 printf (", ");
5949                         printf ("%d", tree->inst_phi_args [i + 1]);
5950                 }
5951                 printf (")]");
5952                 break;
5953         }
5954         case OP_RENAME:
5955         case OP_RETARG:
5956         case CEE_NOP:
5957         case CEE_JMP:
5958         case CEE_BREAK:
5959                 break;
5960         case OP_LOAD_MEMBASE:
5961         case OP_LOADI4_MEMBASE:
5962         case OP_LOADU4_MEMBASE:
5963         case OP_LOADU1_MEMBASE:
5964         case OP_LOADI1_MEMBASE:
5965         case OP_LOADU2_MEMBASE:
5966         case OP_LOADI2_MEMBASE:
5967                 printf ("[%s] <- [%s + 0x%x]", mono_arch_regname (tree->dreg), mono_arch_regname (tree->inst_basereg), tree->inst_offset);
5968                 break;
5969         case CEE_BR:
5970                 printf ("[B%d]", tree->inst_target_bb->block_num);
5971                 break;
5972         case CEE_SWITCH:
5973         case CEE_ISINST:
5974         case CEE_CASTCLASS:
5975         case OP_OUTARG:
5976         case OP_CALL_REG:
5977         case OP_FCALL_REG:
5978         case OP_LCALL_REG:
5979         case OP_VCALL_REG:
5980         case OP_VOIDCALL_REG:
5981                 mono_print_tree (tree->inst_left);
5982                 break;
5983         case CEE_BNE_UN:
5984         case CEE_BEQ:
5985         case CEE_BLT:
5986         case CEE_BLT_UN:
5987         case CEE_BGT:
5988         case CEE_BGT_UN:
5989         case CEE_BGE:
5990         case CEE_BGE_UN:
5991         case CEE_BLE:
5992         case CEE_BLE_UN:
5993                 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
5994                 mono_print_tree (tree->inst_left);
5995                 break;
5996         default:
5997                 if (!mono_arch_print_tree(tree, arity)) {
5998                         if (arity) {
5999                                 mono_print_tree (tree->inst_left);
6000                                 if (arity > 1)
6001                                         mono_print_tree (tree->inst_right);
6002                         }
6003                 }
6004                 break;
6005         }
6006
6007         if (arity)
6008                 printf (")");
6009 }
6010
6011 void
6012 mono_print_tree_nl (MonoInst *tree)
6013 {
6014         mono_print_tree (tree);
6015         printf ("\n");
6016 }
6017
6018 #define make_icall_sig mono_create_icall_signature
6019
6020 static void
6021 create_helper_signature (void)
6022 {
6023         /* MonoArray * mono_array_new (MonoDomain *domain, MonoClass *klass, gint32 len) */
6024         helper_sig_newarr = make_icall_sig ("object ptr ptr int32");
6025
6026         /* MonoArray * mono_array_new_specific (MonoVTable *vtable, guint32 len) */
6027         helper_sig_newarr_specific = make_icall_sig ("object ptr int32");
6028
6029         /* MonoObject * mono_object_new (MonoDomain *domain, MonoClass *klass) */
6030         helper_sig_object_new = make_icall_sig ("object ptr ptr");
6031
6032         /* MonoObject * mono_object_new_specific (MonoVTable *vtable) */
6033         helper_sig_object_new_specific = make_icall_sig ("object ptr");
6034
6035         /* void* mono_method_compile (MonoMethod*) */
6036         helper_sig_compile = make_icall_sig ("ptr ptr");
6037
6038         /* void* mono_ldvirtfn (MonoObject *, MonoMethod*) */
6039         helper_sig_compile_virt = make_icall_sig ("ptr object ptr");
6040
6041         /* MonoString* mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 str_index) */
6042         helper_sig_ldstr = make_icall_sig ("object ptr ptr int32");
6043
6044         /* MonoDomain *mono_domain_get (void) */
6045         helper_sig_domain_get = make_icall_sig ("ptr");
6046
6047         /* void stelem_ref (MonoArray *, int index, MonoObject *) */
6048         helper_sig_stelem_ref = make_icall_sig ("void ptr int32 object");
6049
6050         /* void stelem_ref_check (MonoArray *, MonoObject *) */
6051         helper_sig_stelem_ref_check = make_icall_sig ("void object object");
6052
6053         /* long amethod (long, long) */
6054         helper_sig_long_long_long = make_icall_sig ("long long long");
6055
6056         /* object  amethod (intptr) */
6057         helper_sig_obj_ptr = make_icall_sig ("object ptr");
6058
6059         helper_sig_obj_ptr_ptr = make_icall_sig ("object ptr ptr");
6060
6061         helper_sig_obj_obj_ptr_ptr = make_icall_sig ("object object ptr ptr");
6062
6063         helper_sig_void_void = make_icall_sig ("void");
6064
6065         /* void amethod (intptr) */
6066         helper_sig_void_ptr = make_icall_sig ("void ptr");
6067
6068         /* void amethod (MonoObject *obj) */
6069         helper_sig_void_obj = make_icall_sig ("void object");
6070
6071         /* void amethod (MonoObject *obj, void *ptr, int i) */
6072         helper_sig_void_obj_ptr_int = make_icall_sig ("void object ptr int");
6073
6074         helper_sig_void_obj_ptr_ptr_obj = make_icall_sig ("void object ptr ptr object");
6075
6076         /* intptr amethod (void) */
6077         helper_sig_ptr_void = make_icall_sig ("ptr");
6078
6079         /* object amethod (void) */
6080         helper_sig_obj_void = make_icall_sig ("object");
6081
6082         /* void  amethod (intptr, intptr) */
6083         helper_sig_void_ptr_ptr = make_icall_sig ("void ptr ptr");
6084
6085         /* void  amethod (intptr, intptr, intptr) */
6086         helper_sig_void_ptr_ptr_ptr = make_icall_sig ("void ptr ptr ptr");
6087
6088         /* intptr  amethod (intptr, intptr) */
6089         helper_sig_ptr_ptr_ptr = make_icall_sig ("ptr ptr ptr");
6090
6091         /* IntPtr  amethod (object) */
6092         helper_sig_ptr_obj = make_icall_sig ("ptr object");
6093
6094         /* IntPtr  amethod (object, int) */
6095         helper_sig_ptr_obj_int = make_icall_sig ("ptr object int");
6096
6097         /* IntPtr  amethod (int) */
6098         helper_sig_ptr_int = make_icall_sig ("ptr int32");
6099
6100         /* long amethod (long, guint32) */
6101         helper_sig_long_long_int = make_icall_sig ("long long int32");
6102
6103         /* ulong amethod (double) */
6104         helper_sig_ulong_double = make_icall_sig ("ulong double");
6105
6106         /* long amethod (double) */
6107         helper_sig_long_double = make_icall_sig ("long double");
6108
6109         /* double amethod (long) */
6110         helper_sig_double_long = make_icall_sig ("double long");
6111
6112         /* double amethod (int) */
6113         helper_sig_double_int = make_icall_sig ("double int32");
6114
6115         /* float amethod (long) */
6116         helper_sig_float_long = make_icall_sig ("float long");
6117
6118         /* double amethod (double, double) */
6119         helper_sig_double_double_double = make_icall_sig ("double double double");
6120
6121         /* uint amethod (double) */
6122         helper_sig_uint_double = make_icall_sig ("uint32 double");
6123
6124         /* int amethod (double) */
6125         helper_sig_int_double = make_icall_sig ("int32 double");
6126
6127         /* void  initobj (intptr, int size) */
6128         helper_sig_initobj = make_icall_sig ("void ptr int32");
6129
6130         /* void  memcpy (intptr, intptr, int size) */
6131         helper_sig_memcpy = make_icall_sig ("void ptr ptr int32");
6132
6133         /* void  memset (intptr, int val, int size) */
6134         helper_sig_memset = make_icall_sig ("void ptr int32 int32");
6135
6136         helper_sig_class_init_trampoline = make_icall_sig ("void");
6137 }
6138
6139 gconstpointer
6140 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
6141 {
6142         char *name;
6143         MonoMethod *wrapper;
6144         gconstpointer code;
6145         
6146         if (callinfo->wrapper)
6147                 return callinfo->wrapper;
6148         
6149         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
6150         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func);
6151         /* Must be domain neutral since there is only one copy */
6152         code = mono_jit_compile_method_with_opt (wrapper, default_opt | MONO_OPT_SHARED);
6153
6154         if (!callinfo->wrapper) {
6155                 callinfo->wrapper = code;
6156                 mono_register_jit_icall_wrapper (callinfo, code);
6157                 mono_debug_add_icall_wrapper (wrapper, callinfo);
6158         }
6159
6160         g_free (name);
6161         return callinfo->wrapper;
6162 }
6163
6164 gpointer
6165 mono_create_class_init_trampoline (MonoVTable *vtable)
6166 {
6167         gpointer code;
6168
6169         /* previously created trampoline code */
6170         mono_domain_lock (vtable->domain);
6171         code = 
6172                 mono_g_hash_table_lookup (vtable->domain->class_init_trampoline_hash,
6173                                                                   vtable);
6174         mono_domain_unlock (vtable->domain);
6175         if (code)
6176                 return code;
6177
6178         code = mono_arch_create_class_init_trampoline (vtable);
6179
6180         /* store trampoline address */
6181         mono_domain_lock (vtable->domain);
6182         mono_g_hash_table_insert (vtable->domain->class_init_trampoline_hash,
6183                                                           vtable, code);
6184         mono_domain_unlock (vtable->domain);
6185
6186         EnterCriticalSection (&jit_mutex);
6187         if (!class_init_hash_addr)
6188                 class_init_hash_addr = g_hash_table_new (NULL, NULL);
6189         g_hash_table_insert (class_init_hash_addr, code, vtable);
6190         LeaveCriticalSection (&jit_mutex);
6191
6192         return code;
6193 }
6194
6195 gpointer
6196 mono_create_jump_trampoline (MonoDomain *domain, MonoMethod *method, 
6197                                                          gboolean add_sync_wrapper)
6198 {
6199         MonoJitInfo *ji;
6200         gpointer code;
6201
6202         if (add_sync_wrapper && method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
6203                 return mono_create_jump_trampoline (domain, mono_marshal_get_synchronized_wrapper (method), FALSE);
6204
6205         code = mono_jit_find_compiled_method (domain, method);
6206         if (code)
6207                 return code;
6208
6209         mono_domain_lock (domain);
6210         code = mono_g_hash_table_lookup (domain->jump_trampoline_hash, method);
6211         mono_domain_unlock (domain);
6212         if (code)
6213                 return code;
6214
6215         ji = mono_arch_create_jump_trampoline (method);
6216
6217         /*
6218          * mono_delegate_ctor needs to find the method metadata from the 
6219          * trampoline address, so we save it here.
6220          */
6221
6222         mono_jit_info_table_add (mono_get_root_domain (), ji);
6223
6224         mono_domain_lock (domain);
6225         mono_g_hash_table_insert (domain->jump_trampoline_hash, method, ji->code_start);
6226         mono_domain_unlock (domain);
6227
6228         return ji->code_start;
6229 }
6230
6231 gpointer
6232 mono_create_jit_trampoline (MonoMethod *method)
6233 {
6234         MonoDomain *domain = mono_domain_get ();
6235         gpointer tramp;
6236
6237         /* Trampoline are domain specific, so cache only the one used in the root domain */
6238         if ((domain == mono_get_root_domain ()) && method->info)
6239                 return method->info;
6240
6241         if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
6242                 return mono_create_jit_trampoline (mono_marshal_get_synchronized_wrapper (method));
6243
6244         tramp = mono_arch_create_jit_trampoline (method);
6245         if (domain == mono_get_root_domain ())
6246                 method->info = tramp;
6247
6248         return tramp;
6249 }       
6250
6251 MonoVTable*
6252 mono_find_class_init_trampoline_by_addr (gconstpointer addr)
6253 {
6254         MonoVTable *res;
6255
6256         EnterCriticalSection (&jit_mutex);
6257         if (class_init_hash_addr)
6258                 res = g_hash_table_lookup (class_init_hash_addr, addr);
6259         else
6260                 res = NULL;
6261         LeaveCriticalSection (&jit_mutex);
6262         return res;
6263 }
6264
6265 static void
6266 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
6267 {
6268         if (!domain->dynamic_code_hash)
6269                 domain->dynamic_code_hash = g_hash_table_new (NULL, NULL);
6270         g_hash_table_insert (domain->dynamic_code_hash, method, ji);
6271 }
6272
6273 static MonoJitDynamicMethodInfo*
6274 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
6275 {
6276         MonoJitDynamicMethodInfo *res;
6277
6278         if (domain->dynamic_code_hash)
6279                 res = g_hash_table_lookup (domain->dynamic_code_hash, method);
6280         else
6281                 res = NULL;
6282         return res;
6283 }
6284
6285 void
6286 mono_register_opcode_emulation (int opcode, const char *name, MonoMethodSignature *sig, gpointer func, gboolean no_throw)
6287 {
6288         MonoJitICallInfo *info;
6289
6290         if (!emul_opcode_map)
6291                 emul_opcode_map = g_new0 (MonoJitICallInfo*, OP_LAST + 1);
6292
6293         g_assert (!sig->hasthis);
6294         g_assert (sig->param_count < 3);
6295
6296         info = mono_register_jit_icall (func, name, sig, no_throw);
6297
6298         emul_opcode_map [opcode] = info;
6299 }
6300
6301 static void
6302 decompose_foreach (MonoInst *tree, gpointer data) 
6303 {
6304         static MonoJitICallInfo *newarr_info = NULL;
6305         static MonoJitICallInfo *newarr_specific_info = NULL;
6306         MonoJitICallInfo *info;
6307         int i;
6308
6309         switch (tree->opcode) {
6310         case CEE_NEWARR: {
6311                 MonoCompile *cfg = data;
6312                 MonoInst *iargs [3];
6313
6314                 if (!newarr_info) {
6315                         newarr_info = mono_find_jit_icall_by_addr (mono_array_new);
6316                         g_assert (newarr_info);
6317                         newarr_specific_info = mono_find_jit_icall_by_addr (mono_array_new_specific);
6318                         g_assert (newarr_specific_info);
6319                 }
6320
6321                 if (cfg->opt & MONO_OPT_SHARED) {
6322                         NEW_DOMAINCONST (cfg, iargs [0]);
6323                         NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
6324                         iargs [2] = tree->inst_newa_len;
6325
6326                         info = newarr_info;
6327                 }
6328                 else {
6329                         MonoVTable *vtable = mono_class_vtable (cfg->domain, mono_array_class_get (tree->inst_newa_class, 1));
6330
6331                         NEW_VTABLECONST (cfg, iargs [0], vtable);
6332                         iargs [1] = tree->inst_newa_len;
6333
6334                         info = newarr_specific_info;
6335                 }
6336
6337                 mono_emulate_opcode (cfg, tree, iargs, info);
6338
6339                 /* Need to decompose arguments after the the opcode is decomposed */
6340                 for (i = 0; i < info->sig->param_count; ++i)
6341                         dec_foreach (iargs [i], cfg);
6342                 break;
6343         }
6344
6345         default:
6346                 break;
6347         }
6348 }
6349
6350 void
6351 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
6352
6353         switch (mono_burg_arity [tree->opcode]) {
6354         case 0: break;
6355         case 1: 
6356                 mono_inst_foreach (tree->inst_left, func, data);
6357                 break;
6358         case 2: 
6359                 mono_inst_foreach (tree->inst_left, func, data);
6360                 mono_inst_foreach (tree->inst_right, func, data);
6361                 break;
6362         default:
6363                 g_assert_not_reached ();
6364         }
6365         func (tree, data);
6366 }
6367
6368 G_GNUC_UNUSED
6369 static void
6370 mono_print_bb_code (MonoBasicBlock *bb) {
6371         if (bb->code) {
6372                 MonoInst *c = bb->code;
6373                 while (c) {
6374                         mono_print_tree (c);
6375                         g_print ("\n");
6376                         c = c->next;
6377                 }
6378         }
6379 }
6380
6381 static void
6382 print_dfn (MonoCompile *cfg) {
6383         int i, j;
6384         char *code;
6385         MonoBasicBlock *bb;
6386
6387         g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
6388
6389         for (i = 0; i < cfg->num_bblocks; ++i) {
6390                 bb = cfg->bblocks [i];
6391                 /*if (bb->cil_code) {
6392                         char* code1, *code2;
6393                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
6394                         if (bb->last_ins->cil_code)
6395                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
6396                         else
6397                                 code2 = g_strdup ("");
6398
6399                         code1 [strlen (code1) - 1] = 0;
6400                         code = g_strdup_printf ("%s -> %s", code1, code2);
6401                         g_free (code1);
6402                         g_free (code2);
6403                 } else*/
6404                         code = g_strdup ("\n");
6405                 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
6406                 if (bb->code) {
6407                         MonoInst *c = bb->code;
6408                         while (c) {
6409                                 mono_print_tree (c);
6410                                 g_print ("\n");
6411                                 c = c->next;
6412                         }
6413                 } else {
6414
6415                 }
6416
6417                 g_print ("\tprev:");
6418                 for (j = 0; j < bb->in_count; ++j) {
6419                         g_print (" BB%d", bb->in_bb [j]->block_num);
6420                 }
6421                 g_print ("\t\tsucc:");
6422                 for (j = 0; j < bb->out_count; ++j) {
6423                         g_print (" BB%d", bb->out_bb [j]->block_num);
6424                 }
6425                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
6426
6427                 if (bb->idom)
6428                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
6429
6430                 if (bb->dominators)
6431                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
6432                 if (bb->dfrontier)
6433                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
6434                 g_free (code);
6435         }
6436
6437         g_print ("\n");
6438 }
6439
6440 void
6441 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
6442 {
6443         inst->next = NULL;
6444         if (bb->last_ins) {
6445                 g_assert (bb->code);
6446                 bb->last_ins->next = inst;
6447                 bb->last_ins = inst;
6448         } else {
6449                 bb->last_ins = bb->code = inst;
6450         }
6451 }
6452
6453 void
6454 mono_destroy_compile (MonoCompile *cfg)
6455 {
6456         //mono_mempool_stats (cfg->mempool);
6457         g_hash_table_destroy (cfg->bb_hash);
6458         mono_free_loop_info (cfg);
6459         if (cfg->rs)
6460                 mono_regstate_free (cfg->rs);
6461         if (cfg->spvars)
6462                 g_hash_table_destroy (cfg->spvars);
6463         mono_mempool_destroy (cfg->mempool);
6464         g_list_free (cfg->ldstr_list);
6465
6466         g_free (cfg->varinfo);
6467         g_free (cfg->vars);
6468         g_free (cfg);
6469 }
6470
6471 #ifdef HAVE_KW_THREAD
6472 static __thread gpointer mono_lmf_addr;
6473 #endif
6474
6475 MonoLMF **
6476 mono_get_lmf_addr (void)
6477 {
6478 #ifdef HAVE_KW_THREAD
6479         return mono_lmf_addr;
6480 #else
6481         MonoJitTlsData *jit_tls;
6482
6483         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
6484                 return &jit_tls->lmf;
6485
6486         g_assert_not_reached ();
6487         return NULL;
6488 #endif
6489 }
6490
6491 /**
6492  * mono_thread_abort:
6493  * @obj: exception object
6494  *
6495  * abort the thread, print exception information and stack trace
6496  */
6497 static void
6498 mono_thread_abort (MonoObject *obj)
6499 {
6500         /* MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id); */
6501         
6502         /* handle_remove should be eventually called for this thread, too
6503         g_free (jit_tls);*/
6504
6505         mono_thread_exit ();
6506 }
6507
6508 static void*
6509 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
6510 {
6511         MonoJitTlsData *jit_tls;
6512         MonoLMF *lmf;
6513
6514         jit_tls = TlsGetValue (mono_jit_tls_id);
6515         if (jit_tls)
6516                 return jit_tls;
6517
6518         jit_tls = g_new0 (MonoJitTlsData, 1);
6519
6520         TlsSetValue (mono_jit_tls_id, jit_tls);
6521
6522         jit_tls->abort_func = abort_func;
6523         jit_tls->end_of_stack = stack_start;
6524
6525         lmf = g_new0 (MonoLMF, 1);
6526         lmf->ebp = -1;
6527
6528         jit_tls->lmf = jit_tls->first_lmf = lmf;
6529
6530 #ifdef HAVE_KW_THREAD
6531         mono_lmf_addr = &jit_tls->lmf;
6532 #endif
6533
6534         mono_arch_setup_jit_tls_data (jit_tls);
6535
6536         return jit_tls;
6537 }
6538
6539 static void
6540 mono_thread_start_cb (guint32 tid, gpointer stack_start, gpointer func)
6541 {
6542         MonoThread *thread;
6543         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
6544         thread = mono_thread_current ();
6545         if (thread)
6546                 thread->jit_data = jit_tls;
6547 }
6548
6549 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
6550
6551 static void
6552 mono_thread_abort_dummy (MonoObject *obj)
6553 {
6554   if (mono_thread_attach_aborted_cb)
6555     mono_thread_attach_aborted_cb (obj);
6556   else
6557     mono_thread_abort (obj);
6558 }
6559
6560 static void
6561 mono_thread_attach_cb (guint32 tid, gpointer stack_start)
6562 {
6563         MonoThread *thread;
6564         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
6565         thread = mono_thread_current ();
6566         if (thread)
6567                 thread->jit_data = jit_tls;
6568 }
6569
6570 static void
6571 mini_thread_cleanup (MonoThread *thread)
6572 {
6573         MonoJitTlsData *jit_tls = thread->jit_data;
6574
6575         if (jit_tls) {
6576                 mono_arch_free_jit_tls_data (jit_tls);
6577                 g_free (jit_tls->first_lmf);
6578                 g_free (jit_tls);
6579                 thread->jit_data = NULL;
6580         }
6581 }
6582
6583 void
6584 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
6585 {
6586         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
6587
6588         ji->ip.i = ip;
6589         ji->type = type;
6590         ji->data.target = target;
6591         ji->next = cfg->patch_info;
6592
6593         cfg->patch_info = ji;
6594 }
6595
6596 void
6597 mono_remove_patch_info (MonoCompile *cfg, int ip)
6598 {
6599         MonoJumpInfo **ji = &cfg->patch_info;
6600
6601         while (*ji) {
6602                 if ((*ji)->ip.i == ip)
6603                         *ji = (*ji)->next;
6604                 else
6605                         ji = &((*ji)->next);
6606         }
6607 }
6608
6609 gpointer
6610 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
6611 {
6612         unsigned char *ip = patch_info->ip.i + code;
6613         gconstpointer target = NULL;
6614
6615         switch (patch_info->type) {
6616         case MONO_PATCH_INFO_BB:
6617                 target = patch_info->data.bb->native_offset + code;
6618                 break;
6619         case MONO_PATCH_INFO_ABS:
6620                 target = patch_info->data.target;
6621                 break;
6622         case MONO_PATCH_INFO_LABEL:
6623                 target = patch_info->data.inst->inst_c0 + code;
6624                 break;
6625         case MONO_PATCH_INFO_IP:
6626                 target = ip;
6627                 break;
6628         case MONO_PATCH_INFO_METHOD_REL:
6629                 target = code + patch_info->data.offset;
6630                 break;
6631         case MONO_PATCH_INFO_INTERNAL_METHOD: {
6632                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
6633                 if (!mi) {
6634                         g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
6635                         g_assert_not_reached ();
6636                 }
6637                 target = mono_icall_get_wrapper (mi);
6638                 break;
6639         }
6640         case MONO_PATCH_INFO_METHOD_JUMP: {
6641                 GSList *list;
6642
6643                 /* get the trampoline to the method from the domain */
6644                 target = mono_create_jump_trampoline (domain, patch_info->data.method, TRUE);
6645                 if (!domain->jump_target_hash)
6646                         domain->jump_target_hash = g_hash_table_new (NULL, NULL);
6647                 list = g_hash_table_lookup (domain->jump_target_hash, patch_info->data.method);
6648                 list = g_slist_prepend (list, ip);
6649                 g_hash_table_insert (domain->jump_target_hash, patch_info->data.method, list);
6650                 break;
6651         }
6652         case MONO_PATCH_INFO_METHOD:
6653                 if (patch_info->data.method == method) {
6654                         target = code;
6655                 } else
6656                         /* get the trampoline to the method from the domain */
6657                         target = mono_create_jit_trampoline (patch_info->data.method);
6658                 break;
6659         case MONO_PATCH_INFO_SWITCH: {
6660                 gpointer *jump_table;
6661                 int i;
6662
6663                 if (method->dynamic) {
6664                         jump_table = mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->table_size);
6665                 } else {
6666                         mono_domain_lock (domain);
6667                         jump_table = mono_code_manager_reserve (domain->code_mp, sizeof (gpointer) * patch_info->table_size);
6668                         mono_domain_unlock (domain);
6669                 }
6670
6671                 for (i = 0; i < patch_info->table_size; i++) {
6672                         jump_table [i] = code + (int)patch_info->data.table [i];
6673                 }
6674                 target = jump_table;
6675                 break;
6676         }
6677         case MONO_PATCH_INFO_METHODCONST:
6678         case MONO_PATCH_INFO_CLASS:
6679         case MONO_PATCH_INFO_IMAGE:
6680         case MONO_PATCH_INFO_FIELD:
6681                 target = patch_info->data.target;
6682                 break;
6683         case MONO_PATCH_INFO_IID:
6684                 mono_class_init (patch_info->data.klass);
6685                 target = (gpointer)patch_info->data.klass->interface_id;
6686                 break;
6687         case MONO_PATCH_INFO_VTABLE:
6688                 target = mono_class_vtable (domain, patch_info->data.klass);
6689                 break;
6690         case MONO_PATCH_INFO_CLASS_INIT:
6691                 target = mono_create_class_init_trampoline (mono_class_vtable (domain, patch_info->data.klass));
6692                 break;
6693         case MONO_PATCH_INFO_SFLDA: {
6694                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
6695                 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && mono_class_needs_cctor_run (vtable->klass, method))
6696                         /* Done by the generated code */
6697                         ;
6698                 else {
6699                         if (run_cctors)
6700                                 mono_runtime_class_init (vtable);
6701                 }
6702                 target = (char*)vtable->data + patch_info->data.field->offset;
6703                 break;
6704         }
6705         case MONO_PATCH_INFO_R4:
6706         case MONO_PATCH_INFO_R8:
6707                 target = patch_info->data.target;
6708                 break;
6709         case MONO_PATCH_INFO_EXC_NAME:
6710                 target = patch_info->data.name;
6711                 break;
6712         case MONO_PATCH_INFO_LDSTR:
6713                 target =
6714                         mono_ldstr (domain, patch_info->data.token->image, 
6715                                                 mono_metadata_token_index (patch_info->data.token->token));
6716                 break;
6717         case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
6718                 gpointer handle;
6719                 MonoClass *handle_class;
6720
6721                 handle = mono_ldtoken (patch_info->data.token->image, 
6722                                        patch_info->data.token->token, &handle_class, NULL);
6723                 mono_class_init (handle_class);
6724                 mono_class_init (mono_class_from_mono_type (handle));
6725
6726                 target =
6727                         mono_type_get_object (domain, handle);
6728                 break;
6729         }
6730         case MONO_PATCH_INFO_LDTOKEN: {
6731                 gpointer handle;
6732                 MonoClass *handle_class;
6733                 
6734                 handle = mono_ldtoken (patch_info->data.token->image,
6735                                        patch_info->data.token->token, &handle_class, NULL);
6736                 mono_class_init (handle_class);
6737                 
6738                 target = handle;
6739                 break;
6740         }
6741         case MONO_PATCH_INFO_BB_OVF:
6742         case MONO_PATCH_INFO_EXC_OVF:
6743                 break;
6744         default:
6745                 g_assert_not_reached ();
6746         }
6747
6748         return (gpointer)target;
6749 }
6750
6751 static void
6752 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
6753         MonoJitICallInfo *info;
6754
6755         decompose_foreach (tree, cfg);
6756
6757         switch (mono_burg_arity [tree->opcode]) {
6758         case 0: break;
6759         case 1: 
6760                 dec_foreach (tree->inst_left, cfg);
6761
6762                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
6763                         MonoInst *iargs [2];
6764                 
6765                         iargs [0] = tree->inst_left;
6766
6767                         mono_emulate_opcode (cfg, tree, iargs, info);
6768                         return;
6769                 }
6770
6771                 break;
6772         case 2:
6773 #ifdef MONO_ARCH_BIGMUL_INTRINS
6774                 if (tree->opcode == OP_LMUL
6775                                 && (cfg->opt & MONO_OPT_INTRINS)
6776                                 && (tree->inst_left->opcode == CEE_CONV_I8 
6777                                         || tree->inst_left->opcode == CEE_CONV_U8)
6778                                 && tree->inst_left->inst_left->type == STACK_I4
6779                                 && (tree->inst_right->opcode == CEE_CONV_I8 
6780                                         || tree->inst_right->opcode == CEE_CONV_U8)
6781                                 && tree->inst_right->inst_left->type == STACK_I4
6782                                 && tree->inst_left->opcode == tree->inst_right->opcode) {
6783                         tree->opcode = (tree->inst_left->opcode == CEE_CONV_I8 ? OP_BIGMUL: OP_BIGMUL_UN);
6784                         tree->inst_left = tree->inst_left->inst_left;
6785                         tree->inst_right = tree->inst_right->inst_left;
6786                         dec_foreach (tree, cfg);
6787                 } else 
6788 #endif
6789                         if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
6790                         MonoInst *iargs [2];
6791                 
6792                         iargs [0] = tree->inst_i0;
6793                         iargs [1] = tree->inst_i1;
6794                 
6795                         mono_emulate_opcode (cfg, tree, iargs, info);
6796
6797                         dec_foreach (iargs [0], cfg);
6798                         dec_foreach (iargs [1], cfg);
6799                         return;
6800                 } else {
6801                         dec_foreach (tree->inst_left, cfg);
6802                         dec_foreach (tree->inst_right, cfg);
6803                 }
6804                 break;
6805         default:
6806                 g_assert_not_reached ();
6807         }
6808 }
6809
6810 static void
6811 decompose_pass (MonoCompile *cfg) {
6812         MonoBasicBlock *bb;
6813
6814         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
6815                 MonoInst *tree;
6816                 cfg->cbb = bb;
6817                 cfg->prev_ins = NULL;
6818                 for (tree = cfg->cbb->code; tree; tree = tree->next) {
6819                         dec_foreach (tree, cfg);
6820                         cfg->prev_ins = tree;
6821                 }
6822         }
6823 }
6824
6825 static void
6826 nullify_basic_block (MonoBasicBlock *bb) 
6827 {
6828         bb->in_count = 0;
6829         bb->out_count = 0;
6830         bb->in_bb = NULL;
6831         bb->out_bb = NULL;
6832         bb->next_bb = NULL;
6833         bb->code = bb->last_ins = NULL;
6834         bb->cil_code = NULL;
6835 }
6836
6837 static void 
6838 replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
6839 {
6840         int i;
6841
6842         for (i = 0; i < bb->out_count; i++) {
6843                 MonoBasicBlock *ob = bb->out_bb [i];
6844                 if (ob == orig) {
6845                         if (!repl) {
6846                                 if (bb->out_count > 1) {
6847                                         bb->out_bb [i] = bb->out_bb [bb->out_count - 1];
6848                                 }
6849                                 bb->out_count--;
6850                         } else {
6851                                 bb->out_bb [i] = repl;
6852                         }
6853                 }
6854         }
6855 }
6856
6857 static void 
6858 replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
6859 {
6860         int i;
6861
6862         for (i = 0; i < bb->in_count; i++) {
6863                 MonoBasicBlock *ib = bb->in_bb [i];
6864                 if (ib == orig) {
6865                         if (!repl) {
6866                                 if (bb->in_count > 1) {
6867                                         bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
6868                                 }
6869                                 bb->in_count--;
6870                         } else {
6871                                 bb->in_bb [i] = repl;
6872                         }
6873                 }
6874         }
6875 }
6876
6877 static void 
6878 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
6879 {
6880         int i, j;
6881
6882         for (i = 0; i < bb->out_count; i++) {
6883                 MonoBasicBlock *ob = bb->out_bb [i];
6884                 for (j = 0; j < ob->in_count; j++) {
6885                         if (ob->in_bb [j] == orig) {
6886                                 ob->in_bb [j] = repl;
6887                         }
6888                 }
6889         }
6890
6891 }
6892
6893
6894 static void
6895 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn) 
6896 {
6897         bb->out_count = bbn->out_count;
6898         bb->out_bb = bbn->out_bb;
6899
6900         replace_basic_block (bb, bbn, bb);
6901
6902         if (bb->last_ins) {
6903                 if (bbn->code) {
6904                         bb->last_ins->next = bbn->code;
6905                         bb->last_ins = bbn->last_ins;
6906                 }
6907         } else {
6908                 bb->code = bbn->code;
6909                 bb->last_ins = bbn->last_ins;
6910         }
6911         bb->next_bb = bbn->next_bb;
6912         nullify_basic_block (bbn);
6913 }
6914
6915 /*
6916  * Optimizes the branches on the Control Flow Graph
6917  *
6918  */
6919 static void
6920 optimize_branches (MonoCompile *cfg)
6921 {
6922         int i, changed = FALSE;
6923         MonoBasicBlock *bb, *bbn;
6924         guint32 niterations;
6925
6926         /*
6927          * Some crazy loops could cause the code below to go into an infinite
6928          * loop, see bug #53003 for an example. To prevent this, we put an upper
6929          * bound on the number of iterations.
6930          */
6931         niterations = 1000;
6932         do {
6933                 changed = FALSE;
6934                 niterations --;
6935
6936                 /* we skip the entry block (exit is handled specially instead ) */
6937                 for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
6938
6939                         /* dont touch code inside exception clauses */
6940                         if (bb->region != -1)
6941                                 continue;
6942
6943                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
6944                                 if (cfg->verbose_level > 2)
6945                                         g_print ("nullify block triggered %d\n", bbn->block_num);
6946
6947                                 bb->next_bb = bbn->next_bb;
6948
6949                                 for (i = 0; i < bbn->out_count; i++)
6950                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
6951
6952                                 nullify_basic_block (bbn);                      
6953                                 changed = TRUE;
6954                         }
6955
6956                         if (bb->out_count == 1) {
6957                                 bbn = bb->out_bb [0];
6958
6959                                 /* conditional branches where true and false targets are the same can be also replaced with CEE_BR */
6960                                 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins)) {
6961                                         bb->last_ins->opcode = CEE_BR;
6962                                         bb->last_ins->inst_target_bb = bb->last_ins->inst_true_bb;
6963                                         changed = TRUE;
6964                                         if (cfg->verbose_level > 2)
6965                                                 g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count);
6966                                 }
6967
6968                                 if (bb->region == bbn->region && bb->next_bb == bbn) {
6969                                         /* the block are in sequence anyway ... */
6970
6971                                         /* branches to the following block can be removed */
6972                                         if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
6973                                                 bb->last_ins->opcode = CEE_NOP;
6974                                                 changed = TRUE;
6975                                                 if (cfg->verbose_level > 2)
6976                                                         g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
6977                                         }
6978
6979                                         if (bbn->in_count == 1) {
6980
6981                                                 if (bbn != cfg->bb_exit) {
6982                                                         if (cfg->verbose_level > 2)
6983                                                                 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
6984                                                         merge_basic_blocks (bb, bbn);
6985                                                         changed = TRUE;
6986                                                 }
6987
6988                                                 //mono_print_bb_code (bb);
6989                                         }
6990                                 }                               
6991                         }
6992                 }
6993         } while (changed && (niterations > 0));
6994
6995         niterations = 1000;
6996         do {
6997                 changed = FALSE;
6998                 niterations --;
6999
7000                 /* we skip the entry block (exit is handled specially instead ) */
7001                 for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
7002
7003                         /* dont touch code inside exception clauses */
7004                         if (bb->region != -1)
7005                                 continue;
7006
7007                         if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
7008                                 if (cfg->verbose_level > 2) {
7009                                         g_print ("nullify block triggered %d\n", bbn->block_num);
7010                                 }
7011                                 bb->next_bb = bbn->next_bb;
7012
7013                                 for (i = 0; i < bbn->out_count; i++)
7014                                         replace_in_block (bbn->out_bb [i], bbn, NULL);
7015
7016                                 nullify_basic_block (bbn);                      
7017                                 changed = TRUE;
7018                                 break;
7019                         }
7020
7021
7022                         if (bb->out_count == 1) {
7023                                 bbn = bb->out_bb [0];
7024
7025                                 if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
7026                                         bbn = bb->last_ins->inst_target_bb;
7027                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
7028                                             bbn->code->inst_target_bb->region == bb->region) {
7029                                                 
7030                                                 if (cfg->verbose_level > 2)
7031                                                         g_print ("in %s branch to branch triggered %d -> %d -> %d\n", cfg->method->name, 
7032                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num);
7033
7034                                                 replace_in_block (bbn, bb, NULL);
7035                                                 replace_out_block (bb, bbn, bbn->code->inst_target_bb);
7036                                                 link_bblock (cfg, bb, bbn->code->inst_target_bb);
7037                                                 bb->last_ins->inst_target_bb = bbn->code->inst_target_bb;
7038                                                 changed = TRUE;
7039                                                 break;
7040                                         }
7041                                 }
7042                         } else if (bb->out_count == 2) {
7043                                 if (bb->last_ins && MONO_IS_COND_BRANCH_NOFP (bb->last_ins)) {
7044                                         bbn = bb->last_ins->inst_true_bb;
7045                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
7046                                             bbn->code->inst_target_bb->region == bb->region) {
7047                                                 if (cfg->verbose_level > 2)             
7048                                                         g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n", 
7049                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num, 
7050                                                                  bbn->code->opcode);
7051
7052                                                 bb->last_ins->inst_true_bb = bbn->code->inst_target_bb;
7053
7054                                                 replace_in_block (bbn, bb, NULL);
7055                                                 if (!bbn->in_count)
7056                                                         replace_in_block (bbn->code->inst_target_bb, bbn, bb);
7057                                                 replace_out_block (bb, bbn, bbn->code->inst_target_bb);
7058
7059                                                 link_bblock (cfg, bb, bbn->code->inst_target_bb);
7060
7061                                                 changed = TRUE;
7062                                                 break;
7063                                         }
7064
7065                                         bbn = bb->last_ins->inst_false_bb;
7066                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
7067                                             bbn->code->inst_target_bb->region == bb->region) {
7068                                                 if (cfg->verbose_level > 2)
7069                                                         g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n", 
7070                                                                  bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num, 
7071                                                                  bbn->code->opcode);
7072
7073                                                 bb->last_ins->inst_false_bb = bbn->code->inst_target_bb;
7074
7075                                                 replace_in_block (bbn, bb, NULL);
7076                                                 if (!bbn->in_count)
7077                                                         replace_in_block (bbn->code->inst_target_bb, bbn, bb);
7078                                                 replace_out_block (bb, bbn, bbn->code->inst_target_bb);
7079
7080                                                 link_bblock (cfg, bb, bbn->code->inst_target_bb);
7081
7082                                                 changed = TRUE;
7083                                                 break;
7084                                         }
7085                                 }
7086                         }
7087                 }
7088         } while (changed && (niterations > 0));
7089
7090 }
7091
7092 static void
7093 mono_compile_create_vars (MonoCompile *cfg)
7094 {
7095         MonoMethodSignature *sig;
7096         MonoMethodHeader *header;
7097         int i;
7098
7099         header = mono_method_get_header (cfg->method);
7100
7101         sig = cfg->method->signature;
7102         
7103         if (!MONO_TYPE_IS_VOID (sig->ret)) {
7104                 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
7105                 cfg->ret->opcode = OP_RETARG;
7106                 cfg->ret->inst_vtype = sig->ret;
7107                 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
7108         }
7109         if (cfg->verbose_level > 2)
7110                 g_print ("creating vars\n");
7111
7112         if (sig->hasthis)
7113                 mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
7114
7115         for (i = 0; i < sig->param_count; ++i)
7116                 mono_compile_create_var (cfg, sig->params [i], OP_ARG);
7117
7118         cfg->locals_start = cfg->num_varinfo;
7119
7120         if (cfg->verbose_level > 2)
7121                 g_print ("creating locals\n");
7122         for (i = 0; i < header->num_locals; ++i)
7123                 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
7124         if (cfg->verbose_level > 2)
7125                 g_print ("locals done\n");
7126 }
7127
7128 void
7129 mono_print_code (MonoCompile *cfg)
7130 {
7131         MonoBasicBlock *bb;
7132         
7133         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7134                 MonoInst *tree = bb->code;      
7135
7136                 if (!tree)
7137                         continue;
7138                 
7139                 g_print ("CODE BLOCK %d (nesting %d):\n", bb->block_num, bb->nesting);
7140
7141                 for (; tree; tree = tree->next) {
7142                         mono_print_tree (tree);
7143                         g_print ("\n");
7144                 }
7145
7146                 if (bb->last_ins)
7147                         bb->last_ins->next = NULL;
7148         }
7149 }
7150
7151 extern const char * const mono_burg_rule_string [];
7152
7153 static void
7154 emit_state (MonoCompile *cfg, MBState *state, int goal)
7155 {
7156         MBState *kids [10];
7157         int ern = mono_burg_rule (state, goal);
7158         const guint16 *nts = mono_burg_nts [ern];
7159         MBEmitFunc emit;
7160
7161         //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
7162         switch (goal) {
7163         case MB_NTERM_reg:
7164                 //if (state->reg2)
7165                 //      state->reg1 = state->reg2; /* chain rule */
7166                 //else
7167 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
7168                 if (!state->reg1)
7169 #endif
7170                         state->reg1 = mono_regstate_next_int (cfg->rs);
7171                 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
7172                 break;
7173         case MB_NTERM_lreg:
7174                 state->reg1 = mono_regstate_next_int (cfg->rs);
7175                 state->reg2 = mono_regstate_next_int (cfg->rs);
7176                 break;
7177         case MB_NTERM_freg:
7178                 state->reg1 = mono_regstate_next_float (cfg->rs);
7179                 break;
7180         default:
7181 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
7182                 /*
7183                  * Enabling this might cause bugs to surface in the local register
7184                  * allocators on some architectures like x86.
7185                  */
7186                 if ((state->tree->ssa_op == MONO_SSA_STORE) && (state->left->tree->opcode == OP_REGVAR)) {
7187                         /* Do not optimize away reg-reg moves */
7188                         if (! ((state->right->tree->ssa_op == MONO_SSA_LOAD) && (state->right->left->tree->opcode == OP_REGVAR))) {
7189                                 state->right->reg1 = state->left->tree->dreg;
7190                         }
7191                 }
7192 #endif
7193
7194                 /* do nothing */
7195                 break;
7196         }
7197         if (nts [0]) {
7198                 mono_burg_kids (state, ern, kids);
7199
7200                 emit_state (cfg, kids [0], nts [0]);
7201                 if (nts [1]) {
7202                         emit_state (cfg, kids [1], nts [1]);
7203                         if (nts [2]) {
7204                                 g_assert (!nts [3]);
7205                                 emit_state (cfg, kids [2], nts [2]);
7206                         }
7207                 }
7208         }
7209
7210 //      g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
7211         if ((emit = mono_burg_func [ern]))
7212                 emit (state, state->tree, cfg); 
7213 }
7214
7215 #define DEBUG_SELECTION
7216
7217 static void 
7218 mini_select_instructions (MonoCompile *cfg)
7219 {
7220         static const int reverse_map [] = {
7221                 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
7222                 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
7223         };
7224         static const int reverse_fmap [] = {
7225                 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
7226                 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
7227         };
7228         static const int reverse_lmap [] = {
7229                 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
7230                 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
7231         };
7232         static const int reverse_imap [] = {
7233                 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
7234                 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
7235         };
7236
7237         MonoBasicBlock *bb;
7238         
7239         cfg->state_pool = mono_mempool_new ();
7240         cfg->rs = mono_regstate_new ();
7241
7242         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7243                 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
7244                     bb->next_bb != bb->last_ins->inst_false_bb) {
7245
7246                         /* we are careful when inverting, since bugs like #59580
7247                          * could show up when dealing with NaNs.
7248                          */
7249                         if (MONO_IS_COND_BRANCH_NOFP(bb->last_ins) && bb->next_bb == bb->last_ins->inst_true_bb) {
7250                                 MonoBasicBlock *tmp =  bb->last_ins->inst_true_bb;
7251                                 bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb;
7252                                 bb->last_ins->inst_false_bb = tmp;
7253                                 
7254                                 if (bb->last_ins->opcode >= CEE_BEQ && bb->last_ins->opcode <= CEE_BLT_UN) {
7255                                         bb->last_ins->opcode = reverse_map [bb->last_ins->opcode - CEE_BEQ];
7256                                 } else if (bb->last_ins->opcode >= OP_FBEQ && bb->last_ins->opcode <= OP_FBLT_UN) {
7257                                         bb->last_ins->opcode = reverse_fmap [bb->last_ins->opcode - OP_FBEQ];
7258                                 } else if (bb->last_ins->opcode >= OP_LBEQ && bb->last_ins->opcode <= OP_LBLT_UN) {
7259                                         bb->last_ins->opcode = reverse_lmap [bb->last_ins->opcode - OP_LBEQ];
7260                                 } else if (bb->last_ins->opcode >= OP_IBEQ && bb->last_ins->opcode <= OP_IBLT_UN) {
7261                                         bb->last_ins->opcode = reverse_imap [bb->last_ins->opcode - OP_IBEQ];
7262                                 }
7263                         } else {                        
7264                                 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
7265                                 inst->opcode = CEE_BR;
7266                                 inst->inst_target_bb = bb->last_ins->inst_false_bb;
7267                                 mono_bblock_add_inst (bb, inst);
7268                         }
7269                 }
7270         }
7271
7272 #ifdef DEBUG_SELECTION
7273         if (cfg->verbose_level >= 4) {
7274         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7275                 MonoInst *tree = bb->code;      
7276                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
7277                 if (!tree)
7278                         continue;
7279                 for (; tree; tree = tree->next) {
7280                         mono_print_tree (tree);
7281                         g_print ("\n");
7282                 }
7283         }
7284         }
7285 #endif
7286
7287         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7288                 MonoInst *tree = bb->code, *next;       
7289                 MBState *mbstate;
7290
7291                 if (!tree)
7292                         continue;
7293                 bb->code = NULL;
7294                 bb->last_ins = NULL;
7295                 
7296                 cfg->cbb = bb;
7297                 mono_regstate_reset (cfg->rs);
7298
7299 #ifdef DEBUG_SELECTION
7300                 if (cfg->verbose_level >= 3)
7301                         g_print ("LABEL BLOCK %d:\n", bb->block_num);
7302 #endif
7303                 for (; tree; tree = next) {
7304                         next = tree->next;
7305 #ifdef DEBUG_SELECTION
7306                         if (cfg->verbose_level >= 3) {
7307                                 mono_print_tree (tree);
7308                                 g_print ("\n");
7309                         }
7310 #endif
7311
7312                         if (!(mbstate = mono_burg_label (tree, cfg))) {
7313                                 g_warning ("unable to label tree %p", tree);
7314                                 mono_print_tree (tree);
7315                                 g_print ("\n");                         
7316                                 g_assert_not_reached ();
7317                         }
7318                         emit_state (cfg, mbstate, MB_NTERM_stmt);
7319                 }
7320                 bb->max_ireg = cfg->rs->next_vireg;
7321                 bb->max_freg = cfg->rs->next_vfreg;
7322
7323                 if (bb->last_ins)
7324                         bb->last_ins->next = NULL;
7325
7326                 mono_mempool_empty (cfg->state_pool); 
7327         }
7328         mono_mempool_destroy (cfg->state_pool); 
7329 }
7330
7331 void
7332 mono_codegen (MonoCompile *cfg)
7333 {
7334         MonoJumpInfo *patch_info;
7335         MonoBasicBlock *bb;
7336         int i, max_epilog_size;
7337         guint8 *code;
7338
7339         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7340                 cfg->spill_count = 0;
7341                 /* we reuse dfn here */
7342                 /* bb->dfn = bb_count++; */
7343                 mono_arch_local_regalloc (cfg, bb);
7344         }
7345
7346         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
7347                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
7348
7349         code = mono_arch_emit_prolog (cfg);
7350
7351         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
7352                 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
7353
7354         cfg->code_len = code - cfg->native_code;
7355         cfg->prolog_end = cfg->code_len;
7356
7357         mono_debug_open_method (cfg);
7358
7359         /* emit code all basic blocks */
7360         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7361                 bb->native_offset = cfg->code_len;
7362                 mono_arch_output_basic_block (cfg, bb);
7363         }
7364         cfg->bb_exit->native_offset = cfg->code_len;
7365
7366         code = cfg->native_code + cfg->code_len;
7367
7368         max_epilog_size = mono_arch_max_epilog_size (cfg);
7369
7370         /* we always allocate code in cfg->domain->code_mp to increase locality */
7371         cfg->code_size = cfg->code_len + max_epilog_size;
7372         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
7373
7374         if (cfg->method->dynamic) {
7375                 /* Allocate the code into a separate memory pool so it can be freed */
7376                 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
7377                 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
7378                 mono_domain_lock (cfg->domain);
7379                 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
7380                 mono_domain_unlock (cfg->domain);
7381
7382                 code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size);
7383         } else {
7384                 mono_domain_lock (cfg->domain);
7385                 code = mono_code_manager_reserve (cfg->domain->code_mp, cfg->code_size);
7386                 mono_domain_unlock (cfg->domain);
7387         }
7388
7389         memcpy (code, cfg->native_code, cfg->code_len);
7390         g_free (cfg->native_code);
7391         cfg->native_code = code;
7392         code = cfg->native_code + cfg->code_len;
7393   
7394         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
7395
7396         cfg->epilog_begin = cfg->code_len;
7397
7398         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
7399                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
7400
7401         cfg->code_len = code - cfg->native_code;
7402
7403         mono_arch_emit_epilog (cfg);
7404
7405         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
7406                 switch (patch_info->type) {
7407                 case MONO_PATCH_INFO_ABS: {
7408                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
7409                         if (info) {
7410                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
7411                                 if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && 
7412                                         strstr (cfg->method->name, info->name))
7413                                         /*
7414                                          * This is an icall wrapper, and this is a call to the
7415                                          * wrapped function.
7416                                          */
7417                                         ;
7418                                 else {
7419                                         patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
7420                                         patch_info->data.name = info->name;
7421                                 }
7422                         }
7423                         else {
7424                                 MonoVTable *vtable = mono_find_class_init_trampoline_by_addr (patch_info->data.target);
7425                                 if (vtable) {
7426                                         patch_info->type = MONO_PATCH_INFO_CLASS_INIT;
7427                                         patch_info->data.klass = vtable->klass;
7428                                 }
7429                         }
7430                         break;
7431                 }
7432                 case MONO_PATCH_INFO_SWITCH: {
7433                         gpointer *table;
7434                         if (cfg->method->dynamic) {
7435                                 table = mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->table_size);
7436                         } else {
7437                                 mono_domain_lock (cfg->domain);
7438                                 table = mono_code_manager_reserve (cfg->domain->code_mp, sizeof (gpointer) * patch_info->table_size);
7439                                 mono_domain_unlock (cfg->domain);
7440                         }
7441                 
7442                         patch_info->ip.i = patch_info->ip.label->inst_c0;
7443                         for (i = 0; i < patch_info->table_size; i++) {
7444                                 table [i] = (gpointer)patch_info->data.table [i]->native_offset;
7445                         }
7446                         patch_info->data.target = table;
7447                         break;
7448                 }
7449                 default:
7450                         /* do nothing */
7451                         break;
7452                 }
7453         }
7454        
7455         if (cfg->verbose_level > 0)
7456                 g_print ("Method %s emitted at %p to %p [%s]\n", 
7457                                  mono_method_full_name (cfg->method, TRUE), 
7458                                  cfg->native_code, cfg->native_code + cfg->code_len, cfg->domain->friendly_name);
7459
7460         mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
7461
7462         if (cfg->method->dynamic) {
7463                 mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
7464         } else {
7465                 mono_domain_lock (cfg->domain);
7466                 mono_code_manager_commit (cfg->domain->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
7467                 mono_domain_unlock (cfg->domain);
7468         }
7469         
7470         mono_arch_flush_icache (cfg->native_code, cfg->code_len);
7471
7472         mono_debug_close_method (cfg);
7473 }
7474
7475 static void
7476 mono_cprop_copy_values (MonoCompile *cfg, MonoInst *tree, MonoInst **acp)
7477 {
7478         MonoInst *cp;
7479         int arity;
7480
7481         if (tree->ssa_op == MONO_SSA_LOAD && (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG) && 
7482             (cp = acp [tree->inst_i0->inst_c0]) && !tree->inst_i0->flags) {
7483
7484                 if (cp->opcode == OP_ICONST) {
7485                         if (cfg->opt & MONO_OPT_CONSPROP) {
7486                                 //{ static int c = 0; printf ("CCOPY %d %d %s\n", c++, cp->inst_c0, mono_method_full_name (cfg->method, TRUE)); }
7487                                 *tree = *cp;
7488                         }
7489                 } else {
7490                         if (tree->inst_i0->inst_vtype->type == cp->inst_vtype->type) {
7491                                 if (cfg->opt & MONO_OPT_COPYPROP) {
7492                                         //{ static int c = 0; printf ("VCOPY %d\n", ++c); }
7493                                         tree->inst_i0 = cp;
7494                                 } 
7495                         }
7496                 } 
7497         } else {
7498                 arity = mono_burg_arity [tree->opcode];
7499
7500                 if (arity) {
7501                         mono_cprop_copy_values (cfg, tree->inst_i0, acp);
7502                         if (cfg->opt & MONO_OPT_CFOLD)
7503                                 mono_constant_fold_inst (tree, NULL); 
7504                         /* The opcode may have changed */
7505                         if (mono_burg_arity [tree->opcode] > 1) {
7506                                 mono_cprop_copy_values (cfg, tree->inst_i1, acp);
7507                                 if (cfg->opt & MONO_OPT_CFOLD)
7508                                         mono_constant_fold_inst (tree, NULL); 
7509                         }
7510                         mono_constant_fold_inst (tree, NULL); 
7511                 }
7512         }
7513 }
7514
7515 static void
7516 mono_cprop_invalidate_values (MonoInst *tree, MonoInst **acp, int acp_size)
7517 {
7518         int arity;
7519
7520         switch (tree->opcode) {
7521         case CEE_STIND_I:
7522         case CEE_STIND_I1:
7523         case CEE_STIND_I2:
7524         case CEE_STIND_I4:
7525         case CEE_STIND_REF:
7526         case CEE_STIND_I8:
7527         case CEE_STIND_R4:
7528         case CEE_STIND_R8:
7529         case CEE_STOBJ:
7530                 if (tree->ssa_op == MONO_SSA_NOP) {
7531                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
7532                         return;
7533                 }
7534
7535                 break;
7536         case CEE_CALL:
7537         case OP_CALL_REG:
7538         case CEE_CALLVIRT:
7539         case OP_LCALL_REG:
7540         case OP_LCALLVIRT:
7541         case OP_LCALL:
7542         case OP_FCALL_REG:
7543         case OP_FCALLVIRT:
7544         case OP_FCALL:
7545         case OP_VCALL_REG:
7546         case OP_VCALLVIRT:
7547         case OP_VCALL:
7548         case OP_VOIDCALL_REG:
7549         case OP_VOIDCALLVIRT:
7550         case OP_VOIDCALL: {
7551                 MonoCallInst *call = (MonoCallInst *)tree;
7552                 MonoMethodSignature *sig = call->signature;
7553                 int i, byref = FALSE;
7554
7555                 for (i = 0; i < sig->param_count; i++) {
7556                         if (sig->params [i]->byref) {
7557                                 byref = TRUE;
7558                                 break;
7559                         }
7560                 }
7561
7562                 if (byref)
7563                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
7564
7565                 return;
7566         }
7567         default:
7568                 break;
7569         }
7570
7571         arity = mono_burg_arity [tree->opcode];
7572
7573         switch (arity) {
7574         case 0:
7575                 break;
7576         case 1:
7577                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
7578                 break;
7579         case 2:
7580                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
7581                 mono_cprop_invalidate_values (tree->inst_i1, acp, acp_size);
7582                 break;
7583         default:
7584                 g_assert_not_reached ();
7585         }
7586 }
7587
7588 static void
7589 mono_local_cprop_bb (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **acp, int acp_size)
7590 {
7591         MonoInst *tree = bb->code;      
7592         int i;
7593
7594         if (!tree)
7595                 return;
7596
7597         for (; tree; tree = tree->next) {
7598
7599                 mono_cprop_copy_values (cfg, tree, acp);
7600
7601                 mono_cprop_invalidate_values (tree, acp, acp_size);
7602
7603                 if (tree->ssa_op == MONO_SSA_STORE  && 
7604                     (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG)) {
7605                         MonoInst *i1 = tree->inst_i1;
7606
7607                         acp [tree->inst_i0->inst_c0] = NULL;
7608
7609                         for (i = 0; i < acp_size; i++) {
7610                                 if (acp [i] && acp [i]->opcode != OP_ICONST && 
7611                                     acp [i]->inst_c0 == tree->inst_i0->inst_c0) {
7612                                         acp [i] = NULL;
7613                                 }
7614                         }
7615
7616                         if (i1->opcode == OP_ICONST) {
7617                                 acp [tree->inst_i0->inst_c0] = i1;
7618                                 //printf ("DEF1 BB%d %d\n", bb->block_num,tree->inst_i0->inst_c0);
7619                         }
7620                         if (i1->ssa_op == MONO_SSA_LOAD && 
7621                             (i1->inst_i0->opcode == OP_LOCAL || i1->inst_i0->opcode == OP_ARG) &&
7622                             (i1->inst_i0->inst_c0 != tree->inst_i0->inst_c0)) {
7623                                 acp [tree->inst_i0->inst_c0] = i1->inst_i0;
7624                                 //printf ("DEF2 BB%d %d %d\n", bb->block_num,tree->inst_i0->inst_c0,i1->inst_i0->inst_c0);
7625                         }
7626                 }
7627
7628                 /*
7629                   if (tree->opcode == CEE_BEQ) {
7630                   g_assert (tree->inst_i0->opcode == OP_COMPARE);
7631                   if (tree->inst_i0->inst_i0->opcode == OP_ICONST &&
7632                   tree->inst_i0->inst_i1->opcode == OP_ICONST) {
7633                   
7634                   tree->opcode = CEE_BR;
7635                   if (tree->inst_i0->inst_i0->opcode == tree->inst_i0->inst_i1->opcode) {
7636                   tree->inst_target_bb = tree->inst_true_bb;
7637                   } else {
7638                   tree->inst_target_bb = tree->inst_false_bb;
7639                   }
7640                   }
7641                   }
7642                 */
7643         }
7644 }
7645
7646 static void
7647 mono_local_cprop (MonoCompile *cfg)
7648 {
7649         MonoBasicBlock *bb;
7650         MonoInst **acp;
7651
7652         acp = alloca (sizeof (MonoInst *) * cfg->num_varinfo);
7653
7654         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7655                 memset (acp, 0, sizeof (MonoInst *) * cfg->num_varinfo);
7656                 mono_local_cprop_bb (cfg, bb, acp, cfg->num_varinfo);
7657         }
7658 }
7659
7660 MonoCompile*
7661 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, int parts)
7662 {
7663         MonoMethodHeader *header = mono_method_get_header (method);
7664         guint8 *ip = (guint8 *)header->code;
7665         MonoCompile *cfg;
7666         MonoJitInfo *jinfo;
7667         int dfn = 0, i, code_size_ratio;
7668
7669         mono_jit_stats.methods_compiled++;
7670         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
7671                 mono_profiler_method_jit (method);
7672
7673         cfg = g_new0 (MonoCompile, 1);
7674         cfg->method = method;
7675         cfg->mempool = mono_mempool_new ();
7676         cfg->opt = opts;
7677         cfg->prof_options = mono_profiler_get_events ();
7678         cfg->run_cctors = run_cctors;
7679         cfg->bb_hash = g_hash_table_new (NULL, NULL);
7680         cfg->domain = domain;
7681         cfg->verbose_level = mini_verbose;
7682         cfg->intvars = mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * 
7683                                             mono_method_get_header (method)->max_stack);
7684
7685         if (cfg->verbose_level > 2)
7686                 g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
7687
7688         /*
7689          * create MonoInst* which represents arguments and local variables
7690          */
7691         mono_compile_create_vars (cfg);
7692
7693         if ((i = mono_method_to_ir (cfg, method, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
7694                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
7695                         mono_profiler_method_end_jit (method, MONO_PROFILE_FAILED);
7696                 mono_destroy_compile (cfg);
7697                 return NULL;
7698         }
7699
7700         mono_jit_stats.basic_blocks += cfg->num_bblocks;
7701         mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
7702
7703         if (cfg->num_varinfo > 2000) {
7704                 /* 
7705                  * we disable some optimizations if there are too many variables
7706                  * because JIT time may become too expensive. The actual number needs 
7707                  * to be tweaked and eventually the non-linear algorithms should be fixed.
7708                  */
7709                 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
7710                 cfg->disable_ssa = TRUE;
7711         }
7712         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
7713
7714         /* Depth-first ordering on basic blocks */
7715         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
7716
7717         if (cfg->opt & MONO_OPT_BRANCH)
7718                 optimize_branches (cfg);
7719
7720         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
7721         if (cfg->num_bblocks != dfn + 1) {
7722                 MonoBasicBlock *bb;
7723
7724                 cfg->num_bblocks = dfn + 1;
7725
7726                 if (!header->clauses) {
7727                         /* remove unreachable code, because the code in them may be 
7728                          * inconsistent  (access to dead variables for example) */
7729                         for (bb = cfg->bb_entry; bb;) {
7730                                 MonoBasicBlock *bbn = bb->next_bb;
7731
7732                                 if (bbn && bbn->region == -1 && !bbn->dfn) {
7733                                         if (cfg->verbose_level > 1)
7734                                                 g_print ("found unreachabel code in BB%d\n", bbn->block_num);
7735                                         bb->next_bb = bbn->next_bb;
7736                                         nullify_basic_block (bbn);                      
7737                                 } else {
7738                                         bb = bb->next_bb;
7739                                 }
7740                         }
7741                 }
7742         }
7743
7744         if (cfg->opt & MONO_OPT_LOOP) {
7745                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
7746                 mono_compute_natural_loops (cfg);
7747         }
7748
7749         /* after method_to_ir */
7750         if (parts == 1)
7751                 return cfg;
7752
7753 //#define DEBUGSSA "logic_run"
7754 #define DEBUGSSA_CLASS "Tests"
7755 #ifdef DEBUGSSA
7756
7757         if (!header->num_clauses && !cfg->disable_ssa) {
7758                 mono_local_cprop (cfg);
7759                 mono_ssa_compute (cfg);
7760         }
7761 #else 
7762
7763         /* fixme: add all optimizations which requires SSA */
7764         if (cfg->opt & (MONO_OPT_DEADCE | MONO_OPT_ABCREM)) {
7765                 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
7766                         mono_local_cprop (cfg);
7767                         mono_ssa_compute (cfg);
7768
7769                         if (cfg->verbose_level >= 2) {
7770                                 print_dfn (cfg);
7771                         }
7772                 }
7773         }
7774 #endif
7775
7776         /* after SSA translation */
7777         if (parts == 2)
7778                 return cfg;
7779
7780         if ((cfg->opt & MONO_OPT_CONSPROP) ||  (cfg->opt & MONO_OPT_COPYPROP)) {
7781                 if (cfg->comp_done & MONO_COMP_SSA) {
7782                         mono_ssa_cprop (cfg);
7783                 } else {
7784                         mono_local_cprop (cfg);
7785                 }
7786         }
7787
7788         if (cfg->comp_done & MONO_COMP_SSA) {                   
7789                 mono_ssa_deadce (cfg);
7790
7791                 //mono_ssa_strength_reduction (cfg);
7792
7793                 if ((cfg->flags & MONO_CFG_HAS_LDELEMA) && (cfg->opt & MONO_OPT_ABCREM))
7794                         mono_perform_abc_removal (cfg);
7795
7796                 mono_ssa_remove (cfg);
7797
7798                 if (cfg->opt & MONO_OPT_BRANCH)
7799                         optimize_branches (cfg);
7800         }
7801
7802         /* after SSA removal */
7803         if (parts == 3)
7804                 return cfg;
7805
7806         decompose_pass (cfg);
7807
7808         if (cfg->opt & MONO_OPT_LINEARS) {
7809                 GList *vars, *regs;
7810
7811                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
7812                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
7813                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
7814                         mono_analyze_liveness (cfg);
7815
7816                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
7817                         regs = mono_arch_get_global_int_regs (cfg);
7818                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
7819                 }
7820         }
7821
7822         //mono_print_code (cfg);
7823
7824        //print_dfn (cfg);
7825         
7826         /* variables are allocated after decompose, since decompose could create temps */
7827         mono_arch_allocate_vars (cfg);
7828
7829         if (cfg->opt & MONO_OPT_CFOLD)
7830                 mono_constant_fold (cfg);
7831
7832         mini_select_instructions (cfg);
7833
7834         mono_codegen (cfg);
7835         if (cfg->verbose_level >= 2) {
7836                 char *id =  mono_method_full_name (cfg->method, FALSE);
7837                 mono_disassemble_code (cfg->native_code, cfg->code_len, id + 3);
7838                 g_free (id);
7839         }
7840         
7841         if (cfg->method->dynamic)
7842                 jinfo = g_new0 (MonoJitInfo, 1);
7843         else
7844                 jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo));
7845
7846         jinfo->method = method;
7847         jinfo->code_start = cfg->native_code;
7848         jinfo->code_size = cfg->code_len;
7849         jinfo->used_regs = cfg->used_int_regs;
7850         jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
7851
7852         if (header->num_clauses) {
7853                 int i;
7854
7855                 jinfo->exvar_offset = cfg->exvar? cfg->exvar->inst_offset: 0;
7856                 jinfo->num_clauses = header->num_clauses;
7857                 jinfo->clauses = mono_mempool_alloc0 (cfg->domain->mp, 
7858                         sizeof (MonoJitExceptionInfo) * header->num_clauses);
7859
7860                 for (i = 0; i < header->num_clauses; i++) {
7861                         MonoExceptionClause *ec = &header->clauses [i];
7862                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
7863                         MonoBasicBlock *tblock;
7864
7865                         ei->flags = ec->flags;
7866
7867                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
7868                                 tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->data.filter_offset);
7869                                 g_assert (tblock);
7870                                 ei->data.filter = cfg->native_code + tblock->native_offset;
7871                         } else {
7872                                 ei->data.catch_class = ec->data.catch_class;
7873                         }
7874
7875                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset);
7876                         g_assert (tblock);
7877                         ei->try_start = cfg->native_code + tblock->native_offset;
7878                         g_assert (tblock->native_offset);
7879                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset + ec->try_len);
7880                         g_assert (tblock);
7881                         ei->try_end = cfg->native_code + tblock->native_offset;
7882                         g_assert (tblock->native_offset);
7883                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->handler_offset);
7884                         g_assert (tblock);
7885                         ei->handler_start = cfg->native_code + tblock->native_offset;
7886                 }
7887         }
7888
7889         cfg->jit_info = jinfo;
7890
7891         mono_jit_info_table_add (cfg->domain, jinfo);
7892
7893         if (cfg->method->dynamic)
7894                 mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = jinfo;
7895
7896         /* collect statistics */
7897         mono_jit_stats.allocated_code_size += cfg->code_len;
7898         code_size_ratio = cfg->code_len;
7899         if (code_size_ratio > mono_jit_stats.biggest_method_size) {
7900                         mono_jit_stats.biggest_method_size = code_size_ratio;
7901                         mono_jit_stats.biggest_method = method;
7902         }
7903         code_size_ratio = (code_size_ratio * 100) / mono_method_get_header (method)->code_size;
7904         if (code_size_ratio > mono_jit_stats.max_code_size_ratio) {
7905                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
7906                 mono_jit_stats.max_ratio_method = method;
7907         }
7908         mono_jit_stats.native_code_size += cfg->code_len;
7909
7910         if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
7911                 mono_profiler_method_end_jit (method, MONO_PROFILE_OK);
7912
7913         return cfg;
7914 }
7915
7916 static gpointer
7917 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain)
7918 {
7919         MonoCompile *cfg;
7920         GHashTable *jit_code_hash;
7921         gpointer code = NULL;
7922         guint32 opt;
7923         MonoJitInfo *info;
7924
7925         opt = default_opt;
7926
7927         jit_code_hash = target_domain->jit_code_hash;
7928
7929 #ifdef MONO_USE_AOT_COMPILER
7930         if (!mono_compile_aot && (opt & MONO_OPT_AOT)) {
7931                 MonoJitInfo *info;
7932                 MonoDomain *domain = mono_domain_get ();
7933
7934                 mono_domain_lock (domain);
7935
7936                 mono_class_init (method->klass);
7937                 if ((info = mono_aot_get_method (domain, method))) {
7938                         g_hash_table_insert (domain->jit_code_hash, method, info);
7939                         mono_domain_unlock (domain);
7940                         mono_runtime_class_init (mono_class_vtable (domain, method->klass));
7941                         return info->code_start;
7942                 }
7943
7944                 mono_domain_unlock (domain);
7945         }
7946 #endif
7947
7948         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
7949             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
7950                 MonoMethod *nm;
7951                 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
7952
7953                 if (!piinfo->addr) {
7954                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
7955                                 piinfo->addr = mono_lookup_internal_call (method);
7956                         else
7957                                 if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
7958                                         mono_lookup_pinvoke_call (method, NULL, NULL);
7959                 }
7960                         nm = mono_marshal_get_native_wrapper (method);
7961                         return mono_compile_method (nm);
7962
7963                         //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE) 
7964                         //mono_debug_add_wrapper (method, nm);
7965         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
7966                 const char *name = method->name;
7967                 MonoMethod *nm;
7968
7969                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
7970                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
7971                                 /* FIXME: uhm, we need a wrapper to handle exceptions? */
7972                                 return (gpointer)mono_delegate_ctor;
7973                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
7974                                 nm = mono_marshal_get_delegate_invoke (method);
7975                                 return mono_jit_compile_method (nm);
7976                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
7977                                 nm = mono_marshal_get_delegate_begin_invoke (method);
7978                                 return mono_jit_compile_method (nm);
7979                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
7980                                 nm = mono_marshal_get_delegate_end_invoke (method);
7981                                 return mono_jit_compile_method (nm);
7982                         }
7983                 }
7984                 return NULL;
7985         }
7986
7987         cfg = mini_method_compile (method, opt, target_domain, TRUE, 0);
7988
7989         mono_domain_lock (target_domain);
7990
7991         /* Check if some other thread already did the job. In this case, we can
7992        discard the code this thread generated. */
7993
7994         if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
7995                 /* We can't use a domain specific method in another domain */
7996                 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
7997                         code = info->code_start;
7998 //                      printf("Discarding code for method %s\n", method->name);
7999                 }
8000         }
8001         
8002         if (code == NULL) {
8003                 g_hash_table_insert (jit_code_hash, method, cfg->jit_info);
8004                 code = cfg->native_code;
8005         }
8006
8007         mono_destroy_compile (cfg);
8008
8009         if (target_domain->jump_target_hash) {
8010                 MonoJumpInfo patch_info;
8011                 GSList *list, *tmp;
8012                 list = g_hash_table_lookup (target_domain->jump_target_hash, method);
8013                 if (list) {
8014                         patch_info.next = NULL;
8015                         patch_info.ip.i = 0;
8016                         patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
8017                         patch_info.data.method = method;
8018                         g_hash_table_remove (target_domain->jump_target_hash, method);
8019                 }
8020                 for (tmp = list; tmp; tmp = tmp->next)
8021                         mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info, TRUE);
8022                 g_slist_free (list);
8023         }
8024
8025         mono_domain_unlock (target_domain);
8026
8027         mono_runtime_class_init (mono_class_vtable (target_domain, method->klass));
8028         return code;
8029 }
8030
8031 static gpointer
8032 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt)
8033 {
8034         /* FIXME: later copy the code from mono */
8035         MonoDomain *target_domain, *domain = mono_domain_get ();
8036         MonoJitInfo *info;
8037         gpointer p;
8038
8039         if (opt & MONO_OPT_SHARED)
8040                 target_domain = mono_get_root_domain ();
8041         else 
8042                 target_domain = domain;
8043
8044         mono_domain_lock (target_domain);
8045
8046         if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
8047                 /* We can't use a domain specific method in another domain */
8048                 if (! ((domain != target_domain) && !info->domain_neutral)) {
8049                         mono_domain_unlock (target_domain);
8050                         mono_jit_stats.methods_lookups++;
8051                         mono_runtime_class_init (mono_class_vtable (domain, method->klass));
8052                         return info->code_start;
8053                 }
8054         }
8055
8056         mono_domain_unlock (target_domain);
8057         p = mono_jit_compile_method_inner (method, target_domain);
8058         return p;
8059 }
8060
8061 static gpointer
8062 mono_jit_compile_method (MonoMethod *method)
8063 {
8064         return mono_jit_compile_method_with_opt (method, default_opt);
8065 }
8066
8067 static void
8068 invalidated_delegate_trampoline (MonoClass *klass)
8069 {
8070         g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
8071                  "See http://www.go-mono.com/delegate.html for an explanation and ways to fix this.",
8072                  mono_type_full_name (&klass->byval_arg));
8073 }
8074
8075 /*
8076  * mono_jit_free_method:
8077  *
8078  *  Free all memory allocated by the JIT for METHOD.
8079  */
8080 static void
8081 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
8082 {
8083         MonoJitDynamicMethodInfo *ji;
8084
8085         g_assert (method->dynamic);
8086
8087         mono_domain_lock (domain);
8088         ji = mono_dynamic_code_hash_lookup (domain, method);
8089         mono_domain_unlock (domain);
8090 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
8091         /* FIXME: only enable this with a env var */
8092         if (method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
8093                 /*
8094                  * Instead of freeing the code, change it to call an error routine
8095                  * so people can fix their code.
8096                  */
8097                 if (ji){
8098                         char *type = mono_type_full_name (&method->klass->byval_arg);
8099                         char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
8100
8101                         g_free (type);
8102                         mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
8103                 }
8104                 return;
8105         }
8106 #endif
8107
8108         if (!ji)
8109                 return;
8110         mono_domain_lock (domain);
8111         g_hash_table_remove (domain->dynamic_code_hash, ji);
8112         mono_domain_unlock (domain);
8113
8114         mono_code_manager_destroy (ji->code_mp);
8115         mono_jit_info_table_remove (domain, ji->ji);
8116         g_free (ji->ji);
8117         g_free (ji);
8118 }
8119
8120 static gpointer
8121 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
8122 {
8123         MonoDomain *target_domain;
8124         MonoJitInfo *info;
8125
8126         if (default_opt & MONO_OPT_SHARED)
8127                 target_domain = mono_get_root_domain ();
8128         else 
8129                 target_domain = domain;
8130
8131         mono_domain_lock (target_domain);
8132
8133         if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
8134                 /* We can't use a domain specific method in another domain */
8135                 if (! ((domain != target_domain) && !info->domain_neutral)) {
8136                         mono_domain_unlock (target_domain);
8137                         mono_jit_stats.methods_lookups++;
8138                         return info->code_start;
8139                 }
8140         }
8141
8142         mono_domain_unlock (target_domain);
8143
8144         return NULL;
8145 }
8146
8147 /**
8148  * mono_jit_runtime_invoke:
8149  * @method: the method to invoke
8150  * @obj: this pointer
8151  * @params: array of parameter values.
8152  * @exc: used to catch exceptions objects
8153  */
8154 static MonoObject*
8155 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
8156 {
8157         MonoMethod *invoke;
8158         MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
8159         void* compiled_method;
8160
8161         if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
8162                 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
8163                 return NULL;
8164         }
8165
8166         invoke = mono_marshal_get_runtime_invoke (method);
8167         runtime_invoke = mono_jit_compile_method (invoke);
8168         
8169         /* We need this here becuase mono_marshal_get_runtime_invoke can be place 
8170          * the helper method in System.Object and not the target class
8171          */
8172         mono_runtime_class_init (mono_class_vtable (mono_domain_get (), method->klass));
8173
8174         compiled_method = mono_jit_compile_method (method);
8175         return runtime_invoke (obj, params, exc, compiled_method);
8176 }
8177
8178 #ifdef PLATFORM_WIN32
8179 #define GET_CONTEXT \
8180         struct sigcontext *ctx = (struct sigcontext*)_dummy;
8181 #else
8182 #ifdef __sparc
8183 #define GET_CONTEXT \
8184     void *ctx = context;
8185 #elif defined(sun)    // Solaris x86
8186 #define GET_CONTEXT \
8187     ucontext_t *uctx = context; \
8188     struct sigcontext *ctx = (struct sigcontext *)&(uctx->uc_mcontext);
8189 #elif defined(__ppc__) || defined (__powerpc__) || defined (__s390__) || defined (MONO_ARCH_USE_SIGACTION)
8190 #define GET_CONTEXT \
8191     void *ctx = context;
8192 #else
8193 #define GET_CONTEXT \
8194         void **_p = (void **)&_dummy; \
8195         struct sigcontext *ctx = (struct sigcontext *)++_p;
8196 #endif
8197 #endif
8198
8199 #ifdef MONO_ARCH_USE_SIGACTION
8200 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, siginfo_t *info, void *context)
8201 #else
8202 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy)
8203 #endif
8204
8205 static void
8206 SIG_HANDLER_SIGNATURE (sigfpe_signal_handler)
8207 {
8208         MonoException *exc = NULL;
8209 #ifndef MONO_ARCH_USE_SIGACTION
8210         void *info = NULL;
8211 #endif
8212         GET_CONTEXT;
8213
8214 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
8215         if (mono_arch_is_int_overflow (ctx, info))
8216                 exc = mono_get_exception_arithmetic ();
8217         else
8218                 exc = mono_get_exception_divide_by_zero ();
8219 #else
8220         exc = mono_get_exception_divide_by_zero ();
8221 #endif
8222         
8223         mono_arch_handle_exception (ctx, exc, FALSE);
8224 }
8225
8226 static void
8227 SIG_HANDLER_SIGNATURE (sigill_signal_handler)
8228 {
8229         MonoException *exc;
8230         GET_CONTEXT
8231         exc = mono_get_exception_execution_engine ("SIGILL");
8232         
8233         mono_arch_handle_exception (ctx, exc, FALSE);
8234 }
8235
8236 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
8237
8238 static void
8239 sigsegv_signal_handler (int _dummy, siginfo_t *info, void *context)
8240 {
8241         MonoException *exc;
8242         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
8243         struct sigcontext *ctx = (struct sigcontext *)&(((ucontext_t*)context)->uc_mcontext);
8244
8245         /* Can't allocate memory using Boehm GC on altstack */
8246         if (jit_tls->stack_size && 
8247                 ((guint8*)info->si_addr >= (guint8*)jit_tls->end_of_stack - jit_tls->stack_size) &&
8248                 ((guint8*)info->si_addr < (guint8*)jit_tls->end_of_stack))
8249                 exc = mono_domain_get ()->stack_overflow_ex;
8250         else
8251                 exc = mono_domain_get ()->null_reference_ex;
8252                         
8253         mono_arch_handle_exception (ctx, exc, FALSE);
8254 }
8255
8256 #else
8257
8258 static void
8259 SIG_HANDLER_SIGNATURE (sigsegv_signal_handler)
8260 {
8261         GET_CONTEXT;
8262
8263         mono_arch_handle_exception (ctx, NULL, FALSE);
8264 }
8265
8266 #endif
8267
8268 static void
8269 SIG_HANDLER_SIGNATURE (sigusr1_signal_handler)
8270 {
8271         gboolean running_managed;
8272         MonoException *exc;
8273         
8274         GET_CONTEXT
8275
8276         running_managed = (mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx)) != NULL);
8277         
8278         exc = mono_thread_request_interruption (running_managed); 
8279         if (!exc) return;
8280         
8281         mono_arch_handle_exception (ctx, exc, FALSE);
8282 }
8283
8284 static void
8285 SIG_HANDLER_SIGNATURE (sigquit_signal_handler)
8286 {
8287        MonoException *exc;
8288        GET_CONTEXT
8289
8290        exc = mono_get_exception_execution_engine ("Interrupted (SIGQUIT).");
8291        
8292        mono_arch_handle_exception (ctx, exc, FALSE);
8293 }
8294
8295 static void
8296 SIG_HANDLER_SIGNATURE (sigint_signal_handler)
8297 {
8298         MonoException *exc;
8299         GET_CONTEXT
8300
8301         exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
8302         
8303         mono_arch_handle_exception (ctx, exc, FALSE);
8304 }
8305
8306 #ifndef PLATFORM_WIN32
8307 static void
8308 add_signal_handler (int signo, gpointer handler)
8309 {
8310         struct sigaction sa;
8311
8312 #ifdef MONO_ARCH_USE_SIGACTION
8313         sa.sa_sigaction = handler;
8314         sigemptyset (&sa.sa_mask);
8315         sa.sa_flags = SA_SIGINFO;
8316 #else
8317         sa.sa_handler = handler;
8318         sigemptyset (&sa.sa_mask);
8319         sa.sa_flags = 0;
8320 #endif
8321         g_assert (sigaction (signo, &sa, NULL) != -1);
8322 }
8323 #endif
8324
8325 static void
8326 mono_runtime_install_handlers (void)
8327 {
8328 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
8329         struct sigaction sa;
8330 #endif
8331
8332 #ifdef PLATFORM_WIN32
8333         win32_seh_init();
8334         win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
8335         win32_seh_set_handler(SIGILL, sigill_signal_handler);
8336         win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
8337         if (getenv ("MONO_DEBUG"))
8338                 win32_seh_set_handler(SIGINT, sigint_signal_handler);
8339 #else /* !PLATFORM_WIN32 */
8340
8341         /* libpthreads has its own implementation of sigaction(),
8342          * but it seems to work well with our current exception
8343          * handlers. If not we must call syscall directly instead 
8344          * of sigaction */
8345
8346         if (getenv ("MONO_DEBUG")) {
8347                 add_signal_handler (SIGINT, sigint_signal_handler);
8348         }
8349
8350         add_signal_handler (SIGFPE, sigfpe_signal_handler);
8351         add_signal_handler (SIGQUIT, sigquit_signal_handler);
8352         add_signal_handler (SIGILL, sigill_signal_handler);
8353         add_signal_handler (SIGBUS, sigsegv_signal_handler);
8354         add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
8355
8356         /* catch SIGSEGV */
8357 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
8358         sa.sa_sigaction = sigsegv_signal_handler;
8359         sigemptyset (&sa.sa_mask);
8360         sa.sa_flags = SA_SIGINFO | SA_ONSTACK;
8361         g_assert (sigaction (SIGSEGV, &sa, NULL) != -1);
8362 #else
8363         add_signal_handler (SIGSEGV, sigsegv_signal_handler);
8364 #endif
8365
8366 #endif /* PLATFORM_WIN32 */
8367 }
8368
8369 /* mono_jit_create_remoting_trampoline:
8370  * @method: pointer to the method info
8371  *
8372  * Creates a trampoline which calls the remoting functions. This
8373  * is used in the vtable of transparent proxies.
8374  * 
8375  * Returns: a pointer to the newly created code 
8376  */
8377 static gpointer
8378 mono_jit_create_remoting_trampoline (MonoMethod *method, MonoRemotingTarget target)
8379 {
8380         MonoMethod *nm;
8381         guint8 *addr = NULL;
8382
8383         if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || 
8384             (method->signature->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
8385                 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
8386                 addr = mono_compile_method (nm);
8387         } else {
8388                 addr = mono_compile_method (method);
8389         }
8390         return addr;
8391 }
8392
8393 MonoDomain *
8394 mini_init (const char *filename)
8395 {
8396         MonoDomain *domain;
8397
8398         mono_arch_cpu_init ();
8399
8400         if (!g_thread_supported ())
8401                 g_thread_init (NULL);
8402         
8403         MONO_GC_PRE_INIT ();
8404
8405         mono_jit_tls_id = TlsAlloc ();
8406         setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
8407
8408         InitializeCriticalSection (&jit_mutex);
8409
8410         mono_burg_init ();
8411
8412         if (default_opt & MONO_OPT_AOT)
8413                 mono_aot_init ();
8414
8415         mono_runtime_install_handlers ();
8416         mono_threads_install_cleanup (mini_thread_cleanup);
8417
8418 #define JIT_TRAMPOLINES_WORK
8419 #ifdef JIT_TRAMPOLINES_WORK
8420         mono_install_compile_method (mono_jit_compile_method);
8421         mono_install_free_method (mono_jit_free_method);
8422         mono_install_trampoline (mono_create_jit_trampoline);
8423         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
8424 #endif
8425 #define JIT_INVOKE_WORKS
8426 #ifdef JIT_INVOKE_WORKS
8427         mono_install_runtime_invoke (mono_jit_runtime_invoke);
8428         mono_install_handler (mono_arch_get_throw_exception ());
8429 #endif
8430         mono_install_stack_walk (mono_jit_walk_stack);
8431
8432         domain = mono_init_from_assembly (filename, filename);
8433         mono_init_icall ();
8434
8435         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info", 
8436                                 ves_icall_get_frame_info);
8437         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace", 
8438                                 ves_icall_get_trace);
8439         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers", 
8440                                 mono_runtime_install_handlers);
8441
8442
8443         create_helper_signature ();
8444
8445 #define JIT_CALLS_WORK
8446 #ifdef JIT_CALLS_WORK
8447         /* Needs to be called here since register_jit_icall depends on it */
8448         mono_marshal_init ();
8449
8450         mono_arch_register_lowlevel_calls ();
8451         mono_register_jit_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
8452         mono_register_jit_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
8453         mono_register_jit_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
8454         mono_register_jit_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
8455         mono_register_jit_icall (mono_get_lmf_addr, "mono_get_lmf_addr", helper_sig_ptr_void, TRUE);
8456         mono_register_jit_icall (mono_domain_get, "mono_domain_get", helper_sig_domain_get, TRUE);
8457
8458         mono_register_jit_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", helper_sig_void_obj, TRUE);
8459         mono_register_jit_icall (mono_arch_get_rethrow_exception (), "mono_arch_rethrow_exception", helper_sig_void_obj, TRUE);
8460         mono_register_jit_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", 
8461                                  helper_sig_void_ptr, TRUE);
8462         mono_register_jit_icall (mono_thread_get_pending_exception, "mono_thread_get_pending_exception", helper_sig_obj_void, FALSE);
8463         mono_register_jit_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", helper_sig_void_void, FALSE);
8464         mono_register_jit_icall (mono_load_remote_field_new, "mono_load_remote_field_new", helper_sig_obj_obj_ptr_ptr, FALSE);
8465         mono_register_jit_icall (mono_store_remote_field_new, "mono_store_remote_field_new", helper_sig_void_obj_ptr_ptr_obj, FALSE);
8466
8467         /* 
8468          * NOTE, NOTE, NOTE, NOTE:
8469          * when adding emulation for some opcodes, remember to also add a dummy
8470          * rule to the burg files, because we need the arity information to be correct.
8471          */
8472         mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", helper_sig_long_long_long, mono_llmult, TRUE);
8473         mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", helper_sig_long_long_long, mono_llmult_ovf_un, FALSE);
8474         mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", helper_sig_long_long_long, mono_llmult_ovf, FALSE);
8475         mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", helper_sig_long_long_long, mono_lldiv, FALSE);
8476         mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", helper_sig_long_long_long, mono_lldiv_un, FALSE);
8477         mono_register_opcode_emulation (OP_LREM, "__emul_lrem", helper_sig_long_long_long, mono_llrem, FALSE);
8478         mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", helper_sig_long_long_long, mono_llrem_un, FALSE);
8479
8480 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
8481         mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", helper_sig_long_long_int, mono_lshl, TRUE);
8482         mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", helper_sig_long_long_int, mono_lshr, TRUE);
8483         mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", helper_sig_long_long_int, mono_lshr_un, TRUE);
8484 #endif
8485
8486         mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", helper_sig_ulong_double, mono_fconv_u8, FALSE);
8487         mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", helper_sig_uint_double, mono_fconv_u4, FALSE);
8488         mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", helper_sig_long_double, mono_fconv_ovf_i8, FALSE);
8489         mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", helper_sig_ulong_double, mono_fconv_ovf_u8, FALSE);
8490
8491 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
8492         mono_register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", helper_sig_long_double, mono_fconv_i8, FALSE);
8493 #endif
8494 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
8495         mono_register_opcode_emulation (CEE_CONV_R_UN, "__emul_conv_r_un", helper_sig_double_int, mono_conv_to_r8_un, FALSE);
8496 #endif
8497 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
8498         mono_register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", helper_sig_double_long, mono_lconv_to_r8, FALSE);
8499 #endif
8500 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
8501         mono_register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", helper_sig_float_long, mono_lconv_to_r4, FALSE);
8502 #endif
8503 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
8504         mono_register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", helper_sig_double_long, mono_lconv_to_r8_un, FALSE);
8505 #endif
8506 #ifdef MONO_ARCH_EMULATE_FREM
8507         mono_register_opcode_emulation (OP_FREM, "__emul_frem", helper_sig_double_double_double, fmod, FALSE);
8508 #endif
8509
8510 #if SIZEOF_VOID_P == 4
8511         mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", helper_sig_uint_double, mono_fconv_u4, TRUE);
8512 #else
8513 #ifdef __GNUC__
8514 #warning "fixme: add opcode emulation"
8515 #endif
8516 #endif
8517
8518         /* other jit icalls */
8519         mono_register_jit_icall (mono_class_static_field_address , "mono_class_static_field_address", 
8520                                  helper_sig_ptr_ptr_ptr, FALSE);
8521         mono_register_jit_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", helper_sig_ptr_ptr_ptr, FALSE);
8522         mono_register_jit_icall (mono_get_special_static_data, "mono_get_special_static_data", helper_sig_ptr_int, FALSE);
8523         mono_register_jit_icall (mono_ldstr, "mono_ldstr", helper_sig_ldstr, FALSE);
8524         mono_register_jit_icall (helper_memcpy, "helper_memcpy", helper_sig_memcpy, FALSE);
8525         mono_register_jit_icall (helper_memset, "helper_memset", helper_sig_memset, FALSE);
8526         mono_register_jit_icall (helper_initobj, "helper_initobj", helper_sig_initobj, FALSE);
8527         mono_register_jit_icall (helper_stelem_ref, "helper_stelem_ref", helper_sig_stelem_ref, FALSE);
8528         mono_register_jit_icall (helper_stelem_ref_check, "helper_stelem_ref_check", helper_sig_stelem_ref_check, FALSE);
8529         mono_register_jit_icall (mono_object_new, "mono_object_new", helper_sig_object_new, FALSE);
8530         mono_register_jit_icall (mono_object_new_specific, "mono_object_new_specific", helper_sig_object_new_specific, FALSE);
8531         mono_register_jit_icall (mono_array_new, "mono_array_new", helper_sig_newarr, FALSE);
8532         mono_register_jit_icall (mono_array_new_specific, "mono_array_new_specific", helper_sig_newarr_specific, FALSE);
8533         mono_register_jit_icall (mono_runtime_class_init, "mono_runtime_class_init", helper_sig_void_ptr, FALSE);
8534         mono_register_jit_icall (mono_ldftn, "mono_ldftn", helper_sig_compile, FALSE);
8535         mono_register_jit_icall (mono_ldftn_nosync, "mono_ldftn_nosync", helper_sig_compile, FALSE);
8536         mono_register_jit_icall (mono_ldvirtfn, "mono_ldvirtfn", helper_sig_compile_virt, FALSE);
8537 #endif
8538
8539 #define JIT_RUNTIME_WORKS
8540 #ifdef JIT_RUNTIME_WORKS
8541         mono_runtime_install_cleanup ((MonoDomainFunc)mini_cleanup);
8542         mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
8543 #endif
8544
8545         mono_thread_attach (domain);
8546         return domain;
8547 }
8548
8549 MonoJitStats mono_jit_stats = {0};
8550
8551 static void 
8552 print_jit_stats (void)
8553 {
8554         if (mono_jit_stats.enabled) {
8555                 g_print ("Mono Jit statistics\n");
8556                 g_print ("Compiled methods:       %ld\n", mono_jit_stats.methods_compiled);
8557                 g_print ("Methods from AOT:       %ld\n", mono_jit_stats.methods_aot);
8558                 g_print ("Methods cache lookup:   %ld\n", mono_jit_stats.methods_lookups);
8559                 g_print ("Method trampolines:     %ld\n", mono_jit_stats.method_trampolines);
8560                 g_print ("Basic blocks:           %ld\n", mono_jit_stats.basic_blocks);
8561                 g_print ("Max basic blocks:       %ld\n", mono_jit_stats.max_basic_blocks);
8562                 g_print ("Allocated vars:         %ld\n", mono_jit_stats.allocate_var);
8563                 g_print ("Analyze stack repeat:   %ld\n", mono_jit_stats.analyze_stack_repeat);
8564                 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
8565                 g_print ("Native code size:       %ld\n", mono_jit_stats.native_code_size);
8566                 g_print ("Max code size ratio:    %.2f (%s::%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
8567                                 mono_jit_stats.max_ratio_method->klass->name, mono_jit_stats.max_ratio_method->name);
8568                 g_print ("Biggest method:         %ld (%s::%s)\n", mono_jit_stats.biggest_method_size,
8569                                 mono_jit_stats.biggest_method->klass->name, mono_jit_stats.biggest_method->name);
8570                 g_print ("Code reallocs:          %ld\n", mono_jit_stats.code_reallocs);
8571                 g_print ("Allocated code size:    %ld\n", mono_jit_stats.allocated_code_size);
8572                 g_print ("Inlineable methods:     %ld\n", mono_jit_stats.inlineable_methods);
8573                 g_print ("Inlined methods:        %ld\n", mono_jit_stats.inlined_methods);
8574                 
8575                 g_print ("\nCreated object count:   %ld\n", mono_stats.new_object_count);
8576                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
8577                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
8578                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
8579                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
8580
8581                 g_print ("\nGeneric instances:      %ld\n", mono_stats.generic_instance_count);
8582                 g_print ("Inflated methods:       %ld\n", mono_stats.inflated_method_count);
8583                 g_print ("Inflated types:         %ld\n", mono_stats.inflated_type_count);
8584                 g_print ("Generics metadata size: %ld\n", mono_stats.generics_metadata_size);
8585         }
8586 }
8587
8588 void
8589 mini_cleanup (MonoDomain *domain)
8590 {
8591         /* 
8592          * mono_runtime_cleanup() and mono_domain_finalize () need to
8593          * be called early since they need the execution engine still
8594          * fully working (mono_domain_finalize may invoke managed finalizers
8595          * and mono_runtime_cleanup will wait for other threads to finish).
8596          */
8597         mono_domain_finalize (domain, 2000);
8598
8599         mono_runtime_cleanup (domain);
8600
8601         mono_profiler_shutdown ();
8602
8603         mono_debug_cleanup ();
8604
8605 #ifdef PLATFORM_WIN32
8606         win32_seh_cleanup();
8607 #endif
8608
8609         mono_domain_free (domain, TRUE);
8610
8611         print_jit_stats ();
8612 }
8613
8614 void
8615 mono_set_defaults (int verbose_level, guint32 opts)
8616 {
8617         mini_verbose = verbose_level;
8618         default_opt = opts;
8619 }
8620
8621 static void
8622 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
8623 {
8624         MonoImage *image = mono_assembly_get_image (ass);
8625         MonoMethod *method, *invoke;
8626         int i, count = 0;
8627
8628         if (mini_verbose > 0)
8629                 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
8630
8631         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
8632                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
8633                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
8634                         continue;
8635
8636                 count++;
8637                 if (mini_verbose > 1) {
8638                         char * desc = mono_method_full_name (method, TRUE);
8639                         g_print ("Compiling %d %s\n", count, desc);
8640                         g_free (desc);
8641                 }
8642                 mono_compile_method (method);
8643                 if (strcmp (method->name, "Finalize") == 0) {
8644                         invoke = mono_marshal_get_runtime_invoke (method);
8645                         mono_compile_method (invoke);
8646                 }
8647                 if (method->klass->marshalbyref && method->signature->hasthis) {
8648                         invoke = mono_marshal_get_remoting_invoke_with_check (method);
8649                         mono_compile_method (invoke);
8650                 }
8651         }
8652 }
8653
8654 void mono_precompile_assemblies ()
8655 {
8656         mono_assembly_foreach ((GFunc)mono_precompile_assembly, NULL);
8657 }