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