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