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