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