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