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