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