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