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