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