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