disable the intvar code because it breaks mcs compilation
[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
15 #include <mono/metadata/assembly.h>
16 #include <mono/metadata/loader.h>
17 #include <mono/metadata/cil-coff.h>
18 #include <mono/metadata/tabledefs.h>
19 #include <mono/metadata/class.h>
20 #include <mono/metadata/object.h>
21 #include <mono/metadata/exception.h>
22 #include <mono/metadata/opcodes.h>
23 #include <mono/metadata/mono-endian.h>
24 #include <mono/metadata/tokentype.h>
25 #include <mono/metadata/tabledefs.h>
26 #include <mono/metadata/threads.h>
27 #include <mono/metadata/marshal.h>
28 #include <mono/metadata/socket-io.h>
29 #include <mono/metadata/appdomain.h>
30 #include <mono/metadata/debug-helpers.h>
31 #include <mono/io-layer/io-layer.h>
32 #include "mono/metadata/profiler.h"
33 #include <mono/metadata/profiler-private.h>
34 #include <mono/metadata/mono-config.h>
35 #include <mono/metadata/environment.h>
36 #include <mono/metadata/mono-debug.h>
37 #include <mono/metadata/mono-debug-debugger.h>
38
39 #include "mini.h"
40 #include <string.h>
41 #include <ctype.h>
42 #include "inssel.h"
43
44 #include "jit-icalls.c"
45
46 #define MONO_CHECK_THIS(ins) (cfg->method->signature->hasthis && (ins)->ssa_op == MONO_SSA_LOAD && (ins)->inst_left->inst_c0 == 0)
47
48 gboolean  mono_arch_handle_exception (struct sigcontext *ctx, gpointer obj, gboolean test_only);
49 static gpointer mono_jit_compile_method (MonoMethod *method);
50
51 static void handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, 
52                           const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native);
53
54 static int mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
55                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
56                    guint inline_offset, gboolean is_virtual_call);
57
58 extern guint8 mono_burg_arity [];
59 /* helper methods signature */
60 static MonoMethodSignature *helper_sig_long_long_long = NULL;
61 static MonoMethodSignature *helper_sig_long_long_int = NULL;
62 static MonoMethodSignature *helper_sig_newarr = NULL;
63 static MonoMethodSignature *helper_sig_newarr_specific = NULL;
64 static MonoMethodSignature *helper_sig_ldstr = NULL;
65 static MonoMethodSignature *helper_sig_domain_get = NULL;
66 static MonoMethodSignature *helper_sig_object_new = NULL;
67 static MonoMethodSignature *helper_sig_object_new_specific = NULL;
68 static MonoMethodSignature *helper_sig_compile = NULL;
69 static MonoMethodSignature *helper_sig_compile_virt = NULL;
70 static MonoMethodSignature *helper_sig_obj_ptr = NULL;
71 static MonoMethodSignature *helper_sig_ptr_void = NULL;
72 static MonoMethodSignature *helper_sig_void_ptr = NULL;
73 static MonoMethodSignature *helper_sig_void_obj = NULL;
74 static MonoMethodSignature *helper_sig_void_ptr_ptr = NULL;
75 static MonoMethodSignature *helper_sig_void_ptr_ptr_ptr = NULL;
76 static MonoMethodSignature *helper_sig_ptr_ptr_ptr = NULL;
77 static MonoMethodSignature *helper_sig_ptr_obj = NULL;
78 static MonoMethodSignature *helper_sig_ptr_int = NULL;
79 static MonoMethodSignature *helper_sig_initobj = NULL;
80 static MonoMethodSignature *helper_sig_memcpy = NULL;
81 static MonoMethodSignature *helper_sig_memset = NULL;
82 static MonoMethodSignature *helper_sig_ulong_double = NULL;
83 static MonoMethodSignature *helper_sig_long_double = NULL;
84 static MonoMethodSignature *helper_sig_uint_double = NULL;
85 static MonoMethodSignature *helper_sig_int_double = NULL;
86 static MonoMethodSignature *helper_sig_stelem_ref = NULL;
87
88 static guint32 default_opt = MONO_OPT_PEEPHOLE;
89
90 guint32 mono_jit_tls_id = 0;
91 gboolean mono_jit_trace_calls = FALSE;
92 gboolean mono_break_on_exc = FALSE;
93 gboolean mono_compile_aot = FALSE;
94 gboolean mono_trace_coverage = FALSE;
95 gboolean mono_jit_profile = FALSE;
96 MonoDebugFormat mono_debug_format = MONO_DEBUG_FORMAT_NONE;
97
98 CRITICAL_SECTION *metadata_section = NULL;
99
100 static int mini_verbose = 0;
101
102 #ifdef MONO_USE_EXC_TABLES
103 static gboolean
104 mono_type_blittable (MonoType *type)
105 {
106         if (type->byref)
107                 return FALSE;
108
109         switch (type->type){
110         case MONO_TYPE_VOID:
111         case MONO_TYPE_I1:
112         case MONO_TYPE_U1:
113         case MONO_TYPE_I2:
114         case MONO_TYPE_U2:
115         case MONO_TYPE_I4:
116         case MONO_TYPE_U4:
117         case MONO_TYPE_I8:
118         case MONO_TYPE_U8:
119         case MONO_TYPE_R4:
120         case MONO_TYPE_R8:
121         case MONO_TYPE_I:
122         case MONO_TYPE_U:
123         case MONO_TYPE_OBJECT:
124                 return TRUE;
125         case MONO_TYPE_VALUETYPE:
126         case MONO_TYPE_CLASS:
127                 return type->data.klass->blittable;
128                 break;
129         default:
130                 break;
131         }
132
133         return FALSE;
134 }
135
136 gboolean
137 mono_method_blittable (MonoMethod *method)
138 {
139         MonoMethodSignature *sig;
140         int i;
141
142         if (!method->addr)
143                 return FALSE;
144
145         if (!mono_arch_has_unwind_info (method->addr)) {
146                 return FALSE;
147         }
148
149         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
150                 return TRUE;
151
152         sig = method->signature;
153
154         if (!mono_type_blittable (sig->ret))
155                 return FALSE;
156
157         for (i = 0; i < sig->param_count; i++)
158                 if (!mono_type_blittable (sig->params [i]))
159                         return FALSE;
160
161         return TRUE;
162 }
163 #endif
164
165 /* debug function */
166 static void
167 print_method_from_ip (void *ip)
168 {
169         MonoJitInfo *ji;
170         char *method;
171         
172         ji = mono_jit_info_table_find (mono_domain_get (), ip);
173         if (!ji) {
174                 g_print ("No method at %p\n", ip);
175                 return;
176         }
177         method = mono_method_full_name (ji->method, TRUE);
178         g_print ("IP at offset 0x%x of method %s (%p %p)\n", (char*)ip - (char*)ji->code_start, method, ji->code_start, (char*)ji->code_start + ji->code_size);
179         g_free (method);
180
181 }
182
183 #define MONO_INIT_VARINFO(vi,id) do { \
184         (vi)->range.first_use.pos.bid = 0xffff; \
185         (vi)->reg = -1; \
186         (vi)->idx = (id); \
187 } while (0)
188
189 /*
190  * Basic blocks have two numeric identifiers:
191  * dfn: Depth First Number
192  * block_num: unique ID assigned at bblock creation
193  */
194 #define NEW_BBLOCK(cfg) (mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock)))
195 #define ADD_BBLOCK(cfg,bbhash,b) do {   \
196                 g_hash_table_insert (bbhash, (b)->cil_code, (b));       \
197                 (b)->block_num = cfg->num_bblocks++;    \
198                 (b)->real_offset = real_offset; \
199         } while (0)
200
201 #define GET_BBLOCK(cfg,bbhash,tblock,ip) do {   \
202                 (tblock) = g_hash_table_lookup (bbhash, (ip));  \
203                 if (!(tblock)) {        \
204                         if ((ip) >= end || (ip) < header->code) goto unverified; \
205                         (tblock) = NEW_BBLOCK (cfg);    \
206                         (tblock)->cil_code = (ip);      \
207                         ADD_BBLOCK (cfg, (bbhash), (tblock));   \
208                 }       \
209                 (tblock)->real_offset = real_offset; \
210         } while (0)
211
212 #define CHECK_BBLOCK(target,ip,tblock) do {     \
213                 if ((target) < (ip) && !(tblock)->code) {       \
214                         bb_recheck = g_list_prepend (bb_recheck, (tblock));     \
215                         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);   \
216                 }       \
217         } while (0)
218
219 #define NEW_ICONST(cfg,dest,val) do {   \
220                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
221                 (dest)->opcode = OP_ICONST;     \
222                 (dest)->inst_c0 = (val);        \
223                 (dest)->type = STACK_I4;        \
224         } while (0)
225
226 /* FIXME: have a different definition of NEW_PCONST for 64 bit systems */
227 #define NEW_PCONST(cfg,dest,val) do {   \
228                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
229                 (dest)->opcode = OP_ICONST;     \
230                 (dest)->inst_p0 = (val);        \
231                 (dest)->type = STACK_PTR;       \
232         } while (0)
233
234 #define NEW_CLASSCONST(cfg,dest,val) do {       \
235                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
236                 (dest)->opcode = mono_compile_aot ? OP_AOTCONST : OP_ICONST;    \
237                 (dest)->inst_p0 = (val);        \
238                 (dest)->inst_i1 = (gpointer)MONO_PATCH_INFO_CLASS; \
239                 (dest)->type = STACK_PTR;       \
240         } while (0)
241
242 #define NEW_IMAGECONST(cfg,dest,val) do {       \
243                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
244                 (dest)->opcode = mono_compile_aot ? OP_AOTCONST : OP_ICONST;    \
245                 (dest)->inst_p0 = (val);        \
246                 (dest)->inst_i1 = (gpointer)MONO_PATCH_INFO_IMAGE; \
247                 (dest)->type = STACK_PTR;       \
248         } while (0)
249
250 #define NEW_FIELDCONST(cfg,dest,field) do {     \
251                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
252                 (dest)->opcode = mono_compile_aot ? OP_AOTCONST : OP_ICONST;    \
253                 (dest)->inst_p0 = (field);      \
254                 (dest)->inst_i1 = (gpointer)MONO_PATCH_INFO_FIELD; \
255                 (dest)->type = STACK_PTR;       \
256         } while (0)
257
258 #define NEW_METHODCONST(cfg,dest,val) do {      \
259                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
260                 (dest)->opcode = mono_compile_aot ? OP_AOTCONST : OP_ICONST;    \
261                 (dest)->inst_p0 = (val);        \
262                 (dest)->inst_i1 = (gpointer)MONO_PATCH_INFO_METHODCONST; \
263                 (dest)->type = STACK_PTR;       \
264         } while (0)
265
266 #define NEW_DOMAINCONST(cfg,dest) do { \
267                if ((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot) { \
268                        NEW_TEMPLOAD (cfg, dest, mono_get_domainvar (cfg)->inst_c0); \
269                } else { \
270                        NEW_PCONST (cfg, dest, (cfg)->domain); \
271                } \
272         } while (0)
273
274 #define GET_VARINFO_INST(cfg,num) ((cfg)->varinfo [(num)]->inst)
275
276 #define NEW_ARGLOAD(cfg,dest,num) do {  \
277                 if (arg_array [(num)]->opcode == OP_ICONST) (dest) = arg_array [(num)]; else { \
278                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
279                 (dest)->ssa_op = MONO_SSA_LOAD; \
280                 (dest)->inst_i0 = arg_array [(num)];    \
281                 (dest)->opcode = mono_type_to_ldind ((dest)->inst_i0->inst_vtype);      \
282                 type_to_eval_stack_type (param_types [(num)], (dest));  \
283                 (dest)->klass = (dest)->inst_i0->klass; \
284         }} while (0)
285
286 #define NEW_LOCLOAD(cfg,dest,num) do {  \
287                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
288                 (dest)->ssa_op = MONO_SSA_LOAD; \
289                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
290                 (dest)->opcode = mono_type_to_ldind ((dest)->inst_i0->inst_vtype);      \
291                 type_to_eval_stack_type (header->locals [(num)], (dest));       \
292                 (dest)->klass = (dest)->inst_i0->klass; \
293         } while (0)
294
295 #define NEW_LOCLOADA(cfg,dest,num) do { \
296                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
297                 (dest)->ssa_op = MONO_SSA_MAYBE_LOAD;   \
298                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
299                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
300                 (dest)->opcode = OP_LDADDR;     \
301                 (dest)->type = STACK_MP;        \
302                 (dest)->klass = (dest)->inst_i0->klass; \
303                 (cfg)->disable_ssa = TRUE; \
304         } while (0)
305
306 #define NEW_RETLOADA(cfg,dest) do {     \
307                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
308                 (dest)->ssa_op = MONO_SSA_MAYBE_LOAD;   \
309                 (dest)->inst_i0 = (cfg)->ret;   \
310                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
311                 (dest)->opcode = CEE_LDIND_I;   \
312                 (dest)->type = STACK_MP;        \
313                 (dest)->klass = (dest)->inst_i0->klass; \
314                 (cfg)->disable_ssa = TRUE; \
315         } while (0)
316
317 #define NEW_ARGLOADA(cfg,dest,num) do { \
318                 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
319                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
320                 (dest)->ssa_op = MONO_SSA_MAYBE_LOAD;   \
321                 (dest)->inst_i0 = arg_array [(num)];    \
322                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
323                 (dest)->opcode = OP_LDADDR;     \
324                 (dest)->type = STACK_MP;        \
325                 (dest)->klass = (dest)->inst_i0->klass; \
326                 (cfg)->disable_ssa = TRUE; \
327         } while (0)
328
329 #define NEW_TEMPLOAD(cfg,dest,num) do { \
330                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
331                 (dest)->ssa_op = MONO_SSA_LOAD; \
332                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
333                 (dest)->opcode = mono_type_to_ldind ((dest)->inst_i0->inst_vtype);      \
334                 type_to_eval_stack_type ((dest)->inst_i0->inst_vtype, (dest));  \
335                 (dest)->klass = (dest)->inst_i0->klass; \
336         } while (0)
337
338 #define NEW_TEMPLOADA(cfg,dest,num) do {        \
339                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
340                 (dest)->ssa_op = MONO_SSA_MAYBE_LOAD;   \
341                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
342                 (dest)->inst_i0->flags |= MONO_INST_INDIRECT;   \
343                 (dest)->opcode = OP_LDADDR;     \
344                 (dest)->type = STACK_MP;        \
345                 (dest)->klass = (dest)->inst_i0->klass; \
346                 (cfg)->disable_ssa = TRUE; \
347         } while (0)
348
349
350 #define NEW_INDLOAD(cfg,dest,addr,vtype) do {   \
351                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
352                 (dest)->inst_left = addr;       \
353                 (dest)->opcode = mono_type_to_ldind (vtype);    \
354                 type_to_eval_stack_type (vtype, (dest));        \
355                 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/     \
356         } while (0)
357
358 #define NEW_INDSTORE(cfg,dest,addr,value,vtype) do {    \
359                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
360                 (dest)->inst_i0 = addr; \
361                 (dest)->opcode = mono_type_to_stind (vtype);    \
362                 (dest)->inst_i1 = (value);      \
363                 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/     \
364         } while (0)
365
366 #define NEW_TEMPSTORE(cfg,dest,num,inst) do {   \
367                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
368                 (dest)->ssa_op = MONO_SSA_STORE;        \
369                 (dest)->inst_i0 = (cfg)->varinfo [(num)];       \
370                 (dest)->opcode = mono_type_to_stind ((dest)->inst_i0->inst_vtype);      \
371                 (dest)->inst_i1 = (inst);       \
372                 (dest)->klass = (dest)->inst_i0->klass; \
373         } while (0)
374
375 #define NEW_LOCSTORE(cfg,dest,num,inst) do {    \
376                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
377                 (dest)->opcode = mono_type_to_stind (header->locals [(num)]);   \
378                 (dest)->ssa_op = MONO_SSA_STORE;        \
379                 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)];       \
380                 (dest)->inst_i1 = (inst);       \
381                 (dest)->klass = (dest)->inst_i0->klass; \
382         } while (0)
383
384 #define NEW_ARGSTORE(cfg,dest,num,inst) do {    \
385                 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
386                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
387                 (dest)->opcode = mono_type_to_stind (param_types [(num)]);      \
388                 (dest)->ssa_op = MONO_SSA_STORE;        \
389                 (dest)->inst_i0 = arg_array [(num)];    \
390                 (dest)->inst_i1 = (inst);       \
391                 (dest)->klass = (dest)->inst_i0->klass; \
392         } while (0)
393
394 #define ADD_BINOP(op) do {      \
395                 MONO_INST_NEW (cfg, ins, (op)); \
396                 ins->cil_code = ip;     \
397                 sp -= 2;        \
398                 ins->inst_i0 = sp [0];  \
399                 ins->inst_i1 = sp [1];  \
400                 *sp++ = ins;    \
401                 type_from_op (ins);     \
402                 CHECK_TYPE (ins);       \
403         } while (0)
404
405 #define ADD_UNOP(op) do {       \
406                 MONO_INST_NEW (cfg, ins, (op)); \
407                 ins->cil_code = ip;     \
408                 sp--;   \
409                 ins->inst_i0 = sp [0];  \
410                 *sp++ = ins;    \
411                 type_from_op (ins);     \
412                 CHECK_TYPE (ins);       \
413         } while (0)
414
415 #define ADD_BINCOND(next_block) do {    \
416                 MonoInst *cmp;  \
417                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
418                 sp -= 2;                \
419                 cmp->inst_i0 = sp [0];  \
420                 cmp->inst_i1 = sp [1];  \
421                 cmp->cil_code = ins->cil_code;  \
422                 type_from_op (cmp);     \
423                 CHECK_TYPE (cmp);       \
424                 ins->inst_i0 = cmp;     \
425                 MONO_ADD_INS (bblock, ins);     \
426                 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);      \
427                 GET_BBLOCK (cfg, bbhash, tblock, target);               \
428                 link_bblock (cfg, bblock, tblock);      \
429                 ins->inst_true_bb = tblock;     \
430                 CHECK_BBLOCK (target, ip, tblock);      \
431                 if ((next_block)) {     \
432                         link_bblock (cfg, bblock, (next_block));        \
433                         ins->inst_false_bb = (next_block);      \
434                         start_new_bblock = 1;   \
435                 } else {        \
436                         GET_BBLOCK (cfg, bbhash, tblock, ip);           \
437                         link_bblock (cfg, bblock, tblock);      \
438                         ins->inst_false_bb = tblock;    \
439                         start_new_bblock = 2;   \
440                 }       \
441         } while (0)
442
443 /* FIXME: handle float, long ... */
444 #define ADD_UNCOND(istrue) do { \
445                 MonoInst *cmp;  \
446                 MONO_INST_NEW(cfg, cmp, OP_COMPARE);    \
447                 sp--;           \
448                 cmp->inst_i0 = sp [0];  \
449                 switch (cmp->inst_i0->type) { \
450                 case STACK_I8: \
451                         cmp->inst_i1 = zero_int64; break; \
452                 case STACK_R8: \
453                         cmp->inst_i1 = zero_r8; break; \
454                 case STACK_PTR: \
455                 case STACK_MP: \
456                         cmp->inst_i1 = zero_ptr; break; \
457                 case STACK_OBJ: \
458                         cmp->inst_i1 = zero_obj; break; \
459                 default: \
460                         cmp->inst_i1 = zero_int32;  \
461                 }  \
462                 cmp->cil_code = ins->cil_code;  \
463                 type_from_op (cmp);     \
464                 CHECK_TYPE (cmp);       \
465                 ins->inst_i0 = cmp;     \
466                 ins->opcode = (istrue)? CEE_BNE_UN: CEE_BEQ;    \
467                 MONO_ADD_INS (bblock, ins);     \
468                 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2);      \
469                 GET_BBLOCK (cfg, bbhash, tblock, target);               \
470                 link_bblock (cfg, bblock, tblock);      \
471                 ins->inst_true_bb = tblock;     \
472                 CHECK_BBLOCK (target, ip, tblock);      \
473                 GET_BBLOCK (cfg, bbhash, tblock, ip);           \
474                 link_bblock (cfg, bblock, tblock);      \
475                 ins->inst_false_bb = tblock;    \
476                 start_new_bblock = 2;   \
477         } while (0)
478
479 #define NEW_LDELEMA(cfg,dest,sp,k) do { \
480                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
481                 (dest)->opcode = CEE_LDELEMA;   \
482                 (dest)->inst_left = (sp) [0];   \
483                 (dest)->inst_right = (sp) [1];  \
484                 (dest)->type = STACK_MP;        \
485                 (dest)->klass = (k);    \
486         } while (0)
487
488 #define NEW_GROUP(cfg,dest,el1,el2) do {        \
489                 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));       \
490                 (dest)->opcode = OP_GROUP;      \
491                 (dest)->inst_left = (el1);      \
492                 (dest)->inst_right = (el2);     \
493         } while (0)
494
495 static GHashTable *coverage_hash = NULL;
496
497 MonoCoverageInfo *
498 mono_allocate_coverage_info (MonoMethod *method, int size)
499 {
500         MonoCoverageInfo *res;
501
502         if (!coverage_hash)
503                 coverage_hash = g_hash_table_new (NULL, NULL);
504
505         res = g_malloc0 (sizeof (MonoCoverageInfo) + sizeof (int) * size * 2);
506
507         res->entries = size;
508
509         g_hash_table_insert (coverage_hash, method, res);
510
511         return res;
512 }
513
514 MonoCoverageInfo *
515 mono_get_coverage_info (MonoMethod *method)
516 {
517         if (!coverage_hash)
518                 return NULL;
519
520         return g_hash_table_lookup (coverage_hash, method);
521 }
522                 
523 #if 0
524 static gint
525 compare_bblock (gconstpointer a, gconstpointer b)
526 {
527         const MonoBasicBlock *b1 = a;
528         const MonoBasicBlock *b2 = b;
529
530         return b2->cil_code - b1->cil_code;
531 }
532 #endif
533
534 /* *
535  * link_bblock: Links two basic blocks
536  *
537  * links two basic blocks in the control flow graph, the 'from'
538  * argument is the starting block and the 'to' argument is the block
539  * the control flow ends to after 'from'.
540  */
541 static void
542 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
543 {
544         MonoBasicBlock **newa;
545         int i, found;
546
547 #if 0
548         if (from->cil_code) {
549                 if (to->cil_code)
550                         g_print ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
551                 else
552                         g_print ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
553         } else {
554                 if (to->cil_code)
555                         g_print ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
556                 else
557                         g_print ("edge from entry to exit\n");
558         }
559 #endif
560         found = FALSE;
561         for (i = 0; i < from->out_count; ++i) {
562                 if (to == from->out_bb [i]) {
563                         found = TRUE;
564                         break;
565                 }
566         }
567         if (!found) {
568                 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
569                 for (i = 0; i < from->out_count; ++i) {
570                         newa [i] = from->out_bb [i];
571                 }
572                 newa [i] = to;
573                 from->out_count++;
574                 from->out_bb = newa;
575         }
576
577         found = FALSE;
578         for (i = 0; i < to->in_count; ++i) {
579                 if (from == to->in_bb [i]) {
580                         found = TRUE;
581                         break;
582                 }
583         }
584         if (!found) {
585                 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
586                 for (i = 0; i < to->in_count; ++i) {
587                         newa [i] = to->in_bb [i];
588                 }
589                 newa [i] = from;
590                 to->in_count++;
591                 to->in_bb = newa;
592         }
593 }
594
595 /*
596  * We mark each basic block with a region ID. We use that to avoid BB
597  * optimizations when blocks are in different regions. 
598  */
599 static int
600 mono_find_block_region (MonoCompile *cfg, int offset, int *filter_lengths)
601 {
602         MonoMethod *method = cfg->method;
603         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
604         MonoExceptionClause *clause;
605         int i;
606
607         /* first search for handlers and filters */
608         for (i = 0; i < header->num_clauses; ++i) {
609                 clause = &header->clauses [i];
610                 if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->token_or_filter) &&
611                     (offset < (clause->token_or_filter + filter_lengths [i])))
612                         return (i << 8) | 128 | clause->flags;
613                            
614                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
615                         return (i << 8) | 64 | clause->flags;
616                 }
617         }
618
619         /* search the try blocks */
620         for (i = 0; i < header->num_clauses; ++i) {
621                 clause = &header->clauses [i];
622                 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
623                         return (i << 8) | clause->flags;
624         }
625
626         return -1;
627 }
628
629 static GList*
630 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
631 {
632         MonoMethod *method = cfg->method;
633         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
634         MonoExceptionClause *clause;
635         MonoBasicBlock *handler;
636         int i;
637         GList *res = NULL;
638
639         for (i = 0; i < header->num_clauses; ++i) {
640                 clause = &header->clauses [i];
641                 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) && 
642                     (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
643                         if (clause->flags == type) {
644                                 handler = g_hash_table_lookup (cfg->bb_hash, header->code + clause->handler_offset);
645                                 g_assert (handler);
646                                 res = g_list_append (res, handler);
647                         }
648                 }
649         }
650         return res;
651 }
652
653
654 static void
655 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
656 {
657         int i;
658
659         array [*dfn] = start;
660         /*g_print ("visit %d at %p\n", *dfn, start->cil_code);*/
661         for (i = 0; i < start->out_count; ++i) {
662                 if (start->out_bb [i]->dfn)
663                         continue;
664                 (*dfn)++;
665                 start->out_bb [i]->dfn = *dfn;
666                 start->out_bb [i]->df_parent = start;
667                 array [*dfn] = start->out_bb [i];
668                 df_visit (start->out_bb [i], dfn, array);
669         }
670 }
671
672 typedef struct {
673         const guchar *code;
674         MonoBasicBlock *best;
675 } PrevStruct;
676
677 static void
678 previous_foreach (gconstpointer key, gpointer val, gpointer data)
679 {
680         PrevStruct *p = data;
681         MonoBasicBlock *bb = val;
682         //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,
683         //bb->method == p->best->method, bb->cil_code < p->code, bb->cil_code > p->best->cil_code);
684
685         if (bb->cil_code && bb->cil_code < p->code && bb->cil_code > p->best->cil_code)
686                 p->best = bb;
687 }
688
689 static MonoBasicBlock*
690 find_previous (GHashTable *bb_hash, MonoBasicBlock *start, const guchar *code) {
691         PrevStruct p;
692
693         p.code = code;
694         p.best = start;
695
696         g_hash_table_foreach (bb_hash, (GHFunc)previous_foreach, &p);
697         return p.best;
698 }
699
700 static void
701 split_bblock (MonoCompile *cfg, MonoBasicBlock *first, MonoBasicBlock *second) {
702         int i, j;
703         MonoInst *inst;
704         MonoBasicBlock *bb;
705
706         if (second->code)
707                 return;
708         
709         /* 
710          * FIXME: take into account all the details:
711          * second may have been the target of more than one bblock
712          */
713         second->out_count = first->out_count;
714         second->out_bb = first->out_bb;
715
716         for (i = 0; i < first->out_count; ++i) {
717                 bb = first->out_bb [i];
718                 for (j = 0; j < bb->in_count; ++j) {
719                         if (bb->in_bb [j] == first)
720                                 bb->in_bb [j] = second;
721                 }
722         }
723
724         first->out_count = 0;
725         first->out_bb = NULL;
726         link_bblock (cfg, first, second);
727
728         second->last_ins = first->last_ins;
729
730         /*g_print ("start search at %p for %p\n", first->cil_code, second->cil_code);*/
731         for (inst = first->code; inst && inst->next; inst = inst->next) {
732                 /*char *code = mono_disasm_code_one (NULL, cfg->method, inst->next->cil_code, NULL);
733                 g_print ("found %p: %s", inst->next->cil_code, code);
734                 g_free (code);*/
735                 if (inst->cil_code < second->cil_code && inst->next->cil_code >= second->cil_code) {
736                         second->code = inst->next;
737                         inst->next = NULL;
738                         first->last_ins = inst;
739                         second->next_bb = first->next_bb;
740                         first->next_bb = second;
741                         return;
742                 }
743         }
744         if (!second->code) {
745                 g_warning ("bblock split failed in %s::%s\n", cfg->method->klass->name, cfg->method->name);
746                 //G_BREAKPOINT ();
747         }
748 }
749
750 guint
751 mono_type_to_ldind (MonoType *type)
752 {
753         int t = type->type;
754
755         if (type->byref)
756                 return CEE_LDIND_I;
757
758 handle_enum:
759         switch (t) {
760         case MONO_TYPE_I1:
761                 return CEE_LDIND_I1;
762         case MONO_TYPE_U1:
763         case MONO_TYPE_BOOLEAN:
764                 return CEE_LDIND_U1;
765         case MONO_TYPE_I2:
766                 return CEE_LDIND_I2;
767         case MONO_TYPE_U2:
768         case MONO_TYPE_CHAR:
769                 return CEE_LDIND_U2;
770         case MONO_TYPE_I4:
771                 return CEE_LDIND_I4;
772         case MONO_TYPE_U4:
773                 return CEE_LDIND_U4;
774         case MONO_TYPE_I:
775         case MONO_TYPE_U:
776         case MONO_TYPE_PTR:
777         case MONO_TYPE_FNPTR:
778                 return CEE_LDIND_I;
779         case MONO_TYPE_CLASS:
780         case MONO_TYPE_STRING:
781         case MONO_TYPE_OBJECT:
782         case MONO_TYPE_SZARRAY:
783         case MONO_TYPE_ARRAY:    
784                 return CEE_LDIND_REF;
785         case MONO_TYPE_I8:
786         case MONO_TYPE_U8:
787                 return CEE_LDIND_I8;
788         case MONO_TYPE_R4:
789                 return CEE_LDIND_R4;
790         case MONO_TYPE_R8:
791                 return CEE_LDIND_R8;
792         case MONO_TYPE_VALUETYPE:
793                 if (type->data.klass->enumtype) {
794                         t = type->data.klass->enum_basetype->type;
795                         goto handle_enum;
796                 }
797                 return CEE_LDOBJ;
798         default:
799                 g_error ("unknown type 0x%02x in type_to_ldind", type->type);
800         }
801         return -1;
802 }
803
804 guint
805 mono_type_to_stind (MonoType *type)
806 {
807         int t = type->type;
808
809         if (type->byref)
810                 return CEE_STIND_I;
811
812 handle_enum:
813         switch (t) {
814         case MONO_TYPE_I1:
815         case MONO_TYPE_U1:
816         case MONO_TYPE_BOOLEAN:
817                 return CEE_STIND_I1;
818         case MONO_TYPE_I2:
819         case MONO_TYPE_U2:
820         case MONO_TYPE_CHAR:
821                 return CEE_STIND_I2;
822         case MONO_TYPE_I4:
823         case MONO_TYPE_U4:
824                 return CEE_STIND_I4;
825         case MONO_TYPE_I:
826         case MONO_TYPE_U:
827         case MONO_TYPE_PTR:
828         case MONO_TYPE_FNPTR:
829                 return CEE_STIND_I;
830         case MONO_TYPE_CLASS:
831         case MONO_TYPE_STRING:
832         case MONO_TYPE_OBJECT:
833         case MONO_TYPE_SZARRAY:
834         case MONO_TYPE_ARRAY:    
835                 return CEE_STIND_REF;
836         case MONO_TYPE_I8:
837         case MONO_TYPE_U8:
838                 return CEE_STIND_I8;
839         case MONO_TYPE_R4:
840                 return CEE_STIND_R4;
841         case MONO_TYPE_R8:
842                 return CEE_STIND_R8;
843         case MONO_TYPE_VALUETYPE:
844                 if (type->data.klass->enumtype) {
845                         t = type->data.klass->enum_basetype->type;
846                         goto handle_enum;
847                 }
848                 return CEE_STOBJ;
849                 /* fail right now */
850         default:
851                 g_error ("unknown type %02x in type_to_stind", type->type);
852         }
853         return -1;
854 }
855
856 /*
857  * Returns the type used in the eval stack when @type is loaded.
858  * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
859  */
860 static void
861 type_to_eval_stack_type (MonoType *type, MonoInst *inst) {
862         int t = type->type;
863
864         if (type->byref) {
865                 inst->type = STACK_MP;
866                 return;
867         }
868
869 handle_enum:
870         switch (t) {
871         case MONO_TYPE_I1:
872         case MONO_TYPE_U1:
873         case MONO_TYPE_BOOLEAN:
874         case MONO_TYPE_I2:
875         case MONO_TYPE_U2:
876         case MONO_TYPE_CHAR:
877         case MONO_TYPE_I4:
878         case MONO_TYPE_U4:
879                 inst->type = STACK_I4;
880                 return;
881         case MONO_TYPE_I:
882         case MONO_TYPE_U:
883         case MONO_TYPE_PTR:
884         case MONO_TYPE_FNPTR:
885                 inst->type = STACK_PTR;
886                 return;
887         case MONO_TYPE_CLASS:
888         case MONO_TYPE_STRING:
889         case MONO_TYPE_OBJECT:
890         case MONO_TYPE_SZARRAY:
891         case MONO_TYPE_ARRAY:    
892                 inst->type = STACK_OBJ;
893                 return;
894         case MONO_TYPE_I8:
895         case MONO_TYPE_U8:
896                 inst->type = STACK_I8;
897                 return;
898         case MONO_TYPE_R4:
899         case MONO_TYPE_R8:
900                 inst->type = STACK_R8;
901                 return;
902         case MONO_TYPE_VALUETYPE:
903                 if (type->data.klass->enumtype) {
904                         t = type->data.klass->enum_basetype->type;
905                         goto handle_enum;
906                 } else {
907                         inst->klass = type->data.klass;
908                         inst->type = STACK_VTYPE;
909                         return;
910                 }
911         default:
912                 g_error ("unknown type 0x%02x in eval stack type", type->type);
913         }
914 }
915
916 /*
917  * The following tables are used to quickly validate the IL code in type_from_op ().
918  */
919 static const char
920 bin_num_table [STACK_MAX] [STACK_MAX] = {
921         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
922         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
923         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
924         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP,  STACK_INV, STACK_INV},
925         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8,  STACK_INV, STACK_INV, STACK_INV},
926         {STACK_INV, STACK_MP,  STACK_INV, STACK_MP,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
927         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
928         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
929 };
930
931 static const char 
932 neg_table [] = {
933         STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV
934 };
935
936 /* reduce the size of this table */
937 static const char
938 bin_int_table [STACK_MAX] [STACK_MAX] = {
939         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
940         {STACK_INV, STACK_I4,  STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
941         {STACK_INV, STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
942         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
943         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
944         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
945         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
946         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
947 };
948
949 static const char
950 bin_comp_table [STACK_MAX] [STACK_MAX] = {
951         {0},
952         {0, 1, 0, 1, 0, 0, 4, 0},
953         {0, 0, 1, 0, 0, 0, 0, 0},
954         {0, 1, 0, 1, 0, 2, 4, 0},
955         {0, 0, 0, 0, 1, 0, 0, 0},
956         {0, 0, 0, 2, 0, 1, 0, 0},
957         {0, 4, 0, 4, 0, 0, 3, 0},
958         {0, 0, 0, 0, 0, 0, 0, 0},
959 };
960
961 /* reduce the size of this table */
962 static const char
963 shift_table [STACK_MAX] [STACK_MAX] = {
964         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
965         {STACK_INV, STACK_I4,  STACK_INV, STACK_I4,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
966         {STACK_INV, STACK_I8,  STACK_INV, STACK_I8,  STACK_INV, STACK_INV, STACK_INV, STACK_INV},
967         {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
968         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
969         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
970         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
971         {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
972 };
973
974 /*
975  * Tables to map from the non-specific opcode to the matching
976  * type-specific opcode.
977  */
978 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
979 static const guint16
980 binops_op_map [STACK_MAX] = {
981         0, 0, OP_LADD-CEE_ADD, OP_PADD-CEE_ADD, OP_FADD-CEE_ADD, 0
982 };
983
984 /* handles from CEE_NEG to CEE_CONV_U8 */
985 static const guint16
986 unops_op_map [STACK_MAX] = {
987         0, 0, OP_LNEG-CEE_NEG, OP_PNEG-CEE_NEG, OP_FNEG-CEE_NEG, 0
988 };
989
990 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
991 static const guint16
992 ovfops_op_map [STACK_MAX] = {
993         0, 0, OP_LCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, OP_FCONV_TO_U2-CEE_CONV_U2, 0
994 };
995
996 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
997 static const guint16
998 ovf2ops_op_map [STACK_MAX] = {
999         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
1000 };
1001
1002 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
1003 static const guint16
1004 ovf3ops_op_map [STACK_MAX] = {
1005         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
1006 };
1007
1008 /* handles from CEE_CEQ to CEE_CLT_UN */
1009 static const guint16
1010 ceqops_op_map [STACK_MAX] = {
1011         0, 0, OP_LCEQ-CEE_CEQ, OP_PCEQ-CEE_CEQ, OP_FCEQ-CEE_CEQ, 0
1012 };
1013
1014 /*
1015  * Sets ins->type (the type on the eval stack) according to the
1016  * type of the opcode and the arguments to it.
1017  * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
1018  *
1019  * FIXME: this function sets ins->type unconditionally in some cases, but
1020  * it should set it to invalid for some types (a conv.x on an object)
1021  */
1022 static void
1023 type_from_op (MonoInst *ins) {
1024         switch (ins->opcode) {
1025         /* binops */
1026         case CEE_ADD:
1027         case CEE_SUB:
1028         case CEE_MUL:
1029         case CEE_DIV:
1030         case CEE_REM:
1031                 /* FIXME: check unverifiable args for STACK_MP */
1032                 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1033                 ins->opcode += binops_op_map [ins->type];
1034                 return;
1035         case CEE_DIV_UN:
1036         case CEE_REM_UN:
1037         case CEE_AND:
1038         case CEE_OR:
1039         case CEE_XOR:
1040                 ins->type = bin_int_table [ins->inst_i0->type] [ins->inst_i1->type];
1041                 ins->opcode += binops_op_map [ins->type];
1042                 return;
1043         case CEE_SHL:
1044         case CEE_SHR:
1045         case CEE_SHR_UN:
1046                 ins->type = shift_table [ins->inst_i0->type] [ins->inst_i1->type];
1047                 ins->opcode += binops_op_map [ins->type];
1048                 return;
1049         case OP_COMPARE:
1050                 /* FIXME: handle some specifics with ins->next->type */
1051                 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1052                 return;
1053         case 256+CEE_CEQ:
1054         case 256+CEE_CGT:
1055         case 256+CEE_CGT_UN:
1056         case 256+CEE_CLT:
1057         case 256+CEE_CLT_UN:
1058                 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1059                 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1060                 return;
1061         /* unops */
1062         case CEE_NEG:
1063                 ins->type = neg_table [ins->inst_i0->type];
1064                 ins->opcode += unops_op_map [ins->type];
1065                 return;
1066         case CEE_NOT:
1067                 if (ins->inst_i0->type >= STACK_I4 && ins->inst_i0->type <= STACK_PTR)
1068                         ins->type = ins->inst_i0->type;
1069                 else
1070                         ins->type = STACK_INV;
1071                 ins->opcode += unops_op_map [ins->type];
1072                 return;
1073         case CEE_CONV_I1:
1074         case CEE_CONV_I2:
1075         case CEE_CONV_I4:
1076         case CEE_CONV_U4:
1077                 ins->type = STACK_I4;
1078                 ins->opcode += unops_op_map [ins->inst_i0->type];
1079                 return;
1080         case CEE_CONV_R_UN:
1081                 ins->type = STACK_R8;
1082                 switch (ins->inst_i0->type) {
1083                 case STACK_I4:
1084                 case STACK_PTR:
1085                         break;
1086                 case STACK_I8:
1087                         ins->opcode = OP_LCONV_TO_R_UN; 
1088                         break;
1089                 }
1090                 return;
1091         case CEE_CONV_OVF_I1:
1092         case CEE_CONV_OVF_U1:
1093         case CEE_CONV_OVF_I2:
1094         case CEE_CONV_OVF_U2:
1095         case CEE_CONV_OVF_I4:
1096         case CEE_CONV_OVF_U4:
1097                 ins->type = STACK_I4;
1098                 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1099                 return;
1100         case CEE_CONV_OVF_I_UN:
1101         case CEE_CONV_OVF_U_UN:
1102                 ins->type = STACK_PTR;
1103                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1104                 return;
1105         case CEE_CONV_OVF_I1_UN:
1106         case CEE_CONV_OVF_I2_UN:
1107         case CEE_CONV_OVF_I4_UN:
1108         case CEE_CONV_OVF_U1_UN:
1109         case CEE_CONV_OVF_U2_UN:
1110         case CEE_CONV_OVF_U4_UN:
1111                 ins->type = STACK_I4;
1112                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1113                 return;
1114         case CEE_CONV_U:
1115                 ins->type = STACK_PTR;
1116                 switch (ins->inst_i0->type) {
1117                 case STACK_I4:
1118                 case STACK_PTR:
1119                 case STACK_MP:
1120                         break;
1121                 case STACK_I8:
1122                         ins->opcode = OP_LCONV_TO_U;
1123                         break;
1124                 case STACK_R8:
1125                         ins->opcode = OP_FCONV_TO_U;
1126                         break;
1127                 }
1128                 return;
1129         case CEE_CONV_I8:
1130         case CEE_CONV_U8:
1131                 ins->type = STACK_I8;
1132                 ins->opcode += unops_op_map [ins->inst_i0->type];
1133                 return;
1134         case CEE_CONV_OVF_I8:
1135         case CEE_CONV_OVF_U8:
1136                 ins->type = STACK_I8;
1137                 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1138                 return;
1139         case CEE_CONV_OVF_U8_UN:
1140         case CEE_CONV_OVF_I8_UN:
1141                 ins->type = STACK_I8;
1142                 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1143                 return;
1144         case CEE_CONV_R4:
1145         case CEE_CONV_R8:
1146                 ins->type = STACK_R8;
1147                 ins->opcode += unops_op_map [ins->inst_i0->type];
1148                 return;
1149         case CEE_CKFINITE:
1150                 ins->type = STACK_R8;           
1151                 return;
1152         case CEE_CONV_U2:
1153         case CEE_CONV_U1:
1154                 ins->type = STACK_I4;
1155                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1156                 break;
1157         case CEE_CONV_I:
1158         case CEE_CONV_OVF_I:
1159         case CEE_CONV_OVF_U:
1160                 ins->type = STACK_PTR;
1161                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1162                 return;
1163         case CEE_ADD_OVF:
1164         case CEE_ADD_OVF_UN:
1165         case CEE_MUL_OVF:
1166         case CEE_MUL_OVF_UN:
1167         case CEE_SUB_OVF:
1168         case CEE_SUB_OVF_UN:
1169                 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1170                 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1171                 return;
1172         default:
1173                 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1174                 break;
1175         }
1176 }
1177
1178 static const char 
1179 ldind_type [] = {
1180         STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I8, STACK_MP, STACK_R8, STACK_R8, STACK_OBJ
1181 };
1182
1183 /* map ldelem.x to the matching ldind.x opcode */
1184 static const guchar
1185 ldelem_to_ldind [] = {
1186         CEE_LDIND_I1,
1187         CEE_LDIND_U1,
1188         CEE_LDIND_I2,
1189         CEE_LDIND_U2,
1190         CEE_LDIND_I4,
1191         CEE_LDIND_U4,
1192         CEE_LDIND_I8,
1193         CEE_LDIND_I,
1194         CEE_LDIND_R4,
1195         CEE_LDIND_R8,
1196         CEE_LDIND_REF
1197 };
1198
1199 /* map stelem.x to the matching stind.x opcode */
1200 static const guchar
1201 stelem_to_stind [] = {
1202         CEE_STIND_I,
1203         CEE_STIND_I1,
1204         CEE_STIND_I2,
1205         CEE_STIND_I4,
1206         CEE_STIND_I8,
1207         CEE_STIND_R4,
1208         CEE_STIND_R8,
1209         CEE_STIND_REF
1210 };
1211
1212 #if 0
1213
1214 static const char
1215 param_table [STACK_MAX] [STACK_MAX] = {
1216         {0},
1217 };
1218
1219 static int
1220 check_values_to_signature (MonoInst *args, MonoType *this, MonoMethodSignature *sig) {
1221         int i;
1222
1223         if (sig->hasthis) {
1224                 switch (args->type) {
1225                 case STACK_I4:
1226                 case STACK_I8:
1227                 case STACK_R8:
1228                 case STACK_VTYPE:
1229                 case STACK_INV:
1230                         return 0;
1231                 }
1232                 args++;
1233         }
1234         for (i = 0; i < sig->param_count; ++i) {
1235                 switch (args [i].type) {
1236                 case STACK_INV:
1237                         return 0;
1238                 case STACK_MP:
1239                         if (!sig->params [i]->byref)
1240                                 return 0;
1241                         continue;
1242                 case STACK_OBJ:
1243                         if (sig->params [i]->byref)
1244                                 return 0;
1245                         switch (sig->params [i]->type) {
1246                         case MONO_TYPE_CLASS:
1247                         case MONO_TYPE_STRING:
1248                         case MONO_TYPE_OBJECT:
1249                         case MONO_TYPE_SZARRAY:
1250                         case MONO_TYPE_ARRAY:
1251                                 break;
1252                         default:
1253                                 return 0;
1254                         }
1255                         continue;
1256                 case STACK_R8:
1257                         if (sig->params [i]->byref)
1258                                 return 0;
1259                         if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1260                                 return 0;
1261                         continue;
1262                 case STACK_PTR:
1263                 case STACK_I4:
1264                 case STACK_I8:
1265                 case STACK_VTYPE:
1266                         break;
1267                 }
1268                 /*if (!param_table [args [i].type] [sig->params [i]->type])
1269                         return 0;*/
1270         }
1271         return 1;
1272 }
1273 #endif
1274
1275 /*
1276  * When we need a pointer to the current domain many times in a method, we
1277  * call mono_domain_get() once and we store the result in a local variable.
1278  * This function returns the variable that represents the MonoDomain*.
1279  */
1280 inline static MonoInst *
1281 mono_get_domainvar (MonoCompile *cfg)
1282 {
1283         if (!cfg->domainvar)
1284                 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1285         return cfg->domainvar;
1286 }
1287
1288 MonoInst*
1289 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1290 {
1291         MonoInst *inst;
1292         int num = cfg->num_varinfo;
1293
1294         if ((num + 1) >= cfg->varinfo_count) {
1295                 cfg->varinfo_count = (cfg->varinfo_count + 2) * 2;
1296                 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
1297                 cfg->vars = (MonoMethodVar **)g_realloc (cfg->vars, sizeof (MonoMethodVar*) * cfg->varinfo_count);      
1298         }
1299
1300         mono_jit_stats.allocate_var++;
1301
1302         MONO_INST_NEW (cfg, inst, opcode);
1303         inst->inst_c0 = num;
1304         inst->inst_vtype = type;
1305         inst->klass = mono_class_from_mono_type (type);
1306         /* if set to 1 the variable is native */
1307         inst->unused = 0;
1308
1309         cfg->varinfo [num] = inst;
1310
1311         cfg->vars [num] = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoMethodVar));
1312         MONO_INIT_VARINFO (cfg->vars [num], num);
1313
1314         cfg->num_varinfo++;
1315         //g_print ("created temp %d of type %s\n", num, mono_type_get_name (type));
1316         return inst;
1317 }
1318
1319 static MonoType*
1320 type_from_stack_type (MonoInst *ins) {
1321         switch (ins->type) {
1322         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1323         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1324         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1325         case STACK_R8: return &mono_defaults.double_class->byval_arg;
1326         case STACK_MP: return &mono_defaults.int_class->byval_arg;
1327         case STACK_OBJ: return &mono_defaults.object_class->byval_arg;
1328         case STACK_VTYPE: return &ins->klass->byval_arg;
1329         default:
1330                 g_error ("stack type %d to montype not handled\n", ins->type);
1331         }
1332         return NULL;
1333 }
1334
1335 static MonoClass*
1336 array_access_to_klass (int opcode)
1337 {
1338         switch (opcode) {
1339         case CEE_LDELEM_U1:
1340                 return mono_defaults.byte_class;
1341         case CEE_LDELEM_U2:
1342                 return mono_defaults.uint16_class;
1343         case CEE_LDELEM_I:
1344         case CEE_STELEM_I:
1345                 return mono_defaults.int_class;
1346         case CEE_LDELEM_I1:
1347         case CEE_STELEM_I1:
1348                 return mono_defaults.sbyte_class;
1349         case CEE_LDELEM_I2:
1350         case CEE_STELEM_I2:
1351                 return mono_defaults.int16_class;
1352         case CEE_LDELEM_I4:
1353         case CEE_STELEM_I4:
1354                 return mono_defaults.int32_class;
1355         case CEE_LDELEM_U4:
1356                 return mono_defaults.uint32_class;
1357         case CEE_LDELEM_I8:
1358         case CEE_STELEM_I8:
1359                 return mono_defaults.int64_class;
1360         case CEE_LDELEM_R4:
1361         case CEE_STELEM_R4:
1362                 return mono_defaults.single_class;
1363         case CEE_LDELEM_R8:
1364         case CEE_STELEM_R8:
1365                 return mono_defaults.double_class;
1366         case CEE_LDELEM_REF:
1367         case CEE_STELEM_REF:
1368                 return mono_defaults.object_class;
1369         default:
1370                 g_assert_not_reached ();
1371         }
1372         return NULL;
1373 }
1374
1375 static void
1376 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
1377 {
1378         MonoInst *prev;
1379         if (!bb->code) {
1380                 MONO_ADD_INS (bb, inst);
1381                 return;
1382         }
1383         switch (bb->last_ins->opcode) {
1384         case CEE_BEQ:
1385         case CEE_BGE:
1386         case CEE_BGT:
1387         case CEE_BLE:
1388         case CEE_BLT:
1389         case CEE_BNE_UN:
1390         case CEE_BGE_UN:
1391         case CEE_BGT_UN:
1392         case CEE_BLE_UN:
1393         case CEE_BLT_UN:
1394         case CEE_BR:
1395                 prev = bb->code;
1396                 while (prev->next && prev->next != bb->last_ins)
1397                         prev = prev->next;
1398                 if (prev == bb->code) {
1399                         if (bb->last_ins == bb->code) {
1400                                 inst->next = bb->code;
1401                                 bb->code = inst;
1402                         } else {
1403                                 inst->next = prev->next;
1404                                 prev->next = inst;
1405                         }
1406                 } else {
1407                         inst->next = bb->last_ins;
1408                         prev->next = inst;
1409                 }
1410                 break;
1411         //      g_warning ("handle conditional jump in add_ins_to_end ()\n");
1412         default:
1413                 MONO_ADD_INS (bb, inst);
1414                 break;
1415         }
1416 }
1417
1418 void
1419 mono_add_varcopy_to_end (MonoCompile *cfg, MonoBasicBlock *bb, int src, int dest)
1420 {
1421         MonoInst *inst, *load;
1422
1423         NEW_TEMPLOAD (cfg, load, src);
1424
1425         NEW_TEMPSTORE (cfg, inst, dest, load);
1426         if (inst->opcode == CEE_STOBJ) {
1427                 NEW_TEMPLOADA (cfg, inst, dest);
1428                 handle_stobj (cfg, bb, inst, load, NULL, inst->klass, TRUE, FALSE);
1429         } else {
1430                 inst->cil_code = NULL;
1431                 mono_add_ins_to_end (bb, inst);
1432         }
1433 }
1434
1435 /*
1436  * We try to share variables when possible
1437  */
1438 static MonoInst *
1439 mono_compile_get_interface_var (MonoCompile *cfg, int slot, MonoInst *ins)
1440 {
1441         MonoInst *res;
1442         int pos, vnum;
1443
1444         /* inlining can result in deeper stacks */ 
1445         if (slot >= ((MonoMethodNormal *)cfg->method)->header->max_stack)
1446                 return mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1447
1448         pos = ins->type - 1 + slot * STACK_MAX;
1449
1450         switch (ins->type) {
1451         case STACK_I4:
1452         case STACK_I8:
1453         case STACK_R8:
1454         case STACK_PTR:
1455         case STACK_MP:
1456         case STACK_OBJ:
1457                 if ((vnum = cfg->intvars [pos]))
1458                         return cfg->varinfo [vnum];
1459                 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1460                 cfg->intvars [pos] = res->inst_c0;
1461                 break;
1462         default:
1463                 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1464         }
1465         return res;
1466 }
1467
1468 /*
1469  * This function is called to handle items that are left on the evaluation stack
1470  * at basic block boundaries. What happens is that we save the values to local variables
1471  * and we reload them later when first entering the target basic block (with the
1472  * handle_loaded_temps () function).
1473  * A single joint point will use the same variables (stored in the array bb->out_stack or
1474  * bb->in_stack, if the basic block is before or after the joint point).
1475  */
1476 static int
1477 handle_stack_args (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **sp, int count) {
1478         int i;
1479         MonoBasicBlock *outb;
1480         MonoInst *inst, **locals;
1481
1482         if (!count)
1483                 return 0;
1484         if (cfg->verbose_level > 3)
1485                 g_print ("%d item(s) on exit from B%d\n", count, bb->block_num);
1486         if (!bb->out_scount) {
1487                 int found = 0;
1488                 bb->out_scount = count;
1489                 //g_print ("bblock %d has out:", bb->block_num);
1490                 for (i = 0; i < bb->out_count; ++i) {
1491                         outb = bb->out_bb [i];
1492                         //g_print (" %d", outb->block_num);
1493                         if (outb->in_stack) {
1494                                 found = 1;
1495                                 bb->out_stack = outb->in_stack;
1496                                 break;
1497                         }
1498                 }
1499                 //g_print ("\n");
1500                 if (!found) {
1501                         bb->out_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
1502                         for (i = 0; i < count; ++i) {
1503 #if 0
1504                                 /* recompiling mcs fails with this */
1505                                 /* try to reuse temps already allocated for this purpouse, if they occupy the same 
1506                                  * stack slot and if they are of the same type. */
1507                                 bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
1508 #else
1509                                 bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
1510 #endif
1511                         }
1512                 }
1513         }
1514         locals = bb->out_stack;
1515         for (i = 0; i < count; ++i) {
1516                 /* add store ops at the end of the bb, before the branch */
1517                 NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
1518                 if (inst->opcode == CEE_STOBJ) {
1519                         NEW_TEMPLOADA (cfg, inst, locals [i]->inst_c0);
1520                         handle_stobj (cfg, bb, inst, sp [i], sp [i]->cil_code, inst->klass, TRUE, FALSE);
1521                 } else {
1522                         inst->cil_code = sp [i]->cil_code;
1523                         mono_add_ins_to_end (bb, inst);
1524                 }
1525                 if (cfg->verbose_level > 3)
1526                         g_print ("storing %d to temp %d\n", i, locals [i]->inst_c0);
1527         }
1528         
1529         for (i = 0; i < bb->out_count; ++i) {
1530                 outb = bb->out_bb [i];
1531                 if (outb->in_scount)
1532                         continue; /* check they are the same locals */
1533                 outb->in_scount = count;
1534                 outb->in_stack = locals;
1535         }
1536         return 0;
1537 }
1538
1539 static int
1540 ret_type_to_call_opcode (MonoType *type, int calli, int virt)
1541 {
1542         int t = type->type;
1543
1544         if (type->byref)
1545                 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
1546
1547 handle_enum:
1548         switch (t) {
1549         case MONO_TYPE_VOID:
1550                 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALLVIRT: OP_VOIDCALL;
1551         case MONO_TYPE_I1:
1552         case MONO_TYPE_U1:
1553         case MONO_TYPE_BOOLEAN:
1554         case MONO_TYPE_I2:
1555         case MONO_TYPE_U2:
1556         case MONO_TYPE_CHAR:
1557         case MONO_TYPE_I4:
1558         case MONO_TYPE_U4:
1559                 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
1560         case MONO_TYPE_I:
1561         case MONO_TYPE_U:
1562         case MONO_TYPE_PTR:
1563                 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
1564         case MONO_TYPE_CLASS:
1565         case MONO_TYPE_STRING:
1566         case MONO_TYPE_OBJECT:
1567         case MONO_TYPE_SZARRAY:
1568         case MONO_TYPE_ARRAY:    
1569                 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
1570         case MONO_TYPE_I8:
1571         case MONO_TYPE_U8:
1572                 return calli? OP_LCALL_REG: virt? OP_LCALLVIRT: OP_LCALL;
1573         case MONO_TYPE_R4:
1574         case MONO_TYPE_R8:
1575                 return calli? OP_FCALL_REG: virt? OP_FCALLVIRT: OP_FCALL;
1576         case MONO_TYPE_VALUETYPE:
1577                 if (type->data.klass->enumtype) {
1578                         t = type->data.klass->enum_basetype->type;
1579                         goto handle_enum;
1580                 } else
1581                         return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
1582         default:
1583                 g_error ("unknown type %02x in ret_type_to_call_opcode", type->type);
1584         }
1585         return -1;
1586 }
1587
1588 void
1589 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
1590 {
1591         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
1592         
1593         ji->ip.label = label;
1594         ji->type = MONO_PATCH_INFO_SWITCH;
1595         ji->data.table = bbs;
1596         ji->next = cfg->patch_info;
1597         ji->table_size = num_blocks;
1598         cfg->patch_info = ji;
1599 }
1600
1601 /*
1602  * When we add a tree of instructions, we need to ensure the instructions currently
1603  * on the stack are executed before (like, if we load a value from a local).
1604  * We ensure this by saving the currently loaded values to temps and rewriting the
1605  * instructions to load the values.
1606  * This is not done for opcodes that terminate a basic block (because it's handled already
1607  * by handle_stack_args ()) and for opcodes that can't change values, like POP.
1608  */
1609 static void
1610 handle_loaded_temps (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst **stack, MonoInst **sp)
1611 {
1612         MonoInst *load, *store, *temp, *ins;
1613
1614         while (stack < sp) {
1615                 ins = *stack;
1616                 /* handle also other constants */
1617                 if (ins->opcode != OP_ICONST) {
1618                         temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1619                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
1620                         store->cil_code = ins->cil_code;
1621                         if (store->opcode == CEE_STOBJ) {
1622                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
1623                                 handle_stobj (cfg, bblock, store, ins, ins->cil_code, temp->klass, FALSE, FALSE);
1624                         } else
1625                                 MONO_ADD_INS (bblock, store);
1626                         NEW_TEMPLOAD (cfg, load, temp->inst_c0);
1627                         load->cil_code = ins->cil_code;
1628                         *stack = load;
1629                 }
1630                 stack++;
1631         }
1632 }
1633
1634 inline static int
1635 mono_spill_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoCallInst *call, MonoMethodSignature *sig, gboolean ret_object, 
1636                  const guint8 *ip, gboolean to_end)
1637 {
1638         MonoInst *temp, *store, *ins = (MonoInst*)call;
1639         MonoType *ret = sig->ret;
1640
1641         if (!MONO_TYPE_IS_VOID (ret) || ret_object) {
1642                 if (ret_object) {
1643                         call->inst.type = STACK_OBJ;
1644                         call->inst.opcode = CEE_CALL;
1645                         temp = mono_compile_create_var (cfg, &mono_defaults.string_class->byval_arg, OP_LOCAL);
1646                 } else {
1647                         type_to_eval_stack_type (ret, ins);
1648                         temp = mono_compile_create_var (cfg, ret, OP_LOCAL);
1649                 }
1650
1651                 if (MONO_TYPE_ISSTRUCT (ret)) {
1652                         MonoInst *loada;
1653
1654                         /* we use this to allocate native sized structs */
1655                         temp->unused = sig->pinvoke;
1656
1657                         NEW_TEMPLOADA (cfg, loada, temp->inst_c0);
1658                         if (call->inst.opcode == OP_VCALL)
1659                                 ins->inst_left = loada;
1660                         else
1661                                 ins->inst_right = loada; /* a virtual or indirect call */
1662
1663                         if (to_end)
1664                                 mono_add_ins_to_end (bblock, ins);
1665                         else
1666                                 MONO_ADD_INS (bblock, ins);
1667                 } else {
1668                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
1669                         store->cil_code = ip;
1670                         if (to_end)
1671                                 mono_add_ins_to_end (bblock, store);
1672                         else
1673                                 MONO_ADD_INS (bblock, store);
1674                 }
1675                 return temp->inst_c0;
1676         } else {
1677                 if (to_end)
1678                         mono_add_ins_to_end (bblock, ins);
1679                 else
1680                         MONO_ADD_INS (bblock, ins);
1681                 return -1;
1682         }
1683 }
1684
1685 inline static MonoCallInst *
1686 mono_emit_call_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
1687                      MonoInst **args, int calli, int virtual, const guint8 *ip, gboolean to_end)
1688 {
1689         MonoCallInst *call;
1690         int i;
1691
1692         MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (sig->ret, calli, virtual));
1693         
1694         call->inst.cil_code = ip;
1695         call->args = args;
1696         call->signature = sig;
1697         call = mono_arch_call_opcode (cfg, bblock, call, virtual);
1698
1699         for (i = 0; i < (sig->param_count + sig->hasthis); ++i) {
1700                 if (call->args [i]) {
1701                         if (!call->args [i]->cil_code)
1702                                 call->args [i]->cil_code = ip;
1703                         if (to_end)
1704                                 mono_add_ins_to_end (bblock, call->args [i]);
1705                         else
1706                                 MONO_ADD_INS (bblock, call->args [i]);
1707                 }
1708         }
1709         return call;
1710 }
1711
1712 inline static int
1713 mono_emit_calli (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, 
1714                  MonoInst **args, MonoInst *addr, const guint8 *ip)
1715 {
1716         MonoCallInst *call = mono_emit_call_args (cfg, bblock, sig, args, TRUE, FALSE, ip, FALSE);
1717
1718         call->inst.inst_i0 = addr;
1719
1720         return mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
1721 }
1722
1723 static MonoCallInst*
1724 mono_emit_method_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
1725                        MonoInst **args, const guint8 *ip, MonoInst *this)
1726 {
1727         gboolean virtual = this != NULL;
1728         MonoCallInst *call;
1729
1730         call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, virtual, ip, FALSE);
1731
1732         if (this && sig->hasthis && 
1733             (method->klass->marshalbyref || method->klass == mono_defaults.object_class) && 
1734             !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !MONO_CHECK_THIS (this)) {
1735                 call->method = mono_marshal_get_remoting_invoke_with_check (method);
1736         } else {
1737                 call->method = method;
1738         }
1739         call->inst.flags |= MONO_INST_HAS_METHOD;
1740         call->inst.inst_left = this;
1741
1742         return call;
1743 }
1744
1745 inline static int
1746 mono_emit_method_call_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,  
1747                        MonoInst **args, const guint8 *ip, MonoInst *this)
1748 {
1749         MonoCallInst *call = mono_emit_method_call (cfg, bblock, method, method->signature, args, ip, this);
1750
1751         return mono_spill_call (cfg, bblock, call, method->signature, method->string_ctor, ip, FALSE);
1752 }
1753
1754 inline static int
1755 mono_emit_native_call (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoMethodSignature *sig,
1756                        MonoInst **args, const guint8 *ip, gboolean to_end)
1757 {
1758         MonoCallInst *call;
1759
1760         g_assert (sig);
1761
1762         call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, FALSE, ip, to_end);
1763         call->fptr = func;
1764         return mono_spill_call (cfg, bblock, call, sig, func == mono_array_new_va, ip, to_end);
1765 }
1766
1767 inline static int
1768 mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip)
1769 {
1770         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
1771         
1772         if (!info) {
1773                 g_warning ("unregistered JIT ICall");
1774                 g_assert_not_reached ();
1775         }
1776
1777         return mono_emit_native_call (cfg, bblock, info->wrapper, info->sig, args, ip, FALSE);
1778 }
1779
1780 static void
1781 mono_emulate_opcode (MonoCompile *cfg, MonoInst *tree, MonoInst **iargs, MonoJitICallInfo *info)
1782 {
1783         MonoInst *ins, *temp = NULL, *store, *load;
1784         int i, nargs;
1785         MonoCallInst *call;
1786
1787         /*g_print ("emulating: ");
1788         mono_print_tree (tree);
1789         g_print ("\n");*/
1790         MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (info->sig->ret, FALSE, FALSE));
1791         ins = (MonoInst*)call;
1792         
1793         call->inst.cil_code = tree->cil_code;
1794         call->args = iargs;
1795         call->signature = info->sig;
1796
1797         call = mono_arch_call_opcode (cfg, cfg->cbb, call, FALSE);
1798
1799         if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
1800                 temp = mono_compile_create_var (cfg, info->sig->ret, OP_LOCAL);
1801                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
1802                 store->cil_code = tree->cil_code;
1803         } else {
1804                 store = ins;
1805         }
1806
1807         nargs = info->sig->param_count + info->sig->hasthis;
1808
1809         for (i = 1; i < nargs; i++) {
1810                 call->args [i - 1]->next = call->args [i];
1811         }
1812
1813         if (nargs)
1814                 call->args [nargs - 1]->next = store;
1815
1816         if (cfg->prev_ins) {
1817                 store->next = cfg->prev_ins->next;
1818                 if (nargs)
1819                         cfg->prev_ins->next =  call->args [0];
1820                 else
1821                         cfg->prev_ins->next = store;
1822         } else {
1823                 store->next = cfg->cbb->code;
1824                 if (nargs)              
1825                         cfg->cbb->code = call->args [0];
1826                 else
1827                         cfg->cbb->code = store;
1828         }
1829
1830         
1831         call->fptr = info->wrapper;
1832
1833         if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
1834                 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
1835                 *tree = *load;
1836         }
1837 }
1838
1839 static MonoMethodSignature *
1840 mono_get_element_address_signature (int arity)
1841 {
1842         static GHashTable *sighash = NULL;
1843         MonoMethodSignature *res;
1844         int i;
1845
1846         if (!sighash)
1847                 sighash = g_hash_table_new (NULL, NULL);
1848
1849
1850         if ((res = g_hash_table_lookup (sighash, (gpointer)arity)))
1851                 return res;
1852
1853         res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
1854
1855         res->params [0] = &mono_defaults.array_class->byval_arg; 
1856         
1857         for (i = 1; i <= arity; i++)
1858                 res->params [i] = &mono_defaults.int_class->byval_arg;
1859
1860         res->ret = &mono_defaults.int_class->byval_arg;
1861
1862         g_hash_table_insert (sighash, (gpointer)arity, res);
1863
1864         return res;
1865 }
1866
1867 static void
1868 handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native) {
1869         MonoInst *iargs [3];
1870         int n;
1871         guint32 align = 0;
1872
1873         g_assert (klass);
1874         /*
1875          * This check breaks with spilled vars... need to handle it during verification anyway.
1876          * g_assert (klass && klass == src->klass && klass == dest->klass);
1877          */
1878
1879         if (native)
1880                 n = mono_class_native_size (klass, &align);
1881         else
1882                 n = mono_class_value_size (klass, &align);
1883
1884         if ((cfg->opt & MONO_OPT_INTRINS) && !to_end && n <= sizeof (gpointer) * 5) {
1885                 MonoInst *inst;
1886                 MONO_INST_NEW (cfg, inst, OP_MEMCPY);
1887                 inst->inst_left = dest;
1888                 inst->inst_right = src;
1889                 inst->cil_code = ip;
1890                 inst->unused = n;
1891                 MONO_ADD_INS (bblock, inst);
1892                 return;
1893         }
1894         iargs [0] = dest;
1895         iargs [1] = src;
1896         NEW_ICONST (cfg, iargs [2], n);
1897
1898         mono_emit_native_call (cfg, bblock, helper_memcpy, helper_sig_memcpy, iargs, ip, to_end);
1899 }
1900
1901 static void
1902 handle_initobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, const guchar *ip, MonoClass *klass, MonoInst **stack_start, MonoInst **sp)
1903 {
1904         MonoInst *iargs [2];
1905         MonoInst *ins, *zero_int32;
1906         int n;
1907
1908         NEW_ICONST (cfg, zero_int32, 0);
1909
1910         mono_class_init (klass);
1911         n = mono_class_value_size (klass, NULL);
1912         MONO_INST_NEW (cfg, ins, 0);
1913         ins->cil_code = ip;
1914         ins->inst_left = dest;
1915         ins->inst_right = zero_int32;
1916         switch (n) {
1917         case 1:
1918                 ins->opcode = CEE_STIND_I1;
1919                 MONO_ADD_INS (bblock, ins);
1920                 break;
1921         case 2:
1922                 ins->opcode = CEE_STIND_I2;
1923                 MONO_ADD_INS (bblock, ins);
1924                 break;
1925         case 4:
1926                 ins->opcode = CEE_STIND_I4;
1927                 MONO_ADD_INS (bblock, ins);
1928                 break;
1929         default:
1930                 handle_loaded_temps (cfg, bblock, stack_start, sp);
1931                 NEW_ICONST (cfg, ins, n);
1932                 iargs [0] = dest;
1933                 iargs [1] = ins;
1934                 mono_emit_jit_icall (cfg, bblock, helper_initobj, iargs, ip);
1935                 break;
1936         }
1937 }
1938
1939 #define CODE_IS_STLOC(ip) (((ip) [0] >= CEE_STLOC_0 && (ip) [0] <= CEE_STLOC_3) || ((ip) [0] == CEE_STLOC_S))
1940
1941 static gboolean
1942 mono_method_check_inlining (MonoMethod *method)
1943 {
1944         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
1945         MonoMethodSignature *signature = method->signature;
1946         int i;
1947
1948         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1949             (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
1950             (method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
1951             (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
1952             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1953             (method->klass->marshalbyref) ||
1954             !header || header->num_clauses ||
1955             /* fixme: why cant we inline valuetype returns? */
1956             MONO_TYPE_ISSTRUCT (signature->ret))
1957                 return FALSE;
1958
1959         /* its not worth to inline methods with valuetype arguments?? */
1960         for (i = 0; i < signature->param_count; i++) {
1961                 if (MONO_TYPE_ISSTRUCT (signature->params [i])) {
1962                         return FALSE;
1963                 }
1964         }
1965
1966         //if (!MONO_TYPE_IS_VOID (signature->ret)) return FALSE;
1967
1968         /* also consider num_locals? */
1969         if (header->code_size < 20)
1970                 return TRUE;
1971
1972         return FALSE;
1973 }
1974
1975 static MonoInst*
1976 mini_get_ldelema_ins (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
1977 {
1978         int temp, rank;
1979         MonoInst *addr;
1980         MonoMethodSignature *esig;
1981
1982         rank = cmethod->signature->param_count - (is_set? 1: 0);
1983         /* 
1984          * FIXME: handle TypeMismatch for set or use the slow path
1985          * for that.
1986          */
1987         if (rank == 2 && (cfg->opt & MONO_OPT_INTRINS)) {
1988                 MonoInst *indexes;
1989                 NEW_GROUP (cfg, indexes, sp [1], sp [2]);
1990                 MONO_INST_NEW (cfg, addr, OP_LDELEMA2D);
1991                 addr->inst_left = sp [0];
1992                 addr->inst_right = indexes;
1993                 addr->cil_code = ip;
1994                 addr->type = STACK_MP;
1995                 addr->klass = cmethod->klass;
1996                 return addr;
1997         }
1998         esig = mono_get_element_address_signature (rank);
1999         temp = mono_emit_native_call (cfg, bblock, ves_array_element_address, esig, sp, ip, FALSE);
2000         NEW_TEMPLOAD (cfg, addr, temp);
2001         return addr;
2002 }
2003
2004 static MonoInst*
2005 mini_get_opcode_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
2006 {
2007         int pc, op;
2008         MonoInst *ins;
2009
2010         if (cmethod->klass == mono_defaults.string_class) {
2011                 if (cmethod->name [0] != 'g' || strcmp (cmethod->name, "get_Chars"))
2012                         return NULL;
2013                 op = OP_GETCHR;
2014         } else if (cmethod->klass == mono_defaults.math_class) {
2015                 if (strcmp (cmethod->name, "Sin") == 0)
2016                         op = OP_SIN;
2017                 else if (strcmp (cmethod->name, "Cos") == 0)
2018                         op = OP_COS;
2019                 else if (strcmp (cmethod->name, "Tan") == 0)
2020                         op = OP_TAN;
2021                 else if (strcmp (cmethod->name, "Atan") == 0)
2022                         op = OP_ATAN;
2023                 else if (strcmp (cmethod->name, "Sqrt") == 0)
2024                         op = OP_SQRT;
2025                 else if (strcmp (cmethod->name, "Abs") == 0 && fsig->params [0]->type == MONO_TYPE_R8)
2026                         op = OP_ABS;
2027                 else
2028                         return NULL;
2029         } else {
2030                 return NULL;
2031         }
2032         pc = fsig->param_count + fsig->hasthis;
2033         MONO_INST_NEW (cfg, ins, op);
2034
2035         if (pc > 0) {
2036                 ins->inst_i0 = args [0];
2037                 if (pc > 1)
2038                         ins->inst_i1 = args [1];
2039         }
2040
2041         return ins;
2042 }
2043
2044 static void
2045 mono_save_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, MonoInst **sp, MonoInst **args)
2046 {
2047         MonoInst *store, *temp;
2048         int i;
2049
2050         g_assert (!MONO_TYPE_ISSTRUCT (sig->ret));
2051
2052         if (!sig->hasthis && sig->param_count == 0) 
2053                 return;
2054
2055         if (sig->hasthis) {
2056                 if (sp [0]->opcode == OP_ICONST) {
2057                         *args++ = sp [0];
2058                 } else {
2059                         temp = mono_compile_create_var (cfg, type_from_stack_type (*sp), OP_LOCAL);
2060                         *args++ = temp;
2061                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
2062                         store->cil_code = sp [0]->cil_code;
2063                         MONO_ADD_INS (bblock, store);
2064                 }
2065                 sp++;
2066         }
2067
2068         for (i = 0; i < sig->param_count; ++i) {
2069                 if (sp [0]->opcode == OP_ICONST) {
2070                         *args++ = sp [0];
2071                 } else {
2072                         temp = mono_compile_create_var (cfg, sig->params [i], OP_LOCAL);
2073                         *args++ = temp;
2074                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
2075                         store->cil_code = sp [0]->cil_code;
2076                         if (store->opcode == CEE_STOBJ) {
2077                                 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2078                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, temp->klass, FALSE, FALSE);
2079                         } else {
2080                                 MONO_ADD_INS (bblock, store);
2081                         } 
2082                 }
2083                 sp++;
2084         }
2085 }
2086
2087 static int
2088 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoBasicBlock *bblock, MonoInst **sp,
2089                 guchar *ip, guint real_offset, GList *dont_inline, MonoBasicBlock **last_b)
2090 {
2091         MonoInst *ins, *rvar = NULL;
2092         MonoMethodHeader *cheader;
2093         MonoBasicBlock *ebblock, *sbblock;
2094         int i, costs, new_locals_offset;
2095
2096         if (cfg->verbose_level > 2)
2097                 g_print ("INLINE START %p %s\n", cmethod,  mono_method_full_name (cmethod, TRUE));
2098
2099         cheader = ((MonoMethodNormal *)cmethod)->header;
2100
2101         if (!cmethod->inline_info) {
2102                 mono_jit_stats.inlineable_methods++;
2103                 cmethod->inline_info = 1;
2104         }
2105         /* allocate space to store the return value */
2106         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
2107                 rvar =  mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
2108         }
2109
2110         /* allocate local variables */
2111         new_locals_offset = cfg->num_varinfo;
2112         for (i = 0; i < cheader->num_locals; ++i)
2113                 mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
2114         
2115         /* allocate starte and end blocks */
2116         sbblock = NEW_BBLOCK (cfg);
2117         sbblock->block_num = cfg->num_bblocks++;
2118         sbblock->real_offset = real_offset;
2119
2120         ebblock = NEW_BBLOCK (cfg);
2121         ebblock->block_num = cfg->num_bblocks++;
2122         ebblock->real_offset = real_offset;
2123         
2124         costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, new_locals_offset, rvar, dont_inline, sp, real_offset, *ip == CEE_CALLVIRT);
2125         
2126         if (costs >= 0 && costs < 60) {
2127                 if (cfg->verbose_level > 2)
2128                         g_print ("INLINE END %s\n", mono_method_full_name (cmethod, TRUE));
2129                 
2130                 mono_jit_stats.inlined_methods++;
2131
2132                 /* always add some code to avoid block split failures */
2133                 MONO_INST_NEW (cfg, ins, CEE_NOP);
2134                 MONO_ADD_INS (bblock, ins);
2135                 ins->cil_code = ip;
2136
2137                 bblock->next_bb = sbblock;
2138                 link_bblock (cfg, bblock, sbblock);
2139
2140                 if (rvar) {
2141                         NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
2142                         *sp++ = ins;
2143                 }
2144                 *last_b = ebblock;
2145                 return costs + 1;
2146         } else {
2147                 if (cfg->verbose_level > 2)
2148                         g_print ("INLINE ABORTED %s\n", mono_method_full_name (cmethod, TRUE));
2149         }
2150         return 0;
2151 }
2152
2153 /*
2154  * Some of these comments may well be out-of-date.
2155  * Design decisions: we do a single pass over the IL code (and we do bblock 
2156  * splitting/merging in the few cases when it's required: a back jump to an IL
2157  * address that was not already seen as bblock starting point).
2158  * Code is validated as we go (full verification is still better left to metadata/verify.c).
2159  * Complex operations are decomposed in simpler ones right away. We need to let the 
2160  * arch-specific code peek and poke inside this process somehow (except when the 
2161  * optimizations can take advantage of the full semantic info of coarse opcodes).
2162  * All the opcodes of the form opcode.s are 'normalized' to opcode.
2163  * MonoInst->opcode initially is the IL opcode or some simplification of that 
2164  * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific 
2165  * opcode with value bigger than OP_LAST.
2166  * At this point the IR can be handed over to an interpreter, a dumb code generator
2167  * or to the optimizing code generator that will translate it to SSA form.
2168  *
2169  * Profiling directed optimizations.
2170  * We may compile by default with few or no optimizations and instrument the code
2171  * or the user may indicate what methods to optimize the most either in a config file
2172  * or through repeated runs where the compiler applies offline the optimizations to 
2173  * each method and then decides if it was worth it.
2174  *
2175  * TODO:
2176  * * consider using an array instead of an hash table (bb_hash)
2177  */
2178
2179 #define CHECK_TYPE(ins) if (!(ins)->type) goto unverified
2180 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) goto unverified
2181 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) goto unverified
2182
2183 /* offset from br.s -> br like opcodes */
2184 #define BIG_BRANCH_OFFSET 13
2185
2186 /*
2187  * mono_method_to_ir: translates IL into basic blocks containing trees
2188  */
2189 static int
2190 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock, 
2191                    int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args, 
2192                    guint inline_offset, gboolean is_virtual_call)
2193 {
2194         MonoInst *zero_int32, *zero_int64, *zero_ptr, *zero_obj, *zero_r8;
2195         MonoInst *ins, **sp, **stack_start;
2196         MonoBasicBlock *bblock, *tblock = NULL, *init_localsbb = NULL;
2197         GHashTable *bbhash;
2198         MonoMethod *cmethod;
2199         MonoInst **arg_array;
2200         MonoMethodHeader *header;
2201         MonoImage *image;
2202         guint32 token, ins_flag;
2203         MonoClass *klass;
2204         unsigned char *ip, *end, *target;
2205         static double r8_0 = 0.0;
2206         MonoMethodSignature *sig;
2207         MonoType **param_types;
2208         GList *bb_recheck = NULL, *tmp;
2209         int i, n, start_new_bblock, align;
2210         int num_calls = 0, inline_costs = 0;
2211         int *filter_lengths = NULL;
2212         int breakpoint_id = 0;
2213         guint real_offset;
2214
2215         image = method->klass->image;
2216         header = ((MonoMethodNormal *)method)->header;
2217         sig = method->signature;
2218         ip = (unsigned char*)header->code;
2219         end = ip + header->code_size;
2220         mono_jit_stats.cil_code_size += header->code_size;
2221
2222         if (cfg->method == method) {
2223                 real_offset = 0;
2224                 bbhash = cfg->bb_hash;
2225         } else {
2226                 real_offset = inline_offset;
2227                 bbhash = g_hash_table_new (g_direct_hash, NULL);
2228         }
2229
2230         dont_inline = g_list_prepend (dont_inline, method);
2231         if (cfg->method == method) {
2232
2233                 /* ENTRY BLOCK */
2234                 cfg->bb_entry = start_bblock = NEW_BBLOCK (cfg);
2235                 start_bblock->cil_code = NULL;
2236                 start_bblock->cil_length = 0;
2237                 start_bblock->block_num = cfg->num_bblocks++;
2238
2239                 /* EXIT BLOCK */
2240                 cfg->bb_exit = end_bblock = NEW_BBLOCK (cfg);
2241                 end_bblock->cil_code = NULL;
2242                 end_bblock->cil_length = 0;
2243                 end_bblock->block_num = cfg->num_bblocks++;
2244                 g_assert (cfg->num_bblocks == 2);
2245
2246                 arg_array = alloca (sizeof (MonoInst *) * (sig->hasthis + sig->param_count));
2247                 for (i = sig->hasthis + sig->param_count - 1; i >= 0; i--)
2248                         arg_array [i] = cfg->varinfo [i];
2249
2250                 if (mono_compile_aot) 
2251                         cfg->opt |= MONO_OPT_SHARED;
2252
2253                 if (header->num_clauses) {
2254                         int size = sizeof (int) * header->num_clauses;
2255                         filter_lengths = alloca (size);
2256                         memset (filter_lengths, 0, size);
2257                 }
2258                 /* handle exception clauses */
2259                 for (i = 0; i < header->num_clauses; ++i) {
2260                         //unsigned char *p = ip;
2261                         MonoExceptionClause *clause = &header->clauses [i];
2262                         GET_BBLOCK (cfg, bbhash, tblock, ip + clause->try_offset);
2263                         tblock->real_offset = clause->try_offset;
2264                         GET_BBLOCK (cfg, bbhash, tblock, ip + clause->handler_offset);
2265                         tblock->real_offset = clause->handler_offset;
2266                         /*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);
2267                           while (p < end) {
2268                           g_print ("%s", mono_disasm_code_one (NULL, method, p, &p));
2269                           }*/
2270                         /* catch and filter blocks get the exception object on the stack */
2271                         if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
2272                             clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2273                                 /* mostly like handle_stack_args (), but just sets the input args */
2274                                 /* g_print ("handling clause at IL_%04x\n", clause->handler_offset); */
2275                                 if (!cfg->exvar) {
2276                                         cfg->exvar = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
2277                                         /* prevent it from being register allocated */
2278                                         cfg->exvar->flags |= MONO_INST_INDIRECT;
2279                                 }
2280                                 tblock->in_scount = 1;
2281                                 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
2282                                 tblock->in_stack [0] = cfg->exvar;
2283                                 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2284                                         GET_BBLOCK (cfg, bbhash, tblock, ip + clause->token_or_filter);
2285                                         tblock->real_offset = clause->token_or_filter;
2286                                         tblock->in_scount = 1;
2287                                         tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
2288                                         tblock->in_stack [0] = cfg->exvar;
2289                                 }
2290                         }
2291                 }
2292
2293         } else {
2294                 arg_array = alloca (sizeof (MonoInst *) * (sig->hasthis + sig->param_count));
2295                 mono_save_args (cfg, start_bblock, sig, inline_args, arg_array);
2296         }
2297
2298         /* FIRST CODE BLOCK */
2299         bblock = NEW_BBLOCK (cfg);
2300         bblock->cil_code = ip;
2301
2302         ADD_BBLOCK (cfg, bbhash, bblock);
2303
2304         if (cfg->method == method) {
2305                 breakpoint_id = mono_debugger_method_has_breakpoint (method);
2306                 if (breakpoint_id && (mono_debug_format != MONO_DEBUG_FORMAT_DEBUGGER)) {
2307                         MONO_INST_NEW (cfg, ins, CEE_BREAK);
2308                         MONO_ADD_INS (bblock, ins);
2309                 }
2310         }
2311         
2312         if ((header->init_locals || (cfg->method == method && (cfg->opt & MONO_OPT_SHARED)))) {
2313                 /* we use a separate basic block for the initialization code */
2314                 cfg->bb_init = init_localsbb = NEW_BBLOCK (cfg);
2315                 init_localsbb->real_offset = real_offset;
2316                 start_bblock->next_bb = init_localsbb;
2317                 init_localsbb->next_bb = bblock;
2318                 link_bblock (cfg, start_bblock, init_localsbb);
2319                 link_bblock (cfg, init_localsbb, bblock);
2320                 init_localsbb->block_num = cfg->num_bblocks++;
2321         } else {
2322                 start_bblock->next_bb = bblock;
2323                 link_bblock (cfg, start_bblock, bblock);
2324         }
2325
2326         mono_debug_init_method (cfg, bblock, breakpoint_id);
2327
2328         param_types = mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * (sig->hasthis + sig->param_count));
2329         if (sig->hasthis)
2330                 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
2331         for (n = 0; n < sig->param_count; ++n)
2332                 param_types [n + sig->hasthis] = sig->params [n];
2333
2334         /* do this somewhere outside - not here */
2335         NEW_ICONST (cfg, zero_int32, 0);
2336         NEW_ICONST (cfg, zero_int64, 0);
2337         zero_int64->type = STACK_I8;
2338         NEW_PCONST (cfg, zero_ptr, 0);
2339         NEW_PCONST (cfg, zero_obj, 0);
2340         zero_obj->type = STACK_OBJ;
2341
2342         MONO_INST_NEW (cfg, zero_r8, OP_R8CONST);
2343         zero_r8->type = STACK_R8;
2344         zero_r8->inst_p0 = &r8_0;
2345
2346         /* add a check for this != NULL to inlined methods */
2347         if (is_virtual_call) {
2348                 MONO_INST_NEW (cfg, ins, OP_CHECK_THIS);
2349                 NEW_ARGLOAD (cfg, ins->inst_left, 0);
2350                 ins->cil_code = ip;
2351                 MONO_ADD_INS (bblock, ins);
2352         }
2353
2354         /* we use a spare stack slot in SWITCH and NEWOBJ and others */
2355         stack_start = sp = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
2356
2357         ins_flag = 0;
2358         start_new_bblock = 0;
2359         while (ip < end) {
2360
2361                 if (cfg->method == method)
2362                         real_offset = ip - header->code;
2363                 else
2364                         real_offset = inline_offset;
2365
2366                 if (start_new_bblock) {
2367                         bblock->cil_length = ip - bblock->cil_code;
2368                         if (start_new_bblock == 2) {
2369                                 g_assert (ip == tblock->cil_code);
2370                         } else {
2371                                 GET_BBLOCK (cfg, bbhash, tblock, ip);
2372                         }
2373                         bblock->next_bb = tblock;
2374                         bblock = tblock;
2375                         start_new_bblock = 0;
2376                         for (i = 0; i < bblock->in_scount; ++i) {
2377                                 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
2378                                 *sp++ = ins;
2379                         }
2380                 } else {
2381                         if ((tblock = g_hash_table_lookup (bbhash, ip)) && (tblock != bblock)) {
2382                                 link_bblock (cfg, bblock, tblock);
2383                                 if (sp != stack_start) {
2384                                         handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2385                                         sp = stack_start;
2386                                 }
2387                                 bblock->next_bb = tblock;
2388                                 bblock = tblock;
2389                                 for (i = 0; i < bblock->in_scount; ++i) {
2390                                         NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
2391                                         *sp++ = ins;
2392                                 }
2393                         }
2394                 }
2395
2396                 if (cfg->verbose_level > 3)
2397                         g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, sp-stack_start, mono_disasm_code_one (NULL, method, ip, NULL));
2398
2399                 switch (*ip) {
2400                 case CEE_NOP:
2401                         ++ip;
2402                         break;
2403                 case CEE_BREAK:
2404                         MONO_INST_NEW (cfg, ins, CEE_BREAK);
2405                         ins->cil_code = ip++;
2406                         MONO_ADD_INS (bblock, ins);
2407                         break;
2408                 case CEE_LDARG_0:
2409                 case CEE_LDARG_1:
2410                 case CEE_LDARG_2:
2411                 case CEE_LDARG_3:
2412                         CHECK_STACK_OVF (1);
2413                         n = (*ip)-CEE_LDARG_0;
2414                         NEW_ARGLOAD (cfg, ins, n);
2415                         ins->cil_code = ip++;
2416                         *sp++ = ins;
2417                         break;
2418                 case CEE_LDLOC_0:
2419                 case CEE_LDLOC_1:
2420                 case CEE_LDLOC_2:
2421                 case CEE_LDLOC_3:
2422                         CHECK_STACK_OVF (1);
2423                         n = (*ip)-CEE_LDLOC_0;
2424                         NEW_LOCLOAD (cfg, ins, n);
2425                         ins->cil_code = ip++;
2426                         *sp++ = ins;
2427                         break;
2428                 case CEE_STLOC_0:
2429                 case CEE_STLOC_1:
2430                 case CEE_STLOC_2:
2431                 case CEE_STLOC_3:
2432                         CHECK_STACK (1);
2433                         n = (*ip)-CEE_STLOC_0;
2434                         --sp;
2435                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2436                         NEW_LOCSTORE (cfg, ins, n, *sp);
2437                         ins->cil_code = ip;
2438                         if (ins->opcode == CEE_STOBJ) {
2439                                 NEW_LOCLOADA (cfg, ins, n);
2440                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
2441                         } else
2442                                 MONO_ADD_INS (bblock, ins);
2443                         ++ip;
2444                         inline_costs += 1;
2445                         break;
2446                 case CEE_LDARG_S:
2447                         CHECK_STACK_OVF (1);
2448                         NEW_ARGLOAD (cfg, ins, ip [1]);
2449                         ins->cil_code = ip;
2450                         *sp++ = ins;
2451                         ip += 2;
2452                         break;
2453                 case CEE_LDARGA_S:
2454                         CHECK_STACK_OVF (1);
2455                         NEW_ARGLOADA (cfg, ins, ip [1]);
2456                         ins->cil_code = ip;
2457                         *sp++ = ins;
2458                         ip += 2;
2459                         break;
2460                 case CEE_STARG_S:
2461                         CHECK_STACK (1);
2462                         --sp;
2463                         NEW_ARGSTORE (cfg, ins, ip [1], *sp);
2464                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2465                         ins->cil_code = ip;
2466                         if (ins->opcode == CEE_STOBJ) {
2467                                 NEW_ARGLOADA (cfg, ins, ip [1]);
2468                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
2469                         } else
2470                                 MONO_ADD_INS (bblock, ins);
2471                         ip += 2;
2472                         break;
2473                 case CEE_LDLOC_S:
2474                         CHECK_STACK_OVF (1);
2475                         NEW_LOCLOAD (cfg, ins, ip [1]);
2476                         ins->cil_code = ip;
2477                         *sp++ = ins;
2478                         ip += 2;
2479                         break;
2480                 case CEE_LDLOCA_S:
2481                         CHECK_STACK_OVF (1);
2482                         NEW_LOCLOADA (cfg, ins, ip [1]);
2483                         ins->cil_code = ip;
2484                         *sp++ = ins;
2485                         ip += 2;
2486                         break;
2487                 case CEE_STLOC_S:
2488                         CHECK_STACK (1);
2489                         --sp;
2490                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2491                         NEW_LOCSTORE (cfg, ins, ip [1], *sp);
2492                         ins->cil_code = ip;
2493                         if (ins->opcode == CEE_STOBJ) {
2494                                 NEW_LOCLOADA (cfg, ins, ip [1]);
2495                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
2496                         } else
2497                                 MONO_ADD_INS (bblock, ins);
2498                         ip += 2;
2499                         inline_costs += 1;
2500                         break;
2501                 case CEE_LDNULL:
2502                         CHECK_STACK_OVF (1);
2503                         NEW_PCONST (cfg, ins, NULL);
2504                         ins->cil_code = ip;
2505                         ins->type = STACK_OBJ;
2506                         ++ip;
2507                         *sp++ = ins;
2508                         break;
2509                 case CEE_LDC_I4_M1:
2510                         CHECK_STACK_OVF (1);
2511                         NEW_ICONST (cfg, ins, -1);
2512                         ins->cil_code = ip;
2513                         ++ip;
2514                         *sp++ = ins;
2515                         break;
2516                 case CEE_LDC_I4_0:
2517                 case CEE_LDC_I4_1:
2518                 case CEE_LDC_I4_2:
2519                 case CEE_LDC_I4_3:
2520                 case CEE_LDC_I4_4:
2521                 case CEE_LDC_I4_5:
2522                 case CEE_LDC_I4_6:
2523                 case CEE_LDC_I4_7:
2524                 case CEE_LDC_I4_8:
2525                         CHECK_STACK_OVF (1);
2526                         NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
2527                         ins->cil_code = ip;
2528                         ++ip;
2529                         *sp++ = ins;
2530                         break;
2531                 case CEE_LDC_I4_S:
2532                         CHECK_STACK_OVF (1);
2533                         ++ip;
2534                         NEW_ICONST (cfg, ins, *((signed char*)ip));
2535                         ins->cil_code = ip;
2536                         ++ip;
2537                         *sp++ = ins;
2538                         break;
2539                 case CEE_LDC_I4:
2540                         CHECK_STACK_OVF (1);
2541                         NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
2542                         ins->cil_code = ip;
2543                         ip += 5;
2544                         *sp++ = ins;
2545                         break;
2546                 case CEE_LDC_I8:
2547                         CHECK_STACK_OVF (1);
2548                         MONO_INST_NEW (cfg, ins, OP_I8CONST);
2549                         ins->cil_code = ip;
2550                         ins->type = STACK_I8;
2551                         ++ip;
2552                         ins->inst_l = (gint64)read64 (ip);
2553                         ip += 8;
2554                         *sp++ = ins;
2555                         break;
2556                 case CEE_LDC_R4: {
2557                         float *f = g_malloc (sizeof (float));
2558                         CHECK_STACK_OVF (1);
2559                         MONO_INST_NEW (cfg, ins, OP_R4CONST);
2560                         ins->type = STACK_R8;
2561                         ++ip;
2562                         readr4 (ip, f);
2563                         ins->inst_p0 = f;
2564                         ip += 4;
2565                         *sp++ = ins;                    
2566                         break;
2567                 }
2568                 case CEE_LDC_R8: {
2569                         double *d = g_malloc (sizeof (double));
2570                         CHECK_STACK_OVF (1);
2571                         MONO_INST_NEW (cfg, ins, OP_R8CONST);
2572                         ins->type = STACK_R8;
2573                         ++ip;
2574                         readr8 (ip, d);
2575                         ins->inst_p0 = d;
2576                         ip += 8;
2577                         *sp++ = ins;                    
2578                         break;
2579                 }
2580                 case CEE_DUP: {
2581                         MonoInst *temp, *store;
2582                         CHECK_STACK (1);
2583                         CHECK_STACK_OVF (1);
2584                         sp--;
2585                         ins = *sp;
2586                 
2587                         /* 
2588                          * small optimization: if the loaded value was from a local already,
2589                          * just load it twice.
2590                          */
2591                         if (ins->ssa_op == MONO_SSA_LOAD && 
2592                             (ins->inst_i0->opcode == OP_LOCAL || ins->inst_i0->opcode == OP_ARG)) {
2593                                 sp++;
2594                                 MONO_INST_NEW (cfg, temp, 0);
2595                                 *temp = *ins;
2596                                 temp->cil_code = ip;
2597                                 *sp++ = temp;
2598                         } else {
2599                                 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
2600                                 temp->cil_code = ip;
2601                                 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2602                                 store->cil_code = ip;
2603                                 MONO_ADD_INS (bblock, store);
2604                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
2605                                 *sp++ = ins;
2606                                 ins->cil_code = ip;
2607                                 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
2608                                 *sp++ = ins;
2609                                 ins->cil_code = ip;
2610                         }
2611                         ++ip;
2612                         inline_costs += 2;
2613                         break;
2614                 }
2615                 case CEE_POP:
2616                         CHECK_STACK (1);
2617                         MONO_INST_NEW (cfg, ins, CEE_POP);
2618                         MONO_ADD_INS (bblock, ins);
2619                         ins->cil_code = ip++;
2620                         --sp;
2621                         ins->inst_i0 = *sp;
2622                         break;
2623                 case CEE_JMP:
2624                         if (stack_start != sp)
2625                                 goto unverified;
2626                         MONO_INST_NEW (cfg, ins, CEE_JMP);
2627                         token = read32 (ip + 1);
2628                         /* FIXME: check the signature matches */
2629                         cmethod = mono_get_method (image, token, NULL);
2630                         /*
2631                          * The current magic trampoline can't handle this
2632                          * apparently, so we compile the method right away.
2633                          * Later, we may need to fix the trampoline or use a different one.
2634                          */
2635                         ins->inst_p0 = mono_compile_method (cmethod);
2636                         MONO_ADD_INS (bblock, ins);
2637                         ip += 5;
2638                         start_new_bblock = 1;
2639                         break;
2640                 case CEE_CALLI:
2641                 case CEE_CALL:
2642                 case CEE_CALLVIRT: {
2643                         MonoInst *addr = NULL;
2644                         MonoMethodSignature *fsig = NULL;
2645                         int temp, array_rank = 0;
2646                         int virtual = *ip == CEE_CALLVIRT;
2647
2648                         token = read32 (ip + 1);
2649
2650                         if (*ip == CEE_CALLI) {
2651                                 cmethod = NULL;
2652                                 CHECK_STACK (1);
2653                                 --sp;
2654                                 addr = *sp;
2655                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
2656                                         fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
2657                                 else
2658                                         fsig = mono_metadata_parse_signature (image, token);
2659
2660                                 n = fsig->param_count + fsig->hasthis;
2661
2662                         } else {
2663                                 cmethod = mono_get_method (image, token, NULL);
2664
2665                                 if (!cmethod->klass->inited)
2666                                         mono_class_init (cmethod->klass);
2667
2668                                 if (cmethod->signature->pinvoke) {
2669 #ifdef MONO_USE_EXC_TABLES
2670                                         if (mono_method_blittable (cmethod)) {
2671                                                 fsig = cmethod->signature;
2672                                         } else {
2673 #endif
2674                                                 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod);
2675                                                 fsig = wrapper->signature;
2676 #ifdef MONO_USE_EXC_TABLES
2677                                         }
2678 #endif
2679                                 } else {
2680                                         fsig = cmethod->signature;
2681                                 }
2682
2683                                 n = fsig->param_count + fsig->hasthis;
2684
2685                                 if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
2686                                     cmethod->klass->parent == mono_defaults.array_class) {
2687                                         array_rank = cmethod->klass->rank;
2688                                 }
2689
2690                                 if (cmethod->string_ctor)
2691                                         g_assert_not_reached ();
2692
2693                         }
2694
2695                         CHECK_STACK (n);
2696
2697                         //g_assert (!virtual || fsig->hasthis);
2698
2699                         sp -= n;
2700
2701                         if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_get_opcode_for_method (cfg, cmethod, fsig, sp))) {
2702                                 ins->cil_code = ip;
2703
2704                                 if (MONO_TYPE_IS_VOID (fsig->ret)) {
2705                                         MONO_ADD_INS (bblock, ins);
2706                                 } else {
2707                                         type_to_eval_stack_type (fsig->ret, ins);
2708                                         *sp = ins;
2709                                         sp++;
2710                                 }
2711
2712                                 ip += 5;
2713                                 break;
2714                         }
2715
2716                         if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
2717                             (!virtual || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || (cmethod->flags & METHOD_ATTRIBUTE_FINAL)) && 
2718                             mono_method_check_inlining (cmethod) &&
2719                             !g_list_find (dont_inline, cmethod)) {
2720                                 int costs;
2721                                 MonoBasicBlock *ebblock;
2722                                 
2723                                 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock))) {
2724                                         ip += 5;
2725                                         real_offset += 5;
2726
2727                                         GET_BBLOCK (cfg, bbhash, bblock, ip);
2728                                         ebblock->next_bb = bblock;
2729                                         link_bblock (cfg, ebblock, bblock);
2730
2731                                         if (!MONO_TYPE_IS_VOID (fsig->ret))
2732                                                 sp++;
2733
2734                                         /* indicates start of a new block, and triggers a load of all 
2735                                            stack arguments at bb boundarie */
2736                                         bblock = ebblock;
2737
2738                                         inline_costs += costs;
2739                                         break;
2740                                 }
2741                         }
2742                         
2743                         inline_costs += 10 * num_calls++;
2744                         handle_loaded_temps (cfg, bblock, stack_start, sp);
2745
2746                         /* tail recursion elimination */
2747                         if ((cfg->opt & MONO_OPT_TAILC) && *ip == CEE_CALL && cmethod == cfg->method && ip [5] == CEE_RET) {
2748                                 gboolean has_vtargs = FALSE;
2749                                 int i;
2750                                 
2751                                 /* keep it simple */
2752                                 for (i =  fsig->param_count - 1; i >= 0; i--) {
2753                                         if (MONO_TYPE_ISSTRUCT (cmethod->signature->params [i])) 
2754                                                 has_vtargs = TRUE;
2755                                 }
2756
2757                                 if (!has_vtargs) {
2758                                         for (i = 0; i < n; ++i) {
2759                                                 NEW_ARGSTORE (cfg, ins, i, sp [i]);
2760                                                 ins->cil_code = ip;
2761                                                 MONO_ADD_INS (bblock, ins);
2762                                         }
2763                                         MONO_INST_NEW (cfg, ins, CEE_BR);
2764                                         ins->cil_code = ip;
2765                                         MONO_ADD_INS (bblock, ins);
2766                                         tblock = start_bblock->out_bb [0];
2767                                         link_bblock (cfg, bblock, tblock);
2768                                         ins->inst_target_bb = tblock;
2769                                         start_new_bblock = 1;
2770                                         ip += 5;
2771                                         
2772                                         if (!MONO_TYPE_IS_VOID (fsig->ret)) {
2773                                                 /* just create a dummy - the value is never used */
2774                                                 ins = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
2775                                                 NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
2776                                                 sp++;
2777                                         }
2778
2779                                         break;
2780                                 }
2781                         }
2782
2783                         if (*ip == CEE_CALLI) {
2784
2785                                 if ((temp = mono_emit_calli (cfg, bblock, fsig, sp, addr, ip)) != -1) {
2786                                         NEW_TEMPLOAD (cfg, *sp, temp);
2787                                         sp++;
2788                                 }
2789                                         
2790                         } else if (array_rank) {
2791                                 MonoInst *addr;
2792
2793                                 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */ 
2794                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, TRUE);
2795                                         NEW_INDSTORE (cfg, ins, addr, sp [fsig->param_count], fsig->params [fsig->param_count - 1]);
2796                                         ins->cil_code = ip;
2797                                         if (ins->opcode == CEE_STOBJ) {
2798                                                 handle_stobj (cfg, bblock, addr, sp [fsig->param_count], ip, mono_class_from_mono_type (fsig->params [fsig->param_count-1]), FALSE, FALSE);
2799                                         } else {
2800                                                 MONO_ADD_INS (bblock, ins);
2801                                         }
2802
2803                                 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
2804                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
2805                                         NEW_INDLOAD (cfg, ins, addr, fsig->ret);
2806                                         ins->cil_code = ip;
2807
2808                                         *sp++ = ins;
2809                                 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
2810                                         addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
2811                                         *sp++ = addr;
2812                                 } else {
2813                                         g_assert_not_reached ();
2814                                 }
2815
2816                         } else {
2817                                 if (0 && CODE_IS_STLOC (ip + 5) && (!MONO_TYPE_ISSTRUCT (fsig->ret)) && (!MONO_TYPE_IS_VOID (fsig->ret) || cmethod->string_ctor)) {
2818                                         /* no need to spill */
2819                                         ins = (MonoInst*)mono_emit_method_call (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL);
2820                                         *sp++ = ins;
2821                                 } else {
2822                                         if ((temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, sp, ip, virtual ? sp [0] : NULL)) != -1) {
2823                                                 NEW_TEMPLOAD (cfg, *sp, temp);
2824                                                 sp++;
2825                                         }
2826                                 }
2827                         }
2828
2829                         ip += 5;
2830                         break;
2831                 }
2832                 case CEE_RET:
2833                         if (cfg->method != method) {
2834                                 /* return from inlined methode */
2835                                 if (return_var) {
2836                                         MonoInst *store;
2837                                         CHECK_STACK (1);
2838                                         --sp;
2839                                         //g_assert (returnvar != -1);
2840                                         NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
2841                                         store->cil_code = sp [0]->cil_code;
2842                                         if (store->opcode == CEE_STOBJ) {
2843                                                 g_assert_not_reached ();
2844                                                 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
2845                                                 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, return_var->klass, FALSE, FALSE);
2846                                         } else
2847                                                 MONO_ADD_INS (bblock, store);
2848                                 } 
2849                         } else {
2850                                 if (cfg->ret) {
2851                                         g_assert (!return_var);
2852                                         CHECK_STACK (1);
2853                                         --sp;
2854                                         MONO_INST_NEW (cfg, ins, CEE_NOP);
2855                                         ins->opcode = mono_type_to_stind (method->signature->ret);
2856                                         if (ins->opcode == CEE_STOBJ) {
2857                                                 NEW_RETLOADA (cfg, ins);
2858                                                 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
2859                                         } else {
2860                                                 ins->opcode = OP_SETRET;
2861                                                 ins->cil_code = ip;
2862                                                 ins->inst_i0 = *sp;;
2863                                                 ins->inst_i1 = NULL;
2864                                                 MONO_ADD_INS (bblock, ins);
2865                                         }
2866                                 }
2867                         }
2868                         if (sp != stack_start)
2869                                 goto unverified;
2870                         MONO_INST_NEW (cfg, ins, CEE_BR);
2871                         ins->cil_code = ip++;
2872                         ins->inst_target_bb = end_bblock;
2873                         MONO_ADD_INS (bblock, ins);
2874                         link_bblock (cfg, bblock, end_bblock);
2875                         start_new_bblock = 1;
2876                         break;
2877                 case CEE_BR_S:
2878                         MONO_INST_NEW (cfg, ins, CEE_BR);
2879                         ins->cil_code = ip++;
2880                         MONO_ADD_INS (bblock, ins);
2881                         target = ip + 1 + (signed char)(*ip);
2882                         ++ip;
2883                         GET_BBLOCK (cfg, bbhash, tblock, target);
2884                         link_bblock (cfg, bblock, tblock);
2885                         CHECK_BBLOCK (target, ip, tblock);
2886                         ins->inst_target_bb = tblock;
2887                         if (sp != stack_start) {
2888                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2889                                 sp = stack_start;
2890                         }
2891                         start_new_bblock = 1;
2892                         inline_costs += 10;
2893                         break;
2894                 case CEE_BRFALSE_S:
2895                 case CEE_BRTRUE_S:
2896                         CHECK_STACK (1);
2897                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
2898                         ins->cil_code = ip++;
2899                         target = ip + 1 + *(signed char*)ip;
2900                         ip++;
2901                         ADD_UNCOND (ins->opcode == CEE_BRTRUE);
2902                         if (sp != stack_start) {
2903                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2904                                 sp = stack_start;
2905                         }
2906                         inline_costs += 10;
2907                         break;
2908                 case CEE_BEQ_S:
2909                 case CEE_BGE_S:
2910                 case CEE_BGT_S:
2911                 case CEE_BLE_S:
2912                 case CEE_BLT_S:
2913                 case CEE_BNE_UN_S:
2914                 case CEE_BGE_UN_S:
2915                 case CEE_BGT_UN_S:
2916                 case CEE_BLE_UN_S:
2917                 case CEE_BLT_UN_S:
2918                         CHECK_STACK (2);
2919                         MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
2920                         ins->cil_code = ip++;
2921                         target = ip + 1 + *(signed char*)ip;
2922                         ip++;
2923                         ADD_BINCOND (NULL);
2924                         if (sp != stack_start) {
2925                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2926                                 sp = stack_start;
2927                         }
2928                         inline_costs += 10;
2929                         break;
2930                 case CEE_BR:
2931                         MONO_INST_NEW (cfg, ins, CEE_BR);
2932                         ins->cil_code = ip++;
2933                         MONO_ADD_INS (bblock, ins);
2934                         target = ip + 4 + (gint32)read32(ip);
2935                         ip += 4;
2936                         GET_BBLOCK (cfg, bbhash, tblock, target);
2937                         link_bblock (cfg, bblock, tblock);
2938                         CHECK_BBLOCK (target, ip, tblock);
2939                         ins->inst_target_bb = tblock;
2940                         if (sp != stack_start) {
2941                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2942                                 sp = stack_start;
2943                         }
2944                         start_new_bblock = 1;
2945                         inline_costs += 10;
2946                         break;
2947                 case CEE_BRFALSE:
2948                 case CEE_BRTRUE:
2949                         CHECK_STACK (1);
2950                         MONO_INST_NEW (cfg, ins, *ip);
2951                         ins->cil_code = ip++;
2952                         target = ip + 4 + (gint32)read32(ip);
2953                         ip += 4;
2954                         ADD_UNCOND(ins->opcode == CEE_BRTRUE);
2955                         if (sp != stack_start) {
2956                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2957                                 sp = stack_start;
2958                         }
2959                         inline_costs += 10;
2960                         break;
2961                 case CEE_BEQ:
2962                 case CEE_BGE:
2963                 case CEE_BGT:
2964                 case CEE_BLE:
2965                 case CEE_BLT:
2966                 case CEE_BNE_UN:
2967                 case CEE_BGE_UN:
2968                 case CEE_BGT_UN:
2969                 case CEE_BLE_UN:
2970                 case CEE_BLT_UN:
2971                         CHECK_STACK (2);
2972                         MONO_INST_NEW (cfg, ins, *ip);
2973                         ins->cil_code = ip++;
2974                         target = ip + 4 + (gint32)read32(ip);
2975                         ip += 4;
2976                         ADD_BINCOND(NULL);
2977                         if (sp != stack_start) {
2978                                 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
2979                                 sp = stack_start;
2980                         }
2981                         inline_costs += 10;
2982                         break;
2983                 case CEE_SWITCH:
2984                         CHECK_STACK (1);
2985                         n = read32 (ip + 1);
2986                         MONO_INST_NEW (cfg, ins, *ip);
2987                         --sp;
2988                         ins->inst_left = *sp;
2989                         if (ins->inst_left->type != STACK_I4) goto unverified;
2990                         ins->cil_code = ip;
2991                         ip += 5;
2992                         target = ip + n * sizeof (guint32);
2993                         MONO_ADD_INS (bblock, ins);
2994                         GET_BBLOCK (cfg, bbhash, tblock, target);
2995                         link_bblock (cfg, bblock, tblock);
2996                         ins->klass = GUINT_TO_POINTER (n);
2997                         ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (n + 1));
2998                         ins->inst_many_bb [n] = tblock;
2999
3000                         for (i = 0; i < n; ++i) {
3001                                 GET_BBLOCK (cfg, bbhash, tblock, target + (gint32)read32(ip));
3002                                 link_bblock (cfg, bblock, tblock);
3003                                 ins->inst_many_bb [i] = tblock;
3004                                 ip += 4;
3005                         }
3006                         /* FIXME: handle stack args */
3007                         inline_costs += 20;
3008                         break;
3009                 case CEE_LDIND_I1:
3010                 case CEE_LDIND_U1:
3011                 case CEE_LDIND_I2:
3012                 case CEE_LDIND_U2:
3013                 case CEE_LDIND_I4:
3014                 case CEE_LDIND_U4:
3015                 case CEE_LDIND_I8:
3016                 case CEE_LDIND_I:
3017                 case CEE_LDIND_R4:
3018                 case CEE_LDIND_R8:
3019                 case CEE_LDIND_REF:
3020                         CHECK_STACK (1);
3021                         MONO_INST_NEW (cfg, ins, *ip);
3022                         ins->cil_code = ip;
3023                         --sp;
3024                         ins->inst_i0 = *sp;
3025                         *sp++ = ins;
3026                         ins->type = ldind_type [*ip - CEE_LDIND_I1];
3027                         ins->flags |= ins_flag;
3028                         ins_flag = 0;
3029                         ++ip;
3030                         break;
3031                 case CEE_STIND_REF:
3032                 case CEE_STIND_I1:
3033                 case CEE_STIND_I2:
3034                 case CEE_STIND_I4:
3035                 case CEE_STIND_I8:
3036                 case CEE_STIND_R4:
3037                 case CEE_STIND_R8:
3038                         CHECK_STACK (2);
3039                         MONO_INST_NEW (cfg, ins, *ip);
3040                         ins->cil_code = ip++;
3041                         sp -= 2;
3042                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3043                         MONO_ADD_INS (bblock, ins);
3044                         ins->inst_i0 = sp [0];
3045                         ins->inst_i1 = sp [1];
3046                         ins->flags |= ins_flag;
3047                         ins_flag = 0;
3048                         inline_costs += 1;
3049                         break;
3050                 case CEE_ADD:
3051                 case CEE_SUB:
3052                 case CEE_MUL:
3053                 case CEE_DIV:
3054                 case CEE_DIV_UN:
3055                 case CEE_REM:
3056                 case CEE_REM_UN:
3057                 case CEE_AND:
3058                 case CEE_OR:
3059                 case CEE_XOR:
3060                 case CEE_SHL:
3061                 case CEE_SHR:
3062                 case CEE_SHR_UN:
3063                         CHECK_STACK (2);
3064                         ADD_BINOP (*ip);
3065                         ip++;
3066                         break;
3067                 case CEE_NEG:
3068                 case CEE_NOT:
3069                 case CEE_CONV_I1:
3070                 case CEE_CONV_I2:
3071                 case CEE_CONV_I4:
3072                 case CEE_CONV_I8:
3073                 case CEE_CONV_R4:
3074                 case CEE_CONV_R8:
3075                 case CEE_CONV_U4:
3076                 case CEE_CONV_U8:
3077                 case CEE_CONV_OVF_I8:
3078                 case CEE_CONV_OVF_U8:
3079                 case CEE_CONV_R_UN:
3080                         CHECK_STACK (1);
3081                         ADD_UNOP (*ip);
3082                         ip++;
3083                         break;
3084                 case CEE_CONV_OVF_I4:
3085                 case CEE_CONV_OVF_I1:
3086                 case CEE_CONV_OVF_I2:
3087                 case CEE_CONV_OVF_I:
3088                 case CEE_CONV_OVF_U:
3089                         CHECK_STACK (1);
3090
3091                         if (sp [-1]->type == STACK_R8) {
3092                                 ADD_UNOP (CEE_CONV_OVF_I8);
3093                                 ADD_UNOP (*ip);
3094                         } else {
3095                                 ADD_UNOP (*ip);
3096                         }
3097
3098                         ip++;
3099                         break;
3100                 case CEE_CONV_OVF_U1:
3101                 case CEE_CONV_OVF_U2:
3102                 case CEE_CONV_OVF_U4:
3103                         CHECK_STACK (1);
3104
3105                         if (sp [-1]->type == STACK_R8) {
3106                                 ADD_UNOP (CEE_CONV_OVF_U8);
3107                                 ADD_UNOP (*ip);
3108                         } else {
3109                                 ADD_UNOP (*ip);
3110                         }
3111
3112                         ip++;
3113                         break;
3114                 case CEE_CONV_OVF_I1_UN:
3115                 case CEE_CONV_OVF_I2_UN:
3116                 case CEE_CONV_OVF_I4_UN:
3117                 case CEE_CONV_OVF_I8_UN:
3118                 case CEE_CONV_OVF_U1_UN:
3119                 case CEE_CONV_OVF_U2_UN:
3120                 case CEE_CONV_OVF_U4_UN:
3121                 case CEE_CONV_OVF_U8_UN:
3122                 case CEE_CONV_OVF_I_UN:
3123                 case CEE_CONV_OVF_U_UN:
3124                         CHECK_STACK (1);
3125                         ADD_UNOP (*ip);
3126                         ip++;
3127                         break;
3128                 case CEE_CPOBJ:
3129                         g_error ("opcode 0x%02x not handled", *ip);
3130                         break;
3131                 case CEE_LDOBJ: {
3132                         MonoInst *iargs [3];
3133                         CHECK_STACK (1);
3134                         --sp;
3135                         token = read32 (ip + 1);
3136                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3137                                 klass = mono_method_get_wrapper_data (method, token);
3138                         else
3139                                 klass = mono_class_get (image, token);
3140
3141                         mono_class_init (klass);
3142                         n = mono_class_value_size (klass, NULL);
3143                         ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
3144                         NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
3145                         if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
3146                                 MonoInst *copy;
3147                                 MONO_INST_NEW (cfg, copy, OP_MEMCPY);
3148                                 copy->inst_left = iargs [0];
3149                                 copy->inst_right = *sp;
3150                                 copy->cil_code = ip;
3151                                 copy->unused = n;
3152                                 MONO_ADD_INS (bblock, copy);
3153                         } else {
3154                                 iargs [1] = *sp;
3155                                 NEW_ICONST (cfg, iargs [2], n);
3156                                 iargs [2]->cil_code = ip;
3157
3158                                 mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
3159                         }
3160                         NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
3161                         ++sp;
3162                         ip += 5;
3163                         inline_costs += 1;
3164                         break;
3165                 }
3166                 case CEE_LDSTR:
3167                         CHECK_STACK_OVF (1);
3168                         n = read32 (ip + 1);
3169
3170                         if (mono_compile_aot) {
3171                                 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, (gpointer)n);
3172                         }
3173
3174                         if ((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot) {
3175                                 int temp;
3176                                 MonoInst *iargs [3];
3177                                 NEW_TEMPLOAD (cfg, iargs [0], mono_get_domainvar (cfg)->inst_c0);
3178                                 NEW_IMAGECONST (cfg, iargs [1], image);
3179                                 NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
3180                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldstr, iargs, ip);
3181                                 NEW_TEMPLOAD (cfg, *sp, temp);
3182                                 mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
3183                         } else {
3184                                 NEW_PCONST (cfg, ins, NULL);
3185                                 ins->cil_code = ip;
3186                                 ins->type = STACK_OBJ;
3187                                 ins->inst_p0 = mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
3188                                 *sp = ins;
3189                         }
3190                         sp++;
3191                         ip += 5;
3192                         break;
3193                 case CEE_NEWOBJ: {
3194                         MonoInst *iargs [2];
3195                         int temp;
3196
3197                         token = read32 (ip + 1);
3198                         if (method->wrapper_type != MONO_WRAPPER_NONE) {
3199                                 cmethod = mono_method_get_wrapper_data (method, token);
3200                         } else
3201                                 cmethod = mono_get_method (image, token, NULL);
3202
3203                         mono_class_init (cmethod->klass);
3204
3205                         n = cmethod->signature->param_count;
3206                         CHECK_STACK (n);
3207
3208                         /* move the args to allow room for 'this' in the first position */
3209                         while (n--) {
3210                                 --sp;
3211                                 sp [1] = sp [0];
3212                         }
3213
3214                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3215                         
3216
3217                         if (cmethod->klass->parent == mono_defaults.array_class) {
3218                                 NEW_METHODCONST (cfg, *sp, cmethod);
3219                                 temp = mono_emit_native_call (cfg, bblock, mono_array_new_va, cmethod->signature, sp, ip, FALSE);
3220
3221                         } else if (cmethod->string_ctor) {
3222                                 /* we simply pass a null pointer */
3223                                 NEW_PCONST (cfg, *sp, NULL); 
3224                                 /* now call the string ctor */
3225                                 temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, sp, ip, NULL);
3226                         } else {
3227                                 if (cmethod->klass->valuetype) {
3228                                         iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
3229                                         temp = iargs [0]->inst_c0;
3230                                         NEW_TEMPLOADA (cfg, *sp, temp);
3231                                 } else {
3232                                         if ((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot) {
3233                                                 NEW_DOMAINCONST (cfg, iargs [0]);
3234                                                 NEW_CLASSCONST (cfg, iargs [1], cmethod->klass);
3235
3236                                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
3237                                         } else {
3238                                                 MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
3239                                                 NEW_PCONST (cfg, iargs [0], vtable);
3240                                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new_specific, iargs, ip);
3241                                         }
3242                                         NEW_TEMPLOAD (cfg, *sp, temp);
3243                                 }
3244
3245                                 if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
3246                                     mono_method_check_inlining (cmethod) &&
3247                                     !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE) &&
3248                                     !g_list_find (dont_inline, cmethod)) {
3249                                         int costs;
3250                                         MonoBasicBlock *ebblock;
3251                                         if ((costs = inline_method (cfg, cmethod, cmethod->signature, bblock, sp, ip, real_offset, dont_inline, &ebblock))) {
3252
3253                                                 ip += 5;
3254                                                 real_offset += 5;
3255                                                 
3256                                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
3257                                                 ebblock->next_bb = bblock;
3258                                                 link_bblock (cfg, ebblock, bblock);
3259
3260                                                 NEW_TEMPLOAD (cfg, *sp, temp);
3261                                                 sp++;
3262
3263                                                 /* indicates start of a new block, and triggers a load 
3264                                                    of all stack arguments at bb boundarie */
3265                                                 bblock = ebblock;
3266
3267                                                 inline_costs += costs;
3268                                                 break;
3269                                                 
3270                                         } else {
3271                                                 mono_emit_method_call_spilled (cfg, bblock, cmethod, sp, ip, sp[0]);
3272                                         }
3273                                 } else {
3274                                         /* now call the actual ctor */
3275                                         mono_emit_method_call_spilled (cfg, bblock, cmethod, sp, ip, sp[0]);
3276                                 }
3277                         }
3278
3279                         NEW_TEMPLOAD (cfg, *sp, temp);
3280                         sp++;
3281                         
3282                         ip += 5;
3283                         inline_costs += 5;
3284                         break;
3285                 }
3286                 case CEE_ISINST:
3287                         CHECK_STACK (1);
3288                         MONO_INST_NEW (cfg, ins, *ip);
3289                         --sp;
3290                         klass = mono_class_get (image, read32 (ip + 1));
3291                         mono_class_init (klass);
3292                         ins->type = STACK_OBJ;
3293                         ins->inst_left = *sp;
3294                         ins->inst_newa_class = klass;
3295                         ins->cil_code = ip;
3296                         ip += 5;
3297                         *sp++ = ins;
3298                         break;
3299                 case CEE_UNBOX: {
3300                         MonoInst *add, *vtoffset;
3301
3302                         CHECK_STACK (1);
3303                         --sp;
3304                         token = read32 (ip + 1);
3305                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3306                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
3307                         else 
3308                                 klass = mono_class_get (image, token);
3309                         mono_class_init (klass);
3310
3311
3312                         MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
3313                         ins->type = STACK_OBJ;
3314                         ins->inst_left = *sp;
3315                         ins->klass = klass;
3316                         ins->inst_newa_class = klass;
3317                         ins->cil_code = ip;
3318
3319                         MONO_INST_NEW (cfg, add, CEE_ADD);
3320                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
3321                         add->inst_left = ins;
3322                         add->inst_right = vtoffset;
3323                         add->type = STACK_MP;
3324                         *sp++ = add;
3325                         ip += 5;
3326                         inline_costs += 2;
3327                         break;
3328                 }
3329                 case CEE_CASTCLASS:
3330                         CHECK_STACK (1);
3331                         MONO_INST_NEW (cfg, ins, *ip);
3332                         --sp;
3333                         klass = mono_class_get (image, read32 (ip + 1));
3334                         mono_class_init (klass);
3335                         ins->type = STACK_OBJ;
3336                         ins->inst_left = *sp;
3337                         ins->klass = klass;
3338                         ins->inst_newa_class = klass;
3339                         ins->cil_code = ip;
3340                         ip += 5;
3341                         *sp++ = ins;
3342                         break;
3343                 case CEE_THROW:
3344                         CHECK_STACK (1);
3345                         MONO_INST_NEW (cfg, ins, *ip);
3346                         --sp;
3347                         ins->inst_left = *sp;
3348                         ins->cil_code = ip++;
3349                         MONO_ADD_INS (bblock, ins);
3350                         sp = stack_start;
3351                         start_new_bblock = 1;
3352                         break;
3353                 case CEE_LDFLD:
3354                 case CEE_LDFLDA:
3355                 case CEE_STFLD: {
3356                         MonoInst *offset_ins;
3357                         MonoClassField *field;
3358                         MonoBasicBlock *ebblock;
3359                         int costs;
3360                         guint foffset;
3361
3362                         if (*ip == CEE_STFLD) {
3363                                 CHECK_STACK (2);
3364                                 sp -= 2;
3365                         } else {
3366                                 CHECK_STACK (1);
3367                                 --sp;
3368                         }
3369                         // FIXME: enable this test later.
3370                         //if (sp [0]->type != STACK_OBJ && sp [0]->type != STACK_MP)
3371                         //      goto unverified;
3372                         token = read32 (ip + 1);
3373                         field = mono_field_from_token (image, token, &klass);
3374                         mono_class_init (klass);
3375
3376                         foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
3377                         /* FIXME: mark instructions for use in SSA */
3378                         if (*ip == CEE_STFLD) {
3379                                 if (klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) {
3380                                         MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type); 
3381                                         MonoInst *iargs [5];
3382
3383                                         iargs [0] = sp [0];
3384                                         NEW_CLASSCONST (cfg, iargs [1], klass);
3385                                         NEW_FIELDCONST (cfg, iargs [2], field);
3386                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : 
3387                                                     field->offset);
3388                                         iargs [4] = sp [1];
3389
3390                                         if (cfg->opt & MONO_OPT_INLINE) {
3391                                                 costs = inline_method (cfg, stfld_wrapper, stfld_wrapper->signature, bblock, 
3392                                                                        iargs, ip, real_offset, dont_inline, &ebblock);
3393                                                 g_assert (costs > 0);
3394                                                       
3395                                                 ip += 5;
3396                                                 real_offset += 5;
3397
3398                                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
3399                                                 ebblock->next_bb = bblock;
3400                                                 link_bblock (cfg, ebblock, bblock);
3401
3402                                                 /* indicates start of a new block, and triggers a load 
3403                                                    of all stack arguments at bb boundarie */
3404                                                 bblock = ebblock;
3405
3406                                                 inline_costs += costs;
3407                                                 break;
3408                                         } else {
3409                                                 mono_emit_method_call_spilled (cfg, bblock, stfld_wrapper, iargs, ip, NULL);
3410                                         }
3411                                 } else {
3412                                         MonoInst *store;
3413                                         NEW_ICONST (cfg, offset_ins, foffset);
3414                                         MONO_INST_NEW (cfg, ins, CEE_ADD);
3415                                         ins->cil_code = ip;
3416                                         ins->inst_left = *sp;
3417                                         ins->inst_right = offset_ins;
3418                                         ins->type = STACK_MP;
3419
3420                                         MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
3421                                         store->cil_code = ip;
3422                                         store->inst_left = ins;
3423                                         store->inst_right = sp [1];
3424                                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3425                                         store->flags |= ins_flag;
3426                                         ins_flag = 0;
3427                                         if (store->opcode == CEE_STOBJ) {
3428                                                 handle_stobj (cfg, bblock, ins, sp [1], ip, 
3429                                                               mono_class_from_mono_type (field->type), FALSE, FALSE);
3430                                         } else
3431                                                 MONO_ADD_INS (bblock, store);
3432                                 }
3433                         } else {
3434                                 if (klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) {
3435                                         /* fixme: we need to inline that call somehow */
3436                                         MonoMethod *ldfld_wrapper = mono_marshal_get_ldfld_wrapper (field->type); 
3437                                         MonoInst *iargs [4];
3438                                         int temp;
3439                                         
3440                                         iargs [0] = sp [0];
3441                                         NEW_CLASSCONST (cfg, iargs [1], klass);
3442                                         NEW_FIELDCONST (cfg, iargs [2], field);
3443                                         NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
3444                                         if (cfg->opt & MONO_OPT_INLINE) {
3445                                                 costs = inline_method (cfg, ldfld_wrapper, ldfld_wrapper->signature, bblock, 
3446                                                                        iargs, ip, real_offset, dont_inline, &ebblock);
3447                                                 g_assert (costs > 0);
3448                                                       
3449                                                 ip += 5;
3450                                                 real_offset += 5;
3451
3452                                                 GET_BBLOCK (cfg, bbhash, bblock, ip);
3453                                                 ebblock->next_bb = bblock;
3454                                                 link_bblock (cfg, ebblock, bblock);
3455
3456                                                 temp = iargs [0]->inst_i0->inst_c0;
3457
3458                                                 if (*ip == CEE_LDFLDA) {
3459                                                         /* not sure howto handle this */
3460                                                         NEW_TEMPLOADA (cfg, *sp, temp);
3461                                                 } else {
3462                                                         NEW_TEMPLOAD (cfg, *sp, temp);
3463                                                 }
3464                                                 sp++;
3465
3466                                                 /* indicates start of a new block, and triggers a load of
3467                                                    all stack arguments at bb boundarie */
3468                                                 bblock = ebblock;
3469                                                 
3470                                                 inline_costs += costs;
3471                                                 break;
3472                                         } else {
3473                                                 temp = mono_emit_method_call_spilled (cfg, bblock, ldfld_wrapper, iargs, ip, NULL);
3474                                                 if (*ip == CEE_LDFLDA) {
3475                                                         /* not sure howto handle this */
3476                                                         NEW_TEMPLOADA (cfg, *sp, temp);
3477                                                 } else {
3478                                                         NEW_TEMPLOAD (cfg, *sp, temp);
3479                                                 }
3480                                                 sp++;
3481                                         }
3482                                 } else {
3483                                         NEW_ICONST (cfg, offset_ins, foffset);
3484                                         MONO_INST_NEW (cfg, ins, CEE_ADD);
3485                                         ins->cil_code = ip;
3486                                         ins->inst_left = *sp;
3487                                         ins->inst_right = offset_ins;
3488                                         ins->type = STACK_MP;
3489
3490                                         if (*ip == CEE_LDFLDA) {
3491                                                 *sp++ = ins;
3492                                         } else {
3493                                                 MonoInst *load;
3494                                                 MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
3495                                                 type_to_eval_stack_type (field->type, load);
3496                                                 load->cil_code = ip;
3497                                                 load->inst_left = ins;
3498                                                 load->flags |= ins_flag;
3499                                                 ins_flag = 0;
3500                                                 *sp++ = load;
3501                                         }
3502                                 }
3503                         }
3504                         ip += 5;
3505                         break;
3506                 }
3507                 case CEE_LDSFLD:
3508                 case CEE_LDSFLDA:
3509                 case CEE_STSFLD: {
3510                         MonoClassField *field;
3511                         MonoVTable *vtable;
3512
3513                         token = read32 (ip + 1);
3514
3515                         field = mono_field_from_token (image, token, &klass);
3516                         mono_class_init (klass);
3517
3518                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3519                                 
3520                         if (((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot)) {
3521                                 int temp;
3522                                 MonoInst *iargs [2];
3523                                 g_assert (field->parent);
3524                                 NEW_TEMPLOAD (cfg, iargs [0], mono_get_domainvar (cfg)->inst_c0);
3525                                 NEW_FIELDCONST (cfg, iargs [1], field);
3526                                 temp = mono_emit_jit_icall (cfg, bblock, mono_class_static_field_address, iargs, ip);
3527                                 NEW_TEMPLOAD (cfg, ins, temp);
3528                         } else {
3529                                 gpointer addr;
3530                                 vtable = mono_class_vtable (cfg->domain, klass);
3531                                 if (!cfg->domain->thread_static_fields || !(addr = g_hash_table_lookup (cfg->domain->thread_static_fields, field))) {
3532                                         addr = (char*)vtable->data + field->offset;
3533                                         NEW_PCONST (cfg, ins, addr);
3534                                         ins->cil_code = ip;
3535                                 } else {
3536                                         /* 
3537                                          * insert call to mono_threads_get_static_data (GPOINTER_TO_UINT (addr)) 
3538                                          * This could be later optimized to do just a couple of
3539                                          * memory dereferences with constant offsets.
3540                                          */
3541                                         int temp;
3542                                         MonoInst *iargs [1];
3543                                         NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
3544                                         temp = mono_emit_jit_icall (cfg, bblock, mono_threads_get_static_data, iargs, ip);
3545                                         NEW_TEMPLOAD (cfg, ins, temp);
3546                                 }
3547                         }
3548
3549                         /* FIXME: mark instructions for use in SSA */
3550                         if (*ip == CEE_LDSFLDA) {
3551                                 *sp++ = ins;
3552                         } else if (*ip == CEE_STSFLD) {
3553                                 MonoInst *store;
3554                                 CHECK_STACK (1);
3555                                 sp--;
3556                                 MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
3557                                 store->cil_code = ip;
3558                                 store->inst_left = ins;
3559                                 store->inst_right = sp [0];
3560                                 store->flags |= ins_flag;
3561                                 ins_flag = 0;
3562
3563                                 if (store->opcode == CEE_STOBJ) {
3564                                         handle_stobj (cfg, bblock, ins, sp [0], ip, mono_class_from_mono_type (field->type), FALSE, FALSE);
3565                                 } else
3566                                         MONO_ADD_INS (bblock, store);
3567                         } else {
3568                                 MonoInst *load;
3569                                 CHECK_STACK_OVF (1);
3570                                 MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
3571                                 type_to_eval_stack_type (field->type, load);
3572                                 load->cil_code = ip;
3573                                 load->inst_left = ins;
3574                                 *sp++ = load;
3575                                 load->flags |= ins_flag;
3576                                 ins_flag = 0;
3577                         /* fixme: dont see the problem why this does not work */
3578                                 //cfg->disable_aot = TRUE;
3579                         }
3580                         ip += 5;
3581                         break;
3582                 }
3583                 case CEE_STOBJ:
3584                         CHECK_STACK (2);
3585                         sp -= 2;
3586                         token = read32 (ip + 1);
3587                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3588                                 klass = mono_method_get_wrapper_data (method, token);
3589                         else
3590                                 klass = mono_class_get (image, token);
3591                         mono_class_init (klass);
3592                         handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE);
3593                         ip += 5;
3594                         inline_costs += 1;
3595                         break;
3596                 case CEE_BOX: {
3597                         MonoInst *iargs [2];
3598                         MonoInst *load, *vtoffset, *add, *val, *vstore;
3599                         int temp;
3600                         CHECK_STACK (1);
3601                         --sp;
3602                         val = *sp;
3603                         token = read32 (ip + 1);
3604                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3605                                 klass = mono_method_get_wrapper_data (method, token);
3606                         else
3607                                 klass = mono_class_get (image, token);
3608                         mono_class_init (klass);
3609
3610                         /* much like NEWOBJ */
3611                         NEW_DOMAINCONST (cfg, iargs [0]);
3612                         NEW_CLASSCONST (cfg, iargs [1], klass);
3613                         
3614                         temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
3615                         NEW_TEMPLOAD (cfg, load, temp);
3616                         NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
3617                         MONO_INST_NEW (cfg, add, CEE_ADD);
3618                         add->inst_left = load;
3619                         add->inst_right = vtoffset;
3620                         add->cil_code = ip;
3621                         add->klass = klass;
3622                         MONO_INST_NEW (cfg, vstore, CEE_STIND_I);
3623                         vstore->opcode = mono_type_to_stind (&klass->byval_arg);
3624                         vstore->cil_code = ip;
3625                         vstore->inst_left = add;
3626                         vstore->inst_right = val;
3627
3628                         if (vstore->opcode == CEE_STOBJ) {
3629                                 handle_stobj (cfg, bblock, add, val, ip, klass, FALSE, FALSE);
3630                         } else
3631                                 MONO_ADD_INS (bblock, vstore);
3632
3633                         NEW_TEMPLOAD (cfg, load, temp);
3634                         *sp++ = load;
3635                         ip += 5;
3636                         inline_costs += 1;
3637                         break;
3638                 }
3639                 case CEE_NEWARR:
3640                         CHECK_STACK (1);
3641                         MONO_INST_NEW (cfg, ins, *ip);
3642                         ins->cil_code = ip;
3643                         --sp;
3644
3645                         token = read32 (ip + 1);
3646
3647                         /* allocate the domainvar - becaus this is used in decompose_foreach */
3648                         if ((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot)
3649                                 mono_get_domainvar (cfg);
3650                         
3651                         if (method->wrapper_type != MONO_WRAPPER_NONE)
3652                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
3653                         else
3654                                 klass = mono_class_get (image, token);
3655
3656                         mono_class_init (klass);
3657                         ins->inst_newa_class = klass;
3658                         ins->inst_newa_len = *sp;
3659                         ins->type = STACK_OBJ;
3660                         ip += 5;
3661                         *sp++ = ins;
3662                         inline_costs += 1;
3663                         break;
3664                 case CEE_LDLEN:
3665                         CHECK_STACK (1);
3666                         MONO_INST_NEW (cfg, ins, *ip);
3667                         ins->cil_code = ip++;
3668                         --sp;
3669                         ins->inst_left = *sp;
3670                         ins->type = STACK_PTR;
3671                         *sp++ = ins;
3672                         break;
3673                 case CEE_LDELEMA:
3674                         CHECK_STACK (2);
3675                         sp -= 2;
3676                         klass = mono_class_get (image, read32 (ip + 1));
3677                         mono_class_init (klass);
3678                         NEW_LDELEMA (cfg, ins, sp, klass);
3679                         ins->cil_code = ip;
3680                         *sp++ = ins;
3681                         ip += 5;
3682                         break;
3683                 case CEE_LDELEM_I1:
3684                 case CEE_LDELEM_U1:
3685                 case CEE_LDELEM_I2:
3686                 case CEE_LDELEM_U2:
3687                 case CEE_LDELEM_I4:
3688                 case CEE_LDELEM_U4:
3689                 case CEE_LDELEM_I8:
3690                 case CEE_LDELEM_I:
3691                 case CEE_LDELEM_R4:
3692                 case CEE_LDELEM_R8:
3693                 case CEE_LDELEM_REF: {
3694                         MonoInst *load;
3695                         /*
3696                          * translate to:
3697                          * ldind.x (ldelema (array, index))
3698                          * ldelema does the bounds check
3699                          */
3700                         CHECK_STACK (2);
3701                         sp -= 2;
3702                         klass = array_access_to_klass (*ip);
3703                         NEW_LDELEMA (cfg, load, sp, klass);
3704                         load->cil_code = ip;
3705                         MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
3706                         ins->cil_code = ip;
3707                         ins->inst_left = load;
3708                         *sp++ = ins;
3709                         ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
3710                         ++ip;
3711                         break;
3712                 }
3713                 case CEE_STELEM_I:
3714                 case CEE_STELEM_I1:
3715                 case CEE_STELEM_I2:
3716                 case CEE_STELEM_I4:
3717                 case CEE_STELEM_I8:
3718                 case CEE_STELEM_R4:
3719                 case CEE_STELEM_R8: {
3720                         MonoInst *load;
3721                         /*
3722                          * translate to:
3723                          * stind.x (ldelema (array, index), val)
3724                          * ldelema does the bounds check
3725                          */
3726                         CHECK_STACK (3);
3727                         sp -= 3;
3728                         klass = array_access_to_klass (*ip);
3729                         NEW_LDELEMA (cfg, load, sp, klass);
3730                         load->cil_code = ip;
3731                         MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
3732                         ins->cil_code = ip;
3733                         ins->inst_left = load;
3734                         ins->inst_right = sp [2];
3735                         ++ip;
3736                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3737                         MONO_ADD_INS (bblock, ins);
3738                         /* FIXME: add the implicit STELEM_REF castclass */
3739                         inline_costs += 1;
3740                         cfg->disable_ssa = TRUE;
3741                         break;
3742                 }
3743                 case CEE_STELEM_REF: {
3744                         MonoInst *iargs [3];
3745
3746                         CHECK_STACK (3);
3747                         sp -= 3;
3748
3749                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3750
3751                         iargs [2] = sp [2];
3752                         iargs [1] = sp [1];
3753                         iargs [0] = sp [0];
3754                         
3755                         mono_emit_jit_icall (cfg, bblock, helper_stelem_ref, iargs, ip);
3756
3757                         /*
3758                         MonoInst *group;
3759                         NEW_GROUP (cfg, group, sp [0], sp [1]);
3760                         MONO_INST_NEW (cfg, ins, CEE_STELEM_REF);
3761                         ins->cil_code = ip;
3762                         ins->inst_left = group;
3763                         ins->inst_right = sp [2];
3764                         MONO_ADD_INS (bblock, ins);
3765                         */
3766
3767                         ++ip;
3768                         inline_costs += 1;
3769                         cfg->disable_ssa = TRUE;
3770                         break;
3771                 }
3772                 case CEE_CKFINITE: {
3773                         MonoInst *store, *temp;
3774                         CHECK_STACK (1);
3775
3776                         /* this instr. can throw exceptions as side effect,
3777                          * so we cant eliminate dead code which contains CKFINITE opdodes.
3778                          * Spilling to memory makes sure that we always perform
3779                          * this check */
3780
3781                         
3782                         MONO_INST_NEW (cfg, ins, CEE_CKFINITE);
3783                         ins->cil_code = ip;
3784                         ins->inst_left = sp [-1];
3785                         temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
3786
3787                         NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
3788                         store->cil_code = ip;
3789                         MONO_ADD_INS (bblock, store);
3790
3791                         NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
3792                        
3793                         ++ip;
3794                         break;
3795                 }
3796                 case CEE_REFANYVAL:
3797                 case CEE_MKREFANY:
3798                         g_error ("opcode 0x%02x not handled", *ip);
3799                         break;
3800                 case CEE_LDTOKEN: {
3801                         gpointer handle;
3802                         MonoClass *handle_class;
3803
3804                         CHECK_STACK_OVF (1);
3805
3806                         n = read32 (ip + 1);
3807
3808                         handle = mono_ldtoken (image, n, &handle_class);
3809                         mono_class_init (handle_class);
3810
3811                         if (((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot)) {
3812                                 int temp;
3813                                 MonoInst *res, *store, *addr, *vtvar, *iargs [2];
3814
3815                                 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL); 
3816
3817                                 NEW_IMAGECONST (cfg, iargs [0], image);
3818                                 NEW_ICONST (cfg, iargs [1], n);
3819                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
3820                                 NEW_TEMPLOAD (cfg, res, temp);
3821                                 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
3822                                 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
3823                                 MONO_ADD_INS (bblock, store);
3824                                 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
3825                         } else {
3826                                 if ((ip [5] == CEE_CALL) && (cmethod = mono_get_method (image, read32 (ip + 6), NULL)) &&
3827                                                 (cmethod->klass == mono_defaults.monotype_class->parent) &&
3828                                                 (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
3829                                         MonoClass *tclass = mono_class_from_mono_type (handle);
3830                                         mono_class_init (tclass);
3831                                         NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
3832                                         ins->type = STACK_OBJ;
3833                                         ins->klass = cmethod->klass;
3834                                         ip += 5;
3835                                 } else {
3836                                         NEW_PCONST (cfg, ins, handle);
3837                                         ins->type = STACK_VTYPE;
3838                                         ins->klass = handle_class;
3839                                 }
3840                         }
3841
3842                         *sp++ = ins;
3843                         ip += 5;
3844                         break;
3845                 }
3846                 case CEE_CONV_U2:
3847                 case CEE_CONV_U1:
3848                 case CEE_CONV_I:
3849                         CHECK_STACK (1);
3850                         ADD_UNOP (*ip);
3851                         ip++;
3852                         break;
3853                 case CEE_ADD_OVF:
3854                 case CEE_ADD_OVF_UN:
3855                 case CEE_MUL_OVF:
3856                 case CEE_MUL_OVF_UN:
3857                 case CEE_SUB_OVF:
3858                 case CEE_SUB_OVF_UN:
3859                         CHECK_STACK (2);
3860                         ADD_BINOP (*ip);
3861                         ip++;
3862                         break;
3863                 case CEE_ENDFINALLY:
3864                         /* FIXME: check stack state */
3865                         MONO_INST_NEW (cfg, ins, *ip);
3866                         MONO_ADD_INS (bblock, ins);
3867                         ins->cil_code = ip++;
3868                         start_new_bblock = 1;
3869                         break;
3870                 case CEE_LEAVE:
3871                 case CEE_LEAVE_S: {
3872                         GList *handlers;
3873                         if (*ip == CEE_LEAVE) {
3874                                 target = ip + 5 + (gint32)read32(ip + 1);
3875                         } else {
3876                                 target = ip + 2 + (signed char)(ip [1]);
3877                         }
3878
3879                         /* empty the stack */
3880                         while (sp != stack_start) {
3881                                 MONO_INST_NEW (cfg, ins, CEE_POP);
3882                                 ins->cil_code = ip;
3883                                 sp--;
3884                                 ins->inst_i0 = *sp;
3885                                 MONO_ADD_INS (bblock, ins);
3886                         }
3887
3888                         /* fixme: call fault handler ? */
3889
3890                         if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
3891                                 GList *tmp;
3892                                 for (tmp = handlers; tmp; tmp = tmp->next) {
3893                                         tblock = tmp->data;
3894                                         link_bblock (cfg, bblock, tblock);
3895                                         MONO_INST_NEW (cfg, ins, OP_HANDLER);
3896                                         ins->cil_code = ip;
3897                                         ins->inst_target_bb = tblock;
3898                                         MONO_ADD_INS (bblock, ins);
3899                                 }
3900                                 g_list_free (handlers);
3901                         } 
3902
3903                         MONO_INST_NEW (cfg, ins, CEE_BR);
3904                         ins->cil_code = ip;
3905                         MONO_ADD_INS (bblock, ins);
3906                         GET_BBLOCK (cfg, bbhash, tblock, target);
3907                         link_bblock (cfg, bblock, tblock);
3908                         CHECK_BBLOCK (target, ip, tblock);
3909                         ins->inst_target_bb = tblock;
3910                         start_new_bblock = 1;
3911
3912                         if (*ip == CEE_LEAVE)
3913                                 ip += 5;
3914                         else
3915                                 ip += 2;
3916
3917                         break;
3918                 }
3919                 case CEE_STIND_I:
3920                         CHECK_STACK (2);
3921                         MONO_INST_NEW (cfg, ins, *ip);
3922                         sp -= 2;
3923                         handle_loaded_temps (cfg, bblock, stack_start, sp);
3924                         MONO_ADD_INS (bblock, ins);
3925                         ins->cil_code = ip++;
3926                         ins->inst_i0 = sp [0];
3927                         ins->inst_i1 = sp [1];
3928                         inline_costs += 1;
3929                         break;
3930                 case CEE_CONV_U:
3931                         CHECK_STACK (1);
3932                         ADD_UNOP (*ip);
3933                         ip++;
3934                         break;
3935                 /* trampoline mono specific opcodes */
3936                 case MONO_CUSTOM_PREFIX: {
3937
3938                         g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
3939
3940                         switch (ip [1]) {
3941
3942                         case CEE_MONO_FUNC1: {
3943                                 int temp;
3944                                 gpointer func = NULL;
3945                                 CHECK_STACK (1);
3946                                 sp--;
3947
3948                                 switch (ip [2]) {
3949                                 case MONO_MARSHAL_CONV_STR_LPWSTR:
3950                                         func = mono_string_to_utf16;
3951                                         break;
3952                                 case MONO_MARSHAL_CONV_LPWSTR_STR:
3953                                         func = mono_string_from_utf16;
3954                                         break;
3955                                 case MONO_MARSHAL_CONV_LPSTR_STR:
3956                                         func = mono_string_new_wrapper;
3957                                         break;
3958                                 case MONO_MARSHAL_CONV_STR_LPTSTR:
3959                                 case MONO_MARSHAL_CONV_STR_LPSTR:
3960                                         func = mono_string_to_utf8;
3961                                         break;
3962                                 case MONO_MARSHAL_CONV_STR_BSTR:
3963                                         func = mono_string_to_bstr;
3964                                         break;
3965                                 case MONO_MARSHAL_CONV_STR_TBSTR:
3966                                 case MONO_MARSHAL_CONV_STR_ANSIBSTR:
3967                                         func = mono_string_to_ansibstr;
3968                                         break;
3969                                 case MONO_MARSHAL_CONV_SB_LPSTR:
3970                                         func = mono_string_builder_to_utf8;
3971                                         break;
3972                                 case MONO_MARSHAL_CONV_ARRAY_SAVEARRAY:
3973                                         func = mono_array_to_savearray;
3974                                         break;
3975                                 case MONO_MARSHAL_CONV_ARRAY_LPARRAY:
3976                                         func = mono_array_to_lparray;
3977                                         break;
3978                                 case MONO_MARSHAL_CONV_DEL_FTN:
3979                                         func = mono_delegate_to_ftnptr;
3980                                         break;
3981                                 case MONO_MARSHAL_CONV_STRARRAY_STRLPARRAY:
3982                                         func = mono_marshal_string_array;
3983                                         break;
3984                                 default:
3985                                         g_warning ("unknown conversion %d\n", ip [2]);
3986                                         g_assert_not_reached ();
3987                                 }
3988
3989                                 temp = mono_emit_jit_icall (cfg, bblock, func, sp, ip);
3990                                 NEW_TEMPLOAD (cfg, *sp, temp);
3991                                 sp++;
3992
3993                                 ip += 3;
3994                                 inline_costs += 10 * num_calls++;
3995                                 break;
3996                         }
3997                         case CEE_MONO_PROC2: {
3998                                 gpointer func = NULL;
3999                                 CHECK_STACK (2);
4000                                 sp -= 2;
4001
4002                                 switch (ip [2]) {
4003                                 case MONO_MARSHAL_CONV_LPSTR_SB:
4004                                         func = mono_string_utf8_to_builder;
4005                                         break;
4006                                 case MONO_MARSHAL_FREE_ARRAY:
4007                                         func = mono_marshal_free_array;
4008                                         break;
4009                                 default:
4010                                         g_assert_not_reached ();
4011                                 }
4012
4013                                 mono_emit_jit_icall (cfg, bblock, func, sp, ip);
4014                                 ip += 3;
4015                                 inline_costs += 10 * num_calls++;
4016                                 break;
4017                         }
4018                         case CEE_MONO_PROC3: {
4019                                 gpointer func = NULL;
4020                                 CHECK_STACK (3);
4021                                 sp -= 3;
4022
4023                                 switch (ip [2]) {
4024                                 case MONO_MARSHAL_CONV_STR_BYVALSTR:
4025                                         func = mono_string_to_byvalstr;
4026                                         break;
4027                                 case MONO_MARSHAL_CONV_STR_BYVALWSTR:
4028                                         func = mono_string_to_byvalwstr;
4029                                         break;
4030                                 default:
4031                                         g_assert_not_reached ();
4032                                 }
4033
4034                                 mono_emit_jit_icall (cfg, bblock, func, sp, ip);
4035                                 ip += 3;
4036                                 inline_costs += 10 * num_calls++;
4037                                 break;
4038                         }
4039                         case CEE_MONO_FREE:
4040                                 CHECK_STACK (1);
4041                                 sp -= 1;
4042                                 mono_emit_jit_icall (cfg, bblock, g_free, sp, ip);
4043                                 ip += 2;
4044                                 inline_costs += 10 * num_calls++;
4045                                 break;
4046                         case CEE_MONO_LDPTR:
4047                                 CHECK_STACK_OVF (1);
4048                                 token = read32 (ip + 2);
4049                                 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
4050                                 ins->cil_code = ip;
4051                                 *sp++ = ins;
4052                                 ip += 6;
4053                                 inline_costs += 10 * num_calls++;
4054                                 break;
4055                         case CEE_MONO_VTADDR:
4056                                 CHECK_STACK (1);
4057                                 --sp;
4058                                 MONO_INST_NEW (cfg, ins, OP_VTADDR);
4059                                 ins->cil_code = ip;
4060                                 ins->type = STACK_MP;
4061                                 ins->inst_left = *sp;
4062                                 *sp++ = ins;
4063                                 ip += 2;
4064                                 break;
4065                         case CEE_MONO_NEWOBJ: {
4066                                 MonoInst *iargs [2];
4067                                 int temp;
4068                                 CHECK_STACK_OVF (1);
4069                                 token = read32 (ip + 2);
4070                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
4071                                 mono_class_init (klass);
4072                                 NEW_DOMAINCONST (cfg, iargs [0]);
4073                                 NEW_CLASSCONST (cfg, iargs [1], klass);
4074                                 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
4075                                 NEW_TEMPLOAD (cfg, *sp, temp);
4076                                 sp++;
4077                                 ip += 6;
4078                                 inline_costs += 10 * num_calls++;
4079                                 break;
4080                         }
4081                         case CEE_MONO_OBJADDR:
4082                                 CHECK_STACK (1);
4083                                 --sp;
4084                                 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
4085                                 ins->cil_code = ip;
4086                                 ins->type = STACK_MP;
4087                                 ins->inst_left = *sp;
4088                                 *sp++ = ins;
4089                                 ip += 2;
4090                                 break;
4091                         case CEE_MONO_LDNATIVEOBJ:
4092                                 CHECK_STACK (1);
4093                                 token = read32 (ip + 2);
4094                                 klass = mono_method_get_wrapper_data (method, token);
4095                                 g_assert (klass->valuetype);
4096                                 mono_class_init (klass);
4097                                 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
4098                                 sp [-1] = ins;
4099                                 ip += 6;
4100                                 break;
4101                         case CEE_MONO_RETOBJ:
4102                                 g_assert (cfg->ret);
4103                                 g_assert (method->signature->pinvoke); 
4104                                 CHECK_STACK (1);
4105                                 --sp;
4106                                 
4107                                 token = read32 (ip + 2);    
4108                                 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
4109
4110                                 NEW_RETLOADA (cfg, ins);
4111                                 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE);
4112                                 
4113                                 if (sp != stack_start)
4114                                         goto unverified;
4115                                 
4116                                 MONO_INST_NEW (cfg, ins, CEE_BR);
4117                                 ins->cil_code = ip;
4118                                 ins->inst_target_bb = end_bblock;
4119                                 MONO_ADD_INS (bblock, ins);
4120                                 link_bblock (cfg, bblock, end_bblock);
4121                                 start_new_bblock = 1;
4122                                 ip += 6;
4123                                 break;
4124                         default:
4125                                 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
4126                                 break;
4127                         }
4128                         break;
4129                 }
4130                 case CEE_PREFIX1: {
4131                         switch (ip [1]) {
4132                         case CEE_ARGLIST:
4133                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
4134                                 break;
4135                         case CEE_CEQ:
4136                         case CEE_CGT:
4137                         case CEE_CGT_UN:
4138                         case CEE_CLT:
4139                         case CEE_CLT_UN: {
4140                                 MonoInst *cmp;
4141                                 CHECK_STACK (2);
4142                                 MONO_INST_NEW (cfg, cmp, 256 + ip [1]);
4143                                 MONO_INST_NEW (cfg, ins, cmp->opcode);
4144                                 sp -= 2;
4145                                 cmp->inst_i0 = sp [0];
4146                                 cmp->inst_i1 = sp [1];
4147                                 cmp->cil_code = ip;
4148                                 type_from_op (cmp);
4149                                 CHECK_TYPE (cmp);
4150                                 cmp->opcode = OP_COMPARE;
4151                                 ins->cil_code = ip;
4152                                 ins->type = STACK_I4;
4153                                 ins->inst_i0 = cmp;
4154                                 *sp++ = ins;
4155                                 ip += 2;
4156                                 break;
4157                         }
4158                         case CEE_LDFTN: {
4159                                 MonoInst *argconst;
4160                                 int temp;
4161
4162                                 CHECK_STACK_OVF (1);
4163                                 n = read32 (ip + 2);
4164                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
4165                                         cmethod = mono_method_get_wrapper_data (method, n);
4166                                 else {
4167                                         cmethod = mono_get_method (image, n, NULL);
4168
4169                                         /*
4170                                          * We can't do this in mono_ldftn, since it is used in
4171                                          * the synchronized wrapper, leading to an infinite loop.
4172                                          */
4173                                         if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
4174                                                 cmethod = mono_marshal_get_synchronized_wrapper (cmethod);
4175                                 }
4176
4177                                 mono_class_init (cmethod->klass);
4178                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4179
4180                                 NEW_METHODCONST (cfg, argconst, cmethod);
4181                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
4182                                 NEW_TEMPLOAD (cfg, *sp, temp);
4183                                 sp ++;
4184                                 
4185                                 ip += 6;
4186                                 inline_costs += 10 * num_calls++;
4187                                 break;
4188                         }
4189                         case CEE_LDVIRTFTN: {
4190                                 MonoInst *args [2];
4191                                 int temp;
4192
4193                                 CHECK_STACK (1);
4194                                 n = read32 (ip + 2);
4195                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
4196                                         cmethod = mono_method_get_wrapper_data (method, n);
4197                                 else
4198                                         cmethod = mono_get_method (image, n, NULL);
4199
4200                                 mono_class_init (cmethod->klass);
4201                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4202
4203                                 --sp;
4204                                 args [0] = *sp;
4205                                 NEW_METHODCONST (cfg, args [1], cmethod);
4206                                 temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
4207                                 NEW_TEMPLOAD (cfg, *sp, temp);
4208                                 sp ++;
4209
4210                                 ip += 6;
4211                                 inline_costs += 10 * num_calls++;
4212                                 break;
4213                         }
4214                         case CEE_LDARG:
4215                                 CHECK_STACK_OVF (1);
4216                                 NEW_ARGLOAD (cfg, ins, read16 (ip + 2));
4217                                 ins->cil_code = ip;
4218                                 *sp++ = ins;
4219                                 ip += 4;
4220                                 break;
4221                         case CEE_LDARGA:
4222                                 CHECK_STACK_OVF (1);
4223                                 NEW_ARGLOADA (cfg, ins, read16 (ip + 2));
4224                                 ins->cil_code = ip;
4225                                 *sp++ = ins;
4226                                 ip += 4;
4227                                 break;
4228                         case CEE_STARG:
4229                                 CHECK_STACK (1);
4230                                 --sp;
4231                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4232                                 n = read16 (ip + 2);
4233                                 NEW_ARGSTORE (cfg, ins, n, *sp);
4234                                 ins->cil_code = ip;
4235                                 if (ins->opcode == CEE_STOBJ) {
4236                                         NEW_ARGLOADA (cfg, ins, n);
4237                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
4238                                 } else
4239                                         MONO_ADD_INS (bblock, ins);
4240                                 ip += 4;
4241                                 break;
4242                         case CEE_LDLOC:
4243                                 CHECK_STACK_OVF (1);
4244                                 NEW_LOCLOAD (cfg, ins, read16 (ip + 2));
4245                                 ins->cil_code = ip;
4246                                 *sp++ = ins;
4247                                 ip += 4;
4248                                 break;
4249                         case CEE_LDLOCA:
4250                                 CHECK_STACK_OVF (1);
4251                                 NEW_LOCLOADA (cfg, ins, read16 (ip + 2));
4252                                 ins->cil_code = ip;
4253                                 *sp++ = ins;
4254                                 ip += 4;
4255                                 break;
4256                         case CEE_STLOC:
4257                                 CHECK_STACK (1);
4258                                 --sp;
4259                                 n = read16 (ip + 2);
4260                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4261                                 NEW_LOCSTORE (cfg, ins, n, *sp);
4262                                 ins->cil_code = ip;
4263                                 if (ins->opcode == CEE_STOBJ) {
4264                                         NEW_LOCLOADA (cfg, ins, n);
4265                                         handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
4266                                 } else
4267                                         MONO_ADD_INS (bblock, ins);
4268                                 ip += 4;
4269                                 inline_costs += 1;
4270                                 break;
4271                         case CEE_LOCALLOC:
4272                                 CHECK_STACK (1);
4273                                 --sp;
4274                                 if (sp != stack_start) 
4275                                         goto unverified;
4276                                 MONO_INST_NEW (cfg, ins, 256 + ip [1]);
4277                                 ins->inst_left = *sp;
4278                                 ins->cil_code = ip;
4279
4280                                 if (header->init_locals)
4281                                         ins->flags |= MONO_INST_INIT;
4282
4283                                 *sp++ = ins;
4284                                 ip += 2;
4285                                 /* FIXME: set init flag if locals init is set in this method */
4286                                 break;
4287                         case CEE_ENDFILTER: {
4288                                 MonoExceptionClause *clause, *nearest;
4289                                 int cc, nearest_num;
4290
4291                                 CHECK_STACK (1);
4292                                 --sp;
4293                                 if ((sp != stack_start) || (sp [0]->type != STACK_I4)) 
4294                                         goto unverified;
4295                                 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
4296                                 ins->inst_left = *sp;
4297                                 ins->cil_code = ip;
4298                                 MONO_ADD_INS (bblock, ins);
4299                                 start_new_bblock = 1;
4300                                 ip += 2;
4301
4302                                 nearest = NULL;
4303                                 for (cc = 0; cc < header->num_clauses; ++cc) {
4304                                         clause = &header->clauses [cc];
4305                                         if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
4306                                             (!nearest || (clause->token_or_filter > nearest->token_or_filter))) {
4307                                                 nearest = clause;
4308                                                 nearest_num = cc;
4309                                         }
4310                                 }
4311                                 g_assert (nearest);
4312                                 filter_lengths [nearest_num] = (ip - header->code) -  nearest->token_or_filter;
4313
4314                                 break;
4315                         }
4316                         case CEE_UNALIGNED_:
4317                                 ins_flag |= MONO_INST_UNALIGNED;
4318                                 ip += 3;
4319                                 break;
4320                         case CEE_VOLATILE_:
4321                                 ins_flag |= MONO_INST_VOLATILE;
4322                                 ip += 2;
4323                                 break;
4324                         case CEE_TAIL_:
4325                                 ins_flag |= MONO_INST_TAILCALL;
4326                                 ip += 2;
4327                                 break;
4328                         case CEE_INITOBJ:
4329                                 CHECK_STACK (1);
4330                                 --sp;
4331                                 token = read32 (ip + 2);
4332                                 if (method->wrapper_type != MONO_WRAPPER_NONE)
4333                                         klass = mono_method_get_wrapper_data (method, token);
4334                                 else
4335                                         klass = mono_class_get (image, token);
4336                                 handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
4337                                 ip += 6;
4338                                 inline_costs += 1;
4339                                 break;
4340                         case CEE_CPBLK:
4341                         case CEE_INITBLK: {
4342                                 MonoInst *iargs [3];
4343                                 CHECK_STACK (3);
4344                                 sp -= 3;
4345                                 iargs [0] = sp [0];
4346                                 iargs [1] = sp [1];
4347                                 iargs [2] = sp [2];
4348                                 handle_loaded_temps (cfg, bblock, stack_start, sp);
4349                                 if (ip [1] == CEE_CPBLK) {
4350                                         mono_emit_jit_icall (cfg, bblock, helper_memcpy, iargs, ip);
4351                                 } else {
4352                                         mono_emit_jit_icall (cfg, bblock, helper_memset, iargs, ip);
4353                                 }
4354                                 ip += 2;
4355                                 inline_costs += 1;
4356                                 break;
4357                         }
4358                         case CEE_RETHROW: {
4359                                 MonoInst *load;
4360                                 /* FIXME: check we are in a catch handler */
4361                                 NEW_TEMPLOAD (cfg, load, cfg->exvar->inst_c0);
4362                                 load->cil_code = ip;
4363                                 MONO_INST_NEW (cfg, ins, CEE_THROW);
4364                                 ins->inst_left = load;
4365                                 ins->cil_code = ip;
4366                                 MONO_ADD_INS (bblock, ins);
4367                                 sp = stack_start;
4368                                 start_new_bblock = 1;
4369                                 ip += 2;
4370                                 break;
4371                         }
4372                         case CEE_SIZEOF:
4373                                 CHECK_STACK_OVF (1);
4374                                 token = read32 (ip + 2);
4375                                 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
4376                                         MonoType *type = mono_type_create_from_typespec (image, token);
4377                                         token = mono_type_size (type, &align);
4378                                         mono_metadata_free_type (type);
4379                                 } else {
4380                                         MonoClass *szclass = mono_class_get (image, token);
4381                                         mono_class_init (szclass);
4382                                         token = mono_class_value_size (szclass, &align);
4383                                 }
4384                                 NEW_ICONST (cfg, ins, token);
4385                                 ins->cil_code = ip;
4386                                 *sp++= ins;
4387                                 ip += 6;
4388                                 break;
4389                         case CEE_REFANYTYPE:
4390                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
4391                                 break;
4392                         default:
4393                                 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
4394                         }
4395                         break;
4396                 }
4397                 default:
4398                         g_error ("opcode 0x%02x not handled", *ip);
4399                 }
4400         }
4401         if (start_new_bblock != 1)
4402                 goto unverified;
4403
4404         bblock->cil_length = ip - bblock->cil_code;
4405         bblock->next_bb = end_bblock;
4406         link_bblock (cfg, bblock, end_bblock);
4407
4408         if (cfg->method == method && cfg->domainvar) {
4409                 MonoCallInst *call;
4410                 MonoInst *store;
4411
4412                 MONO_INST_NEW_CALL (cfg, call, CEE_CALL);
4413                 call->signature = helper_sig_domain_get;
4414                 call->inst.type = STACK_PTR;
4415                 call->fptr = mono_domain_get;
4416                 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, (MonoInst*)call);
4417                 
4418                 MONO_ADD_INS (init_localsbb, store);
4419         }
4420
4421         if (header->init_locals) {
4422                 MonoInst *store;
4423                 for (i = 0; i < header->num_locals; ++i) {
4424                         int t = header->locals [i]->type;
4425                         if (t == MONO_TYPE_VALUETYPE && header->locals [i]->data.klass->enumtype)
4426                                 t = header->locals [i]->data.klass->enum_basetype->type;
4427                         /* FIXME: use initobj for valuetypes, handle pointers, long, float. */
4428                         if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
4429                                 NEW_ICONST (cfg, ins, 0);
4430                                 NEW_LOCSTORE (cfg, store, i, ins);
4431                                 MONO_ADD_INS (init_localsbb, store);
4432                         } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
4433                                 MONO_INST_NEW (cfg, ins, OP_I8CONST);
4434                                 ins->type = STACK_I8;
4435                                 ins->inst_l = 0;
4436                                 NEW_LOCSTORE (cfg, store, i, ins);
4437                                 MONO_ADD_INS (init_localsbb, store);
4438                         } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
4439                                 MONO_INST_NEW (cfg, ins, OP_R8CONST);
4440                                 ins->type = STACK_R8;
4441                                 ins->inst_p0 = (void*)&r8_0;
4442                                 NEW_LOCSTORE (cfg, store, i, ins);
4443                                 MONO_ADD_INS (init_localsbb, store);
4444                         } else if (t == MONO_TYPE_VALUETYPE) {
4445                                 NEW_LOCLOADA (cfg, ins, i);
4446                                 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (header->locals [i]), NULL, NULL);
4447                                 break;
4448                         } else {
4449                                 NEW_PCONST (cfg, ins, NULL);
4450                                 NEW_LOCSTORE (cfg, store, i, ins);
4451                                 MONO_ADD_INS (init_localsbb, store);
4452                         }
4453                 }
4454         }
4455
4456         
4457         /* resolve backward branches in the middle of an existing basic block */
4458         for (tmp = bb_recheck; tmp; tmp = tmp->next) {
4459                 bblock = tmp->data;
4460                 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
4461                 tblock = find_previous (bbhash, start_bblock, bblock->cil_code);
4462                 if (tblock != start_bblock) {
4463                         int l;
4464                         split_bblock (cfg, tblock, bblock);
4465                         l = bblock->cil_code - header->code;
4466                         bblock->cil_length = tblock->cil_length - l;
4467                         tblock->cil_length = l;
4468                 } else {
4469                         g_print ("recheck failed.\n");
4470                 }
4471         }
4472
4473         /* we compute regions here, because the length of filter clauses is not known in advance.
4474         * It is computed in the CEE_ENDFILTER case in the above switch statement*/
4475         if (cfg->method == method) {
4476                 MonoBasicBlock *bb;
4477                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4478                         bb->region = mono_find_block_region (cfg, bb->real_offset, filter_lengths);
4479                         if (cfg->verbose_level > 2)
4480                                 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
4481                 }
4482         } else {
4483                 g_hash_table_destroy (bbhash);
4484         }
4485
4486         dont_inline = g_list_remove (dont_inline, method);
4487         return inline_costs;
4488
4489  inline_failure:
4490         if (cfg->method != method) 
4491                 g_hash_table_destroy (bbhash);
4492         dont_inline = g_list_remove (dont_inline, method);
4493         return -1;
4494
4495  unverified:
4496         if (cfg->method != method) 
4497                 g_hash_table_destroy (bbhash);
4498         g_error ("Invalid IL code at IL%04x in %s: %s\n", ip - header->code, 
4499                  mono_method_full_name (method, TRUE), mono_disasm_code_one (NULL, method, ip, NULL));
4500         dont_inline = g_list_remove (dont_inline, method);
4501         return -1;
4502 }
4503
4504 void
4505 mono_print_tree (MonoInst *tree) {
4506         int arity;
4507
4508         if (!tree)
4509                 return;
4510
4511         arity = mono_burg_arity [tree->opcode];
4512
4513         printf (" %s%s", arity?"(":"",  mono_inst_name (tree->opcode));
4514
4515         switch (tree->opcode) {
4516         case OP_ICONST:
4517                 printf ("[%d]", tree->inst_c0);
4518                 break;
4519         case OP_I8CONST:
4520                 printf ("[%lld]", tree->inst_l);
4521                 break;
4522         case OP_R8CONST:
4523                 printf ("[%f]", *(double*)tree->inst_p0);
4524                 break;
4525         case OP_R4CONST:
4526                 printf ("[%f]", *(float*)tree->inst_p0);
4527                 break;
4528         case OP_ARG:
4529         case OP_LOCAL:
4530                 printf ("[%d]", tree->inst_c0);
4531                 break;
4532         case OP_REGOFFSET:
4533                 printf ("[0x%x(%s)]", tree->inst_offset, mono_arch_regname (tree->inst_basereg));
4534                 break;
4535         case OP_REGVAR:
4536                 printf ("[%s]", mono_arch_regname (tree->dreg));
4537                 break;
4538         case CEE_NEWARR:
4539                 printf ("[%s]",  tree->inst_newa_class->name);
4540                 mono_print_tree (tree->inst_newa_len);
4541                 break;
4542         case CEE_CALL:
4543         case CEE_CALLVIRT:
4544         case OP_FCALL:
4545         case OP_FCALLVIRT:
4546         case OP_LCALL:
4547         case OP_LCALLVIRT:
4548         case OP_VCALL:
4549         case OP_VCALLVIRT:
4550         case OP_VOIDCALL:
4551         case OP_VOIDCALLVIRT: {
4552                 MonoCallInst *call = (MonoCallInst*)tree;
4553                 if (call->method)
4554                         printf ("[%s]", call->method->name);
4555                 break;
4556         }
4557         case OP_PHI: {
4558                 int i;
4559                 printf ("[%d (", tree->inst_c0);
4560                 for (i = 0; i < tree->inst_phi_args [0]; i++) {
4561                         if (i)
4562                                 printf (", ");
4563                         printf ("%d", tree->inst_phi_args [i + 1]);
4564                 }
4565                 printf (")]");
4566                 break;
4567         }
4568         case OP_RENAME:
4569         case OP_RETARG:
4570         case CEE_NOP:
4571         case CEE_JMP:
4572         case CEE_BREAK:
4573                 break;
4574         case CEE_BR:
4575                 printf ("[B%d]", tree->inst_target_bb->block_num);
4576                 break;
4577         case CEE_SWITCH:
4578         case CEE_ISINST:
4579         case CEE_CASTCLASS:
4580         case OP_OUTARG:
4581         case OP_CALL_REG:
4582         case OP_FCALL_REG:
4583         case OP_LCALL_REG:
4584         case OP_VCALL_REG:
4585         case OP_VOIDCALL_REG:
4586                 mono_print_tree (tree->inst_left);
4587                 break;
4588         case CEE_BNE_UN:
4589         case CEE_BEQ:
4590         case CEE_BLT:
4591         case CEE_BLT_UN:
4592         case CEE_BGT:
4593         case CEE_BGT_UN:
4594         case CEE_BGE:
4595         case CEE_BGE_UN:
4596         case CEE_BLE:
4597         case CEE_BLE_UN:
4598                 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
4599                 mono_print_tree (tree->inst_left);
4600                 break;
4601         default:
4602                 if (arity) {
4603                         mono_print_tree (tree->inst_left);
4604                         if (arity > 1)
4605                                 mono_print_tree (tree->inst_right);
4606                 }
4607                 break;
4608         }
4609
4610         if (arity)
4611                 printf (")");
4612 }
4613
4614 static void
4615 create_helper_signature (void)
4616 {
4617         /* FIXME: set call conv */
4618         /* MonoArray * mono_array_new (MonoDomain *domain, MonoClass *klass, gint32 len) */
4619         helper_sig_newarr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4620         helper_sig_newarr->params [0] = helper_sig_newarr->params [1] = &mono_defaults.int_class->byval_arg;
4621         helper_sig_newarr->ret = &mono_defaults.object_class->byval_arg;
4622         helper_sig_newarr->params [2] = &mono_defaults.int32_class->byval_arg;
4623         helper_sig_newarr->pinvoke = 1;
4624
4625         /* MonoArray * mono_array_new_specific (MonoVTable *vtable, guint32 len) */
4626         helper_sig_newarr_specific = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4627         helper_sig_newarr_specific->params [0] = &mono_defaults.int_class->byval_arg;
4628         helper_sig_newarr_specific->params [1] = &mono_defaults.int32_class->byval_arg;
4629         helper_sig_newarr_specific->ret = &mono_defaults.object_class->byval_arg;
4630         helper_sig_newarr_specific->pinvoke = 1;
4631
4632         /* MonoObject * mono_object_new (MonoDomain *domain, MonoClass *klass) */
4633         helper_sig_object_new = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4634         helper_sig_object_new->params [0] = helper_sig_object_new->params [1] = &mono_defaults.int_class->byval_arg;
4635         helper_sig_object_new->ret = &mono_defaults.object_class->byval_arg;
4636         helper_sig_object_new->pinvoke = 1;
4637
4638         /* MonoObject * mono_object_new_specific (MonoVTable *vtable) */
4639         helper_sig_object_new_specific = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4640         helper_sig_object_new_specific->params [0] = &mono_defaults.int_class->byval_arg;
4641         helper_sig_object_new_specific->ret = &mono_defaults.object_class->byval_arg;
4642         helper_sig_object_new_specific->pinvoke = 1;
4643
4644         /* void* mono_method_compile (MonoMethod*) */
4645         helper_sig_compile = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4646         helper_sig_compile->params [0] = helper_sig_compile->ret = &mono_defaults.int_class->byval_arg;
4647         helper_sig_compile->pinvoke = 1;
4648
4649         /* void* mono_ldvirtfn (MonoObject *, MonoMethod*) */
4650         helper_sig_compile_virt = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4651         helper_sig_compile_virt->params [0] = &mono_defaults.object_class->byval_arg;
4652         helper_sig_compile_virt->params [1] = helper_sig_compile_virt->ret = &mono_defaults.int_class->byval_arg;
4653         helper_sig_compile_virt->pinvoke = 1;
4654
4655         /* MonoString* mono_ldstr (MonoDomain *domain, MonoImage *image, guint32 str_index) */
4656         helper_sig_ldstr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4657         helper_sig_ldstr->params [0] = helper_sig_ldstr->params [1] = &mono_defaults.int_class->byval_arg;
4658         helper_sig_ldstr->params [2] = &mono_defaults.int32_class->byval_arg;
4659         helper_sig_ldstr->ret = &mono_defaults.object_class->byval_arg;
4660         helper_sig_ldstr->pinvoke = 1;
4661
4662         /* MonoDomain *mono_domain_get (void) */
4663         helper_sig_domain_get = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4664         helper_sig_domain_get->ret = &mono_defaults.int_class->byval_arg;
4665         helper_sig_domain_get->pinvoke = 1;
4666
4667         /* void* stelem_ref (MonoArray *, int index, MonoObject *) */
4668         helper_sig_stelem_ref = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4669         helper_sig_stelem_ref->params [0] = &mono_defaults.array_class->byval_arg;
4670         helper_sig_stelem_ref->params [1] = &mono_defaults.int32_class->byval_arg;
4671         helper_sig_stelem_ref->params [2] = &mono_defaults.object_class->byval_arg;
4672         helper_sig_stelem_ref->ret = &mono_defaults.void_class->byval_arg;
4673         helper_sig_stelem_ref->pinvoke = 1;
4674
4675         /* long amethod (long, long) */
4676         helper_sig_long_long_long = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4677         helper_sig_long_long_long->params [0] = helper_sig_long_long_long->params [1] = 
4678                 &mono_defaults.int64_class->byval_arg;
4679         helper_sig_long_long_long->ret = &mono_defaults.int64_class->byval_arg;
4680         helper_sig_long_long_long->pinvoke = 1;
4681
4682         /* object  amethod (intptr) */
4683         helper_sig_obj_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4684         helper_sig_obj_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4685         helper_sig_obj_ptr->ret = &mono_defaults.object_class->byval_arg;
4686         helper_sig_obj_ptr->pinvoke = 1;
4687
4688         /* void amethod (intptr) */
4689         helper_sig_void_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4690         helper_sig_void_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4691         helper_sig_void_ptr->ret = &mono_defaults.void_class->byval_arg;
4692         helper_sig_void_ptr->pinvoke = 1;
4693
4694         /* void amethod (MonoObject *obj) */
4695         helper_sig_void_obj = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4696         helper_sig_void_obj->params [0] = &mono_defaults.object_class->byval_arg;
4697         helper_sig_void_obj->ret = &mono_defaults.void_class->byval_arg;
4698         helper_sig_void_obj->pinvoke = 1;
4699
4700         /* intptr amethod (void) */
4701         helper_sig_ptr_void = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
4702         helper_sig_ptr_void->ret = &mono_defaults.int_class->byval_arg;
4703         helper_sig_ptr_void->pinvoke = 1;
4704
4705         /* void  amethod (intptr, intptr) */
4706         helper_sig_void_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4707         helper_sig_void_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4708         helper_sig_void_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
4709         helper_sig_void_ptr_ptr->ret = &mono_defaults.void_class->byval_arg;
4710         helper_sig_void_ptr_ptr->pinvoke = 1;
4711
4712         /* void  amethod (intptr, intptr, intptr) */
4713         helper_sig_void_ptr_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4714         helper_sig_void_ptr_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4715         helper_sig_void_ptr_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
4716         helper_sig_void_ptr_ptr_ptr->params [2] = &mono_defaults.int_class->byval_arg;
4717         helper_sig_void_ptr_ptr_ptr->ret = &mono_defaults.void_class->byval_arg;
4718         helper_sig_void_ptr_ptr_ptr->pinvoke = 1;
4719
4720         /* intptr  amethod (intptr, intptr) */
4721         helper_sig_ptr_ptr_ptr = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4722         helper_sig_ptr_ptr_ptr->params [0] = &mono_defaults.int_class->byval_arg;
4723         helper_sig_ptr_ptr_ptr->params [1] = &mono_defaults.int_class->byval_arg;
4724         helper_sig_ptr_ptr_ptr->ret = &mono_defaults.int_class->byval_arg;
4725         helper_sig_ptr_ptr_ptr->pinvoke = 1;
4726
4727         /* IntPtr  amethod (object) */
4728         helper_sig_ptr_obj = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4729         helper_sig_ptr_obj->params [0] = &mono_defaults.object_class->byval_arg;
4730         helper_sig_ptr_obj->ret = &mono_defaults.int_class->byval_arg;
4731         helper_sig_ptr_obj->pinvoke = 1;
4732
4733         /* IntPtr  amethod (int) */
4734         helper_sig_ptr_int = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4735         helper_sig_ptr_int->params [0] = &mono_defaults.int32_class->byval_arg;
4736         helper_sig_ptr_int->ret = &mono_defaults.int_class->byval_arg;
4737         helper_sig_ptr_int->pinvoke = 1;
4738
4739         /* long amethod (long, guint32) */
4740         helper_sig_long_long_int = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4741         helper_sig_long_long_int->params [0] = &mono_defaults.int64_class->byval_arg;
4742         helper_sig_long_long_int->params [1] = &mono_defaults.int32_class->byval_arg;
4743         helper_sig_long_long_int->ret = &mono_defaults.int64_class->byval_arg;
4744         helper_sig_long_long_int->pinvoke = 1;
4745
4746         /* ulong amethod (double) */
4747         helper_sig_ulong_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4748         helper_sig_ulong_double->params [0] = &mono_defaults.double_class->byval_arg;
4749         helper_sig_ulong_double->ret = &mono_defaults.uint64_class->byval_arg;
4750         helper_sig_ulong_double->pinvoke = 1;
4751
4752         /* long amethod (double) */
4753         helper_sig_long_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4754         helper_sig_long_double->params [0] = &mono_defaults.double_class->byval_arg;
4755         helper_sig_long_double->ret = &mono_defaults.int64_class->byval_arg;
4756         helper_sig_long_double->pinvoke = 1;
4757
4758         /* uint amethod (double) */
4759         helper_sig_uint_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4760         helper_sig_uint_double->params [0] = &mono_defaults.double_class->byval_arg;
4761         helper_sig_uint_double->ret = &mono_defaults.uint32_class->byval_arg;
4762         helper_sig_uint_double->pinvoke = 1;
4763
4764         /* int amethod (double) */
4765         helper_sig_int_double = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
4766         helper_sig_int_double->params [0] = &mono_defaults.double_class->byval_arg;
4767         helper_sig_int_double->ret = &mono_defaults.int32_class->byval_arg;
4768         helper_sig_int_double->pinvoke = 1;
4769
4770         /* void  initobj (intptr, int size) */
4771         helper_sig_initobj = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
4772         helper_sig_initobj->params [0] = &mono_defaults.int_class->byval_arg;
4773         helper_sig_initobj->params [1] = &mono_defaults.int32_class->byval_arg;
4774         helper_sig_initobj->ret = &mono_defaults.void_class->byval_arg;
4775         helper_sig_initobj->pinvoke = 1;
4776
4777         /* void  memcpy (intptr, intptr, int size) */
4778         helper_sig_memcpy = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4779         helper_sig_memcpy->params [0] = &mono_defaults.int_class->byval_arg;
4780         helper_sig_memcpy->params [1] = &mono_defaults.int_class->byval_arg;
4781         helper_sig_memcpy->params [2] = &mono_defaults.int32_class->byval_arg;
4782         helper_sig_memcpy->ret = &mono_defaults.void_class->byval_arg;
4783         helper_sig_memcpy->pinvoke = 1;
4784
4785         /* void  memset (intptr, int val, int size) */
4786         helper_sig_memset = mono_metadata_signature_alloc (mono_defaults.corlib, 3);
4787         helper_sig_memset->params [0] = &mono_defaults.int_class->byval_arg;
4788         helper_sig_memset->params [1] = &mono_defaults.int32_class->byval_arg;
4789         helper_sig_memset->params [2] = &mono_defaults.int32_class->byval_arg;
4790         helper_sig_memset->ret = &mono_defaults.void_class->byval_arg;
4791         helper_sig_memset->pinvoke = 1;
4792 }
4793
4794 static GHashTable *jit_icall_hash_name = NULL;
4795 static GHashTable *jit_icall_hash_addr = NULL;
4796
4797 MonoJitICallInfo *
4798 mono_find_jit_icall_by_name (const char *name)
4799 {
4800         g_assert (jit_icall_hash_name);
4801
4802         //printf ("lookup addr %s %p\n", name, g_hash_table_lookup (jit_icall_hash_name, name));
4803         return g_hash_table_lookup (jit_icall_hash_name, name);
4804 }
4805
4806 MonoJitICallInfo *
4807 mono_find_jit_icall_by_addr (gconstpointer addr)
4808 {
4809         g_assert (jit_icall_hash_addr);
4810
4811         return g_hash_table_lookup (jit_icall_hash_addr, (gpointer)addr);
4812 }
4813
4814 MonoJitICallInfo *
4815 mono_register_jit_icall (gconstpointer func, const char *name, MonoMethodSignature *sig, gboolean is_save)
4816 {
4817         MonoJitICallInfo *info;
4818         MonoMethod *wrapper;
4819         char *n;
4820         
4821         g_assert (func);
4822         g_assert (name);
4823
4824         if (!jit_icall_hash_name) {
4825                 jit_icall_hash_name = g_hash_table_new (g_str_hash, g_str_equal);
4826                 jit_icall_hash_addr = g_hash_table_new (NULL, NULL);
4827         }
4828
4829         if (g_hash_table_lookup (jit_icall_hash_name, name)) {
4830                 g_warning ("jit icall already defined \"%s\"\n", name);
4831                 g_assert_not_reached ();
4832         }
4833
4834         info = g_new (MonoJitICallInfo, 1);
4835         
4836         info->name = g_strdup (name);
4837         info->func = func;
4838         info->sig = sig;
4839                 
4840         if (is_save
4841 #ifdef MONO_USE_EXC_TABLES
4842             || mono_arch_has_unwind_info (func)
4843 #endif
4844             ) {
4845                 info->wrapper = func;
4846         } else {
4847                 g_assert (sig);
4848                 n = g_strdup_printf ("__icall_wrapper_%s", name);       
4849                 wrapper = mono_marshal_get_icall_wrapper (sig, n, func);
4850                 info->wrapper = mono_jit_compile_method (wrapper);
4851                 g_free (n);
4852         }
4853
4854         g_hash_table_insert (jit_icall_hash_name, info->name, info);
4855         g_hash_table_insert (jit_icall_hash_addr, (gpointer)func, info);
4856         if (func != info->wrapper)
4857                 g_hash_table_insert (jit_icall_hash_addr, (gpointer)info->wrapper, info);
4858
4859         return info;
4860 }
4861
4862 static GHashTable *emul_opcode_hash = NULL;
4863
4864 static MonoJitICallInfo *
4865 mono_find_jit_opcode_emulation (int opcode)
4866 {
4867         if  (emul_opcode_hash)
4868                 return g_hash_table_lookup (emul_opcode_hash, (gpointer)opcode);
4869         else
4870                 return NULL;
4871 }
4872
4873 void
4874 mono_register_opcode_emulation (int opcode, MonoMethodSignature *sig, gpointer func)
4875 {
4876         MonoJitICallInfo *info;
4877         char *name;
4878
4879         if (!emul_opcode_hash)
4880                 emul_opcode_hash = g_hash_table_new (NULL, NULL);
4881
4882         g_assert (!sig->hasthis);
4883         g_assert (sig->param_count < 3);
4884
4885         name = g_strdup_printf ("__emulate_%s",  mono_inst_name (opcode));
4886
4887         info = mono_register_jit_icall (func, name, sig, FALSE);
4888
4889         g_free (name);
4890
4891         g_hash_table_insert (emul_opcode_hash, (gpointer)opcode, info);
4892 }
4893
4894 static void
4895 decompose_foreach (MonoInst *tree, gpointer data) 
4896 {
4897         static MonoJitICallInfo *newarr_info = NULL;
4898         static MonoJitICallInfo *newarr_specific_info = NULL;
4899         MonoJitICallInfo *info;
4900
4901         switch (tree->opcode) {
4902         case CEE_NEWARR: {
4903                 MonoCompile *cfg = data;
4904                 MonoInst *iargs [3];
4905
4906                 if (!newarr_info) {
4907                         newarr_info = mono_find_jit_icall_by_addr (mono_array_new);
4908                         g_assert (newarr_info);
4909                         newarr_specific_info = mono_find_jit_icall_by_addr (mono_array_new_specific);
4910                         g_assert (newarr_specific_info);
4911                 }
4912
4913                 if ((cfg->opt & MONO_OPT_SHARED) || mono_compile_aot) {
4914                         NEW_DOMAINCONST (cfg, iargs [0]);
4915                         NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
4916                         iargs [2] = tree->inst_newa_len;
4917
4918                         info = newarr_info;
4919                 }
4920                 else {
4921                         MonoVTable *vtable = mono_class_vtable (cfg->domain, 
4922                                                                                                         mono_array_class_get (&tree->inst_newa_class->byval_arg, 1));
4923
4924                         NEW_PCONST (cfg, iargs [0], vtable);
4925                         iargs [1] = tree->inst_newa_len;
4926
4927                         info = newarr_specific_info;
4928                 }
4929
4930                 mono_emulate_opcode (cfg, tree, iargs, info);
4931                 break;
4932         }
4933
4934         default:
4935                 break;
4936         }
4937 }
4938
4939 void
4940 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
4941
4942         switch (mono_burg_arity [tree->opcode]) {
4943         case 0: break;
4944         case 1: 
4945                 mono_inst_foreach (tree->inst_left, func, data);
4946                 break;
4947         case 2: 
4948                 mono_inst_foreach (tree->inst_left, func, data);
4949                 mono_inst_foreach (tree->inst_right, func, data);
4950                 break;
4951         default:
4952                 g_assert_not_reached ();
4953         }
4954         func (tree, data);
4955 }
4956
4957 #if 0
4958 static void
4959 mono_print_bb_code (MonoBasicBlock *bb) {
4960         if (bb->code) {
4961                 MonoInst *c = bb->code;
4962                 while (c) {
4963                         mono_print_tree (c);
4964                         g_print ("\n");
4965                         c = c->next;
4966                 }
4967         }
4968 }
4969 #endif
4970
4971 static void
4972 print_dfn (MonoCompile *cfg) {
4973         int i, j;
4974         char *code;
4975         MonoBasicBlock *bb;
4976
4977         g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
4978
4979         for (i = 0; i < cfg->num_bblocks; ++i) {
4980                 bb = cfg->bblocks [i];
4981                 if (bb->cil_code) {
4982                         char* code1, *code2;
4983                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
4984                         if (bb->last_ins->cil_code)
4985                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
4986                         else
4987                                 code2 = g_strdup ("");
4988
4989                         code1 [strlen (code1) - 1] = 0;
4990                         code = g_strdup_printf ("%s -> %s", code1, code2);
4991                         g_free (code1);
4992                         g_free (code2);
4993                 } else
4994                         code = g_strdup ("\n");
4995                 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
4996                 if (bb->code) {
4997                         MonoInst *c = bb->code;
4998                         while (c) {
4999                                 mono_print_tree (c);
5000                                 g_print ("\n");
5001                                 c = c->next;
5002                         }
5003                 } else {
5004
5005                 }
5006
5007                 g_print ("\tprev:");
5008                 for (j = 0; j < bb->in_count; ++j) {
5009                         g_print (" BB%d", bb->in_bb [j]->block_num);
5010                 }
5011                 g_print ("\t\tsucc:");
5012                 for (j = 0; j < bb->out_count; ++j) {
5013                         g_print (" BB%d", bb->out_bb [j]->block_num);
5014                 }
5015                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
5016
5017                 if (bb->idom)
5018                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
5019
5020                 if (bb->dominators)
5021                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
5022                 if (bb->dfrontier)
5023                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
5024                 g_free (code);
5025         }
5026
5027         g_print ("\n");
5028 }
5029
5030 /*
5031  * returns the offset used by spillvar. It allocates a new
5032  * spill variable if necessary. 
5033  */
5034 int
5035 mono_spillvar_offset (MonoCompile *cfg, int spillvar)
5036 {
5037         MonoSpillInfo **si, *info;
5038         int i = 0;
5039
5040         si = &cfg->spill_info; 
5041         
5042         while (i <= spillvar) {
5043
5044                 if (!*si) {
5045                         *si = info = mono_mempool_alloc (cfg->mempool, sizeof (MonoSpillInfo));
5046                         info->next = NULL;
5047                         cfg->stack_offset -= sizeof (gpointer);
5048                         info->offset = cfg->stack_offset;
5049                 }
5050
5051                 if (i == spillvar)
5052                         return (*si)->offset;
5053
5054                 i++;
5055                 si = &(*si)->next;
5056         }
5057
5058         g_assert_not_reached ();
5059         return 0;
5060 }
5061
5062 void
5063 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
5064 {
5065         inst->next = NULL;
5066         if (bb->last_ins) {
5067                 g_assert (bb->code);
5068                 bb->last_ins->next = inst;
5069                 bb->last_ins = inst;
5070         } else {
5071                 bb->last_ins = bb->code = inst;
5072         }
5073 }
5074
5075 void
5076 mono_destroy_compile (MonoCompile *cfg)
5077 {
5078         //mono_mempool_stats (cfg->mempool);
5079         g_hash_table_destroy (cfg->bb_hash);
5080         if (cfg->rs)
5081                 mono_regstate_free (cfg->rs);
5082         mono_mempool_destroy (cfg->mempool);
5083         g_list_free (cfg->ldstr_list);
5084
5085         g_free (cfg->varinfo);
5086         g_free (cfg->vars);
5087         g_free (cfg);
5088 }
5089
5090 gpointer 
5091 mono_get_lmf_addr (void)
5092 {
5093         MonoJitTlsData *jit_tls;        
5094
5095         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
5096                 return &jit_tls->lmf;
5097
5098         g_assert_not_reached ();
5099         return NULL;
5100 }
5101
5102 /**
5103  * mono_thread_abort:
5104  * @obj: exception object
5105  *
5106  * abort the thread, print exception information and stack trace
5107  */
5108 static void
5109 mono_thread_abort (MonoObject *obj)
5110 {
5111         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
5112         
5113         g_free (jit_tls);
5114
5115         ExitThread (-1);
5116 }
5117
5118 static void
5119 mono_thread_start_cb (guint32 tid, gpointer stack_start, gpointer func)
5120 {
5121         MonoJitTlsData *jit_tls;
5122         MonoLMF *lmf;
5123
5124         jit_tls = g_new0 (MonoJitTlsData, 1);
5125
5126         TlsSetValue (mono_jit_tls_id, jit_tls);
5127
5128         jit_tls->abort_func = mono_thread_abort;
5129         jit_tls->end_of_stack = stack_start;
5130
5131         lmf = g_new0 (MonoLMF, 1);
5132         lmf->ebp = -1;
5133
5134         jit_tls->lmf = lmf;
5135 }
5136
5137 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
5138
5139 static void
5140 mono_thread_abort_dummy (MonoObject *obj)
5141 {
5142   if (mono_thread_attach_aborted_cb)
5143     mono_thread_attach_aborted_cb (obj);
5144   else
5145     mono_thread_abort (obj);
5146 }
5147
5148 static void
5149 mono_thread_attach_cb (guint32 tid, gpointer stack_start)
5150 {
5151         MonoJitTlsData *jit_tls;
5152         MonoLMF *lmf;
5153
5154         jit_tls = g_new0 (MonoJitTlsData, 1);
5155
5156         TlsSetValue (mono_jit_tls_id, jit_tls);
5157
5158         jit_tls->abort_func = mono_thread_abort_dummy;
5159         jit_tls->end_of_stack = stack_start;
5160
5161         lmf = g_new0 (MonoLMF, 1);
5162         lmf->ebp = -1;
5163
5164         jit_tls->lmf = lmf;
5165 }
5166
5167 void
5168 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
5169 {
5170         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
5171
5172         ji->ip.i = ip;
5173         ji->type = type;
5174         ji->data.target = target;
5175         ji->next = cfg->patch_info;
5176
5177         cfg->patch_info = ji;
5178 }
5179
5180 void
5181 mono_remove_patch_info (MonoCompile *cfg, int ip)
5182 {
5183         MonoJumpInfo **ji = &cfg->patch_info;
5184
5185         while (*ji) {
5186                 if ((*ji)->ip.i == ip)
5187                         *ji = (*ji)->next;
5188                 else
5189                         ji = &((*ji)->next);
5190         }
5191 }
5192
5193 static void
5194 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
5195         MonoJitICallInfo *info;
5196
5197         switch (mono_burg_arity [tree->opcode]) {
5198         case 0: break;
5199         case 1: 
5200                 dec_foreach (tree->inst_left, cfg);
5201
5202                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
5203                         MonoInst *iargs [2];
5204                 
5205                         iargs [0] = tree->inst_left;
5206
5207                         mono_emulate_opcode (cfg, tree, iargs, info);
5208                         return;
5209                 }
5210
5211                 break;
5212         case 2: 
5213                 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
5214                         MonoInst *iargs [2];
5215                 
5216                         iargs [0] = tree->inst_i0;
5217                         iargs [1] = tree->inst_i1;
5218                 
5219                         mono_emulate_opcode (cfg, tree, iargs, info);
5220
5221                         dec_foreach (iargs [0], cfg);
5222                         dec_foreach (iargs [1], cfg);
5223                         return;
5224                 } else {
5225                         dec_foreach (tree->inst_left, cfg);
5226                         dec_foreach (tree->inst_right, cfg);
5227                 }
5228                 break;
5229         default:
5230                 g_assert_not_reached ();
5231         }
5232         decompose_foreach (tree, cfg);
5233 }
5234
5235 static void
5236 decompose_pass (MonoCompile *cfg) {
5237         MonoBasicBlock *bb;
5238
5239         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5240                 MonoInst *tree;
5241                 cfg->cbb = bb;
5242                 cfg->prev_ins = NULL;
5243                 for (tree = cfg->cbb->code; tree; tree = tree->next) {
5244                         dec_foreach (tree, cfg);
5245                         cfg->prev_ins = tree;
5246                 }
5247         }
5248 }
5249
5250 static void
5251 nullify_basic_block (MonoBasicBlock *bb) 
5252 {
5253         bb->in_count = 0;
5254         bb->out_count = 0;
5255         bb->in_bb = NULL;
5256         bb->out_bb = NULL;
5257         bb->next_bb = NULL;
5258         bb->code = bb->last_ins = NULL;
5259 }
5260
5261 static void 
5262 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig,  MonoBasicBlock *repl)
5263 {
5264         int i, j;
5265
5266         for (i = 0; i < bb->out_count; i++) {
5267                 MonoBasicBlock *ob = bb->out_bb [i];
5268                 for (j = 0; j < ob->in_count; j++) {
5269                         if (ob->in_bb [j] == orig)
5270                                 ob->in_bb [j] = repl;
5271                 }
5272         }
5273
5274 }
5275
5276 static void
5277 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn) 
5278 {
5279         bb->out_count = bbn->out_count;
5280         bb->out_bb = bbn->out_bb;
5281
5282         replace_basic_block (bb, bbn, bb);
5283
5284         if (bb->last_ins) {
5285                 if (bbn->code) {
5286                         bb->last_ins->next = bbn->code;
5287                         bb->last_ins = bbn->last_ins;
5288                 }
5289         } else {
5290                 bb->code = bbn->code;
5291                 bb->last_ins = bbn->last_ins;
5292         }
5293         bb->next_bb = bbn->next_bb;
5294         nullify_basic_block (bbn);
5295 }
5296
5297 static void
5298 optimize_branches (MonoCompile *cfg) {
5299         int changed = FALSE;
5300         MonoBasicBlock *bb, *bbn;
5301
5302         do {
5303                 changed = FALSE;
5304
5305                 /* we skip the entry block (exit is handled specially instead ) */
5306                 for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
5307
5308                         /* dont touch code inside exception clauses */
5309                         if (bb->region != -1)
5310                                 continue;
5311
5312                         if (bb->out_count == 1) {
5313                                 bbn = bb->out_bb [0];
5314
5315                                 if (bb->region == bbn->region && bb->next_bb == bbn) {
5316                                 /* the block are in sequence anyway ... */
5317
5318                                         /* 
5319                                          * miguel: I do not understand what the test below does, could we
5320                                          * use a macro, or a comment here?  opcode > CEE_BEQ && <= BLT_UN
5321                                          *
5322                                          * It could also test for bb->last_in only once, and the value
5323                                          * could be cached (last_ins->opcode)
5324                                          */
5325                                         if (bb->last_ins && (bb->last_ins->opcode == CEE_BR || (
5326                                                 (bb->last_ins && bb->last_ins->opcode >= CEE_BEQ && bb->last_ins->opcode <= CEE_BLT_UN)))) {
5327                                                 bb->last_ins->opcode = CEE_NOP;
5328                                                 changed = TRUE;
5329                                                 if (cfg->verbose_level > 2)
5330                                                         g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
5331                                         }
5332                                         /* fixme: this causes problems with inlining */
5333                                         if (bbn->in_count == 1) {
5334
5335                                                 if (bbn != cfg->bb_exit) {
5336                                                         if (cfg->verbose_level > 2)
5337                                                                 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
5338                                                         merge_basic_blocks (bb, bbn);
5339                                                         changed = TRUE;
5340                                                 }
5341
5342                                                 //mono_print_bb_code (bb);
5343                                         }
5344                                 } else {
5345                                         if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
5346                                                 bbn = bb->last_ins->inst_target_bb;
5347                                                 if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR) {
5348                                                         /*
5349                                                         if (cfg->verbose_level > 2)
5350                                                                 g_print ("in %s branch to branch triggered %d -> %d\n", cfg->method->name, bb->block_num, bbn->block_num);
5351                                                         bb->out_bb [0] = bb->last_ins->inst_target_bb = bbn->code->inst_target_bb;
5352                                                         changed = TRUE;*/
5353                                                 }
5354                                         }
5355                                 }
5356                         } else if (bb->out_count == 2) {
5357                                 /* fixme: this does not correctly unlink the blocks, so we get serious problems in idom code */
5358                                 if (0 && bb->last_ins && bb->last_ins->opcode >= CEE_BEQ && bb->last_ins->opcode <= CEE_BLT_UN) {
5359                                         bbn = bb->last_ins->inst_true_bb;
5360                                         if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR) {
5361                                                 if (cfg->verbose_level > 2)
5362                                                         g_print ("cbranch to branch triggered %d -> %d (0x%02x)\n", bb->block_num, 
5363                                                                  bbn->block_num, bbn->code->opcode);
5364                                                  
5365                                                 if (bb->out_bb [0] == bbn) {
5366                                                         bb->out_bb [0] = bbn->code->inst_target_bb;
5367                                                 } else if (bb->out_bb [1] == bbn) {
5368                                                         bb->out_bb [1] = bbn->code->inst_target_bb;
5369                                                 }
5370                                                 bb->last_ins->inst_true_bb = bbn->code->inst_target_bb;
5371                                                 changed = TRUE;
5372                                         }
5373                                 }
5374                         }
5375                 }
5376         } while (changed);
5377 }
5378
5379 static void
5380 mono_compile_create_vars (MonoCompile *cfg)
5381 {
5382         MonoMethodSignature *sig;
5383         MonoMethodHeader *header;
5384         int i;
5385
5386         header = ((MonoMethodNormal *)cfg->method)->header;
5387
5388         sig = cfg->method->signature;
5389         
5390         if (!MONO_TYPE_IS_VOID (sig->ret)) {
5391                 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
5392                 cfg->ret->opcode = OP_RETARG;
5393                 cfg->ret->inst_vtype = sig->ret;
5394                 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
5395         }
5396
5397         if (sig->hasthis)
5398                 mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
5399
5400         for (i = 0; i < sig->param_count; ++i)
5401                 mono_compile_create_var (cfg, sig->params [i], OP_ARG);
5402
5403         cfg->locals_start = cfg->num_varinfo;
5404
5405         for (i = 0; i < header->num_locals; ++i)
5406                 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
5407 }
5408
5409 #if 0
5410 static void
5411 mono_print_code (MonoCompile *cfg)
5412 {
5413         MonoBasicBlock *bb;
5414         
5415         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5416                 MonoInst *tree = bb->code;      
5417
5418                 if (!tree)
5419                         continue;
5420                 
5421                 g_print ("CODE BLOCK %d (nesting %d):\n", bb->block_num, bb->nesting);
5422
5423                 for (; tree; tree = tree->next) {
5424                         mono_print_tree (tree);
5425                         g_print ("\n");
5426                 }
5427
5428                 if (bb->last_ins)
5429                         bb->last_ins->next = NULL;
5430         }
5431 }
5432 #endif
5433
5434 extern const char * const mono_burg_rule_string [];
5435
5436 static void
5437 emit_state (MonoCompile *cfg, MBState *state, int goal)
5438 {
5439         MBState *kids [10];
5440         int ern = mono_burg_rule (state, goal);
5441         const guint16 *nts = mono_burg_nts [ern];
5442         MBEmitFunc emit;
5443
5444         //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
5445         switch (goal) {
5446         case MB_NTERM_reg:
5447                 //if (state->reg2)
5448                 //      state->reg1 = state->reg2; /* chain rule */
5449                 //else
5450                 state->reg1 = mono_regstate_next_int (cfg->rs);
5451                 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
5452                 break;
5453         case MB_NTERM_lreg:
5454                 state->reg1 = mono_regstate_next_int (cfg->rs);
5455                 state->reg2 = mono_regstate_next_int (cfg->rs);
5456                 break;
5457         case MB_NTERM_freg:
5458                 state->reg1 = mono_regstate_next_float (cfg->rs);
5459                 break;
5460         default:
5461                 /* do nothing */
5462                 break;
5463         }
5464         if (nts [0]) {
5465                 mono_burg_kids (state, ern, kids);
5466
5467                 emit_state (cfg, kids [0], nts [0]);
5468                 if (nts [1]) {
5469                         emit_state (cfg, kids [1], nts [1]);
5470                         if (nts [2]) {
5471                                 g_assert (!nts [3]);
5472                                 emit_state (cfg, kids [2], nts [2]);
5473                         }
5474                 }
5475         }
5476
5477 //      g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
5478         if ((emit = mono_burg_func [ern]))
5479                 emit (state, state->tree, cfg); 
5480 }
5481
5482 #define DEBUG_SELECTION
5483
5484 static void 
5485 mini_select_instructions (MonoCompile *cfg)
5486 {
5487         MonoBasicBlock *bb;
5488         
5489         cfg->state_pool = mono_mempool_new ();
5490         cfg->rs = mono_regstate_new ();
5491
5492 #ifdef DEBUG_SELECTION
5493         if (cfg->verbose_level >= 4) {
5494         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5495                 MonoInst *tree = bb->code;      
5496                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
5497                 if (!tree)
5498                         continue;
5499                 for (; tree; tree = tree->next) {
5500                         mono_print_tree (tree);
5501                         g_print ("\n");
5502                 }
5503         }
5504         }
5505 #endif
5506
5507         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5508                 MonoInst *tree = bb->code, *next;       
5509                 MBState *mbstate;
5510
5511                 if (!tree)
5512                         continue;
5513                 bb->code = NULL;
5514                 bb->last_ins = NULL;
5515                 
5516                 cfg->cbb = bb;
5517                 mono_regstate_reset (cfg->rs);
5518
5519 #ifdef DEBUG_SELECTION
5520                 if (cfg->verbose_level >= 3)
5521                         g_print ("LABEL BLOCK %d:\n", bb->block_num);
5522 #endif
5523                 for (; tree; tree = next) {
5524                         next = tree->next;
5525 #ifdef DEBUG_SELECTION
5526                         if (cfg->verbose_level >= 3) {
5527                                 mono_print_tree (tree);
5528                                 g_print ("\n");
5529                         }
5530 #endif
5531
5532                         if (!(mbstate = mono_burg_label (tree, cfg))) {
5533                                 g_warning ("unabled to label tree %p", tree);
5534                                 mono_print_tree (tree);
5535                                 g_print ("\n");                         
5536                                 g_assert_not_reached ();
5537                         }
5538                         emit_state (cfg, mbstate, MB_NTERM_stmt);
5539                 }
5540                 bb->max_ireg = cfg->rs->next_vireg;
5541                 bb->max_freg = cfg->rs->next_vfreg;
5542
5543                 if (bb->last_ins)
5544                         bb->last_ins->next = NULL;
5545
5546                 mono_mempool_empty (cfg->state_pool); 
5547         }
5548         mono_mempool_destroy (cfg->state_pool); 
5549 }
5550
5551 void
5552 mono_codegen (MonoCompile *cfg)
5553 {
5554         MonoJumpInfo *patch_info;
5555         MonoBasicBlock *bb;
5556         int i, max_epilog_size;
5557         guint8 *code;
5558
5559         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5560                 cfg->spill_count = 0;
5561                 /* we reuse dfn here */
5562                 /* bb->dfn = bb_count++; */
5563                 mono_arch_local_regalloc (cfg, bb);
5564         }
5565
5566         if (mono_trace_coverage)
5567                 mono_allocate_coverage_info (cfg->method, cfg->num_bblocks);
5568
5569         code = mono_arch_emit_prolog (cfg);
5570
5571         if (mono_jit_profile)
5572                 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
5573
5574         cfg->code_len = code - cfg->native_code;
5575         cfg->prolog_end = cfg->code_len;
5576
5577         mono_debug_open_method (cfg);
5578              
5579         /* emit code all basic blocks */
5580         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5581                 bb->native_offset = cfg->code_len;
5582                 mono_arch_output_basic_block (cfg, bb);
5583         }
5584         cfg->bb_exit->native_offset = cfg->code_len;
5585
5586         code = cfg->native_code + cfg->code_len;
5587
5588         max_epilog_size = mono_arch_max_epilog_size (cfg);
5589
5590         /* we always allocate code in cfg->domain->code_mp to increase locality */
5591         cfg->code_size = cfg->code_len + max_epilog_size;
5592         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
5593         code = mono_mempool_alloc (cfg->domain->code_mp, cfg->code_size);
5594         memcpy (code, cfg->native_code, cfg->code_len);
5595         g_free (cfg->native_code);
5596         cfg->native_code = code;
5597         code = cfg->native_code + cfg->code_len;
5598   
5599         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
5600
5601         cfg->epilog_begin = cfg->code_len;
5602
5603         if (mono_jit_profile)
5604                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
5605
5606         cfg->code_len = code - cfg->native_code;
5607
5608         mono_arch_emit_epilog (cfg);
5609
5610         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5611                 switch (patch_info->type) {
5612                 case MONO_PATCH_INFO_ABS: {
5613                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
5614                         if (info) {
5615                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
5616                                 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
5617                                 patch_info->data.name = info->name;
5618                         }
5619                         break;
5620                 }
5621                 case MONO_PATCH_INFO_SWITCH: {
5622                         gpointer *table = g_new (gpointer, patch_info->table_size);
5623                         patch_info->ip.i = patch_info->ip.label->inst_c0;
5624                         for (i = 0; i < patch_info->table_size; i++) {
5625                                 table [i] = (gpointer)patch_info->data.table [i]->native_offset;
5626                         }
5627                         patch_info->data.target = table;
5628                         break;
5629                 }
5630                 default:
5631                         /* do nothing */
5632                         break;
5633                 }
5634         }
5635        
5636         if (cfg->verbose_level > 1)
5637                 g_print ("Method %s::%s emmitted at %p to %p\n", cfg->method->klass->name, 
5638                          cfg->method->name, cfg->native_code, cfg->native_code + cfg->code_len);
5639
5640         mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info);
5641
5642         mono_debug_close_method (cfg);
5643 }
5644
5645 static void
5646 mono_cprop_copy_values (MonoCompile *cfg, MonoInst *tree, MonoInst **acp)
5647 {
5648         MonoInst *cp;
5649         int arity;
5650
5651         if (tree->ssa_op == MONO_SSA_LOAD && (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG) && 
5652             (cp = acp [tree->inst_i0->inst_c0]) && !tree->inst_i0->flags) {
5653
5654                 if (cp->opcode == OP_ICONST) {
5655                         if (cfg->opt & MONO_OPT_CONSPROP) {
5656                                 //{ static int c = 0; printf ("CCOPY %d %d %s\n", c++, cp->inst_c0, mono_method_full_name (cfg->method, TRUE)); }
5657                                 *tree = *cp;
5658                         }
5659                 } else {
5660                         if (tree->inst_i0->inst_vtype->type == cp->inst_vtype->type) {
5661                                 if (cfg->opt & MONO_OPT_COPYPROP) {
5662                                         //{ static int c = 0; printf ("VCOPY %d\n", ++c); }
5663                                         tree->inst_i0 = cp;
5664                                 } 
5665                         }
5666                 } 
5667         } else {
5668                 arity = mono_burg_arity [tree->opcode];
5669
5670                 if (arity) {
5671                         mono_cprop_copy_values (cfg, tree->inst_i0, acp);
5672                         if (cfg->opt & MONO_OPT_CFOLD)
5673                                 mono_constant_fold_inst (tree, NULL); 
5674                         if (arity > 1) {
5675                                 mono_cprop_copy_values (cfg, tree->inst_i1, acp);
5676                                 if (cfg->opt & MONO_OPT_CFOLD)
5677                                         mono_constant_fold_inst (tree, NULL); 
5678                         }
5679                         mono_constant_fold_inst (tree, NULL); 
5680                 }
5681         }
5682 }
5683
5684 static void
5685 mono_cprop_invalidate_values (MonoInst *tree, MonoInst **acp, int acp_size)
5686 {
5687         int arity;
5688
5689         switch (tree->opcode) {
5690         case CEE_STIND_I:
5691         case CEE_STIND_I1:
5692         case CEE_STIND_I2:
5693         case CEE_STIND_I4:
5694         case CEE_STIND_REF:
5695         case CEE_STIND_I8:
5696         case CEE_STIND_R4:
5697         case CEE_STIND_R8:
5698         case CEE_STOBJ:
5699                 if (tree->ssa_op == MONO_SSA_NOP) {
5700                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
5701                         return;
5702                 }
5703
5704                 break;
5705         case CEE_CALL:
5706         case OP_CALL_REG:
5707         case CEE_CALLVIRT:
5708         case OP_LCALL_REG:
5709         case OP_LCALLVIRT:
5710         case OP_LCALL:
5711         case OP_FCALL_REG:
5712         case OP_FCALLVIRT:
5713         case OP_FCALL:
5714         case OP_VCALL_REG:
5715         case OP_VCALLVIRT:
5716         case OP_VCALL:
5717         case OP_VOIDCALL_REG:
5718         case OP_VOIDCALLVIRT:
5719         case OP_VOIDCALL: {
5720                 MonoCallInst *call = (MonoCallInst *)tree;
5721                 MonoMethodSignature *sig = call->signature;
5722                 int i, byref = FALSE;
5723
5724                 for (i = 0; i < sig->param_count; i++) {
5725                         if (sig->params [i]->byref) {
5726                                 byref = TRUE;
5727                                 break;
5728                         }
5729                 }
5730
5731                 if (byref)
5732                         memset (acp, 0, sizeof (MonoInst *) * acp_size);
5733
5734                 return;
5735         }
5736         default:
5737                 break;
5738         }
5739
5740         arity = mono_burg_arity [tree->opcode];
5741
5742         switch (arity) {
5743         case 0:
5744                 break;
5745         case 1:
5746                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
5747                 break;
5748         case 2:
5749                 mono_cprop_invalidate_values (tree->inst_i0, acp, acp_size);
5750                 mono_cprop_invalidate_values (tree->inst_i1, acp, acp_size);
5751                 break;
5752         default:
5753                 g_assert_not_reached ();
5754         }
5755 }
5756
5757 static void
5758 mono_local_cprop_bb (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **acp, int acp_size)
5759 {
5760         MonoInst *tree = bb->code;      
5761         int i;
5762
5763         if (!tree)
5764                 return;
5765
5766         for (; tree; tree = tree->next) {
5767
5768                 mono_cprop_copy_values (cfg, tree, acp);
5769
5770                 mono_cprop_invalidate_values (tree, acp, acp_size);
5771
5772                 if (tree->ssa_op == MONO_SSA_STORE  && 
5773                     (tree->inst_i0->opcode == OP_LOCAL || tree->inst_i0->opcode == OP_ARG)) {
5774                         MonoInst *i1 = tree->inst_i1;
5775
5776                         acp [tree->inst_i0->inst_c0] = NULL;
5777
5778                         for (i = 0; i < acp_size; i++) {
5779                                 if (acp [i] && acp [i]->opcode != OP_ICONST && 
5780                                     acp [i]->inst_c0 == tree->inst_i0->inst_c0) {
5781                                         acp [i] = NULL;
5782                                 }
5783                         }
5784
5785                         if (i1->opcode == OP_ICONST) {
5786                                 acp [tree->inst_i0->inst_c0] = i1;
5787                                 //printf ("DEF1 BB%d %d\n", bb->block_num,tree->inst_i0->inst_c0);
5788                         }
5789                         if (i1->ssa_op == MONO_SSA_LOAD && 
5790                             (i1->inst_i0->opcode == OP_LOCAL || i1->inst_i0->opcode == OP_ARG) &&
5791                             (i1->inst_i0->inst_c0 != tree->inst_i0->inst_c0)) {
5792                                 acp [tree->inst_i0->inst_c0] = i1->inst_i0;
5793                                 //printf ("DEF2 BB%d %d %d\n", bb->block_num,tree->inst_i0->inst_c0,i1->inst_i0->inst_c0);
5794                         }
5795                 }
5796
5797                 /*
5798                   if (tree->opcode == CEE_BEQ) {
5799                   g_assert (tree->inst_i0->opcode == OP_COMPARE);
5800                   if (tree->inst_i0->inst_i0->opcode == OP_ICONST &&
5801                   tree->inst_i0->inst_i1->opcode == OP_ICONST) {
5802                   
5803                   tree->opcode = CEE_BR;
5804                   if (tree->inst_i0->inst_i0->opcode == tree->inst_i0->inst_i1->opcode) {
5805                   tree->inst_target_bb = tree->inst_true_bb;
5806                   } else {
5807                   tree->inst_target_bb = tree->inst_false_bb;
5808                   }
5809                   }
5810                   }
5811                 */
5812         }
5813 }
5814
5815 static void
5816 mono_local_cprop (MonoCompile *cfg)
5817 {
5818         MonoBasicBlock *bb;
5819         MonoInst **acp;
5820
5821         acp = alloca (sizeof (MonoInst *) * cfg->num_varinfo);
5822
5823         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
5824                 memset (acp, 0, sizeof (MonoInst *) * cfg->num_varinfo);
5825                 mono_local_cprop_bb (cfg, bb, acp, cfg->num_varinfo);
5826         }
5827 }
5828
5829 MonoCompile*
5830 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, int parts)
5831 {
5832         MonoMethodHeader *header = ((MonoMethodNormal *)method)->header;
5833         guint8 *ip = (guint8 *)header->code;
5834         MonoCompile *cfg;
5835         MonoJitInfo *jinfo;
5836         int dfn = 0, i, code_size_ratio;
5837
5838         mono_jit_stats.methods_compiled++;
5839         if (mono_jit_profile)
5840                 mono_profiler_method_jit (method);
5841
5842         cfg = g_new0 (MonoCompile, 1);
5843         cfg->method = method;
5844         cfg->mempool = mono_mempool_new ();
5845         cfg->opt = opts;
5846         cfg->bb_hash = g_hash_table_new (g_direct_hash, NULL);
5847         cfg->domain = domain;
5848         cfg->verbose_level = mini_verbose;
5849         cfg->intvars = mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * 
5850                                             ((MonoMethodNormal *)method)->header->max_stack);
5851
5852         /*
5853          * create MonoInst* which represents arguments and local variables
5854          */
5855         mono_compile_create_vars (cfg);
5856
5857         if (cfg->verbose_level > 2)
5858                 g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
5859
5860         if ((i = mono_method_to_ir (cfg, method, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
5861                 mono_destroy_compile (cfg);
5862                 if (mono_jit_profile)
5863                         mono_profiler_method_end_jit (method, MONO_PROFILE_FAILED);
5864                 return NULL;
5865         }
5866
5867         mono_jit_stats.basic_blocks += cfg->num_bblocks;
5868         mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
5869
5870         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
5871
5872         /* Depth-first ordering on basic blocks */
5873         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
5874
5875         if (cfg->opt & MONO_OPT_BRANCH)
5876                 optimize_branches (cfg);
5877
5878         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
5879         if (cfg->num_bblocks != dfn + 1) {
5880                 if (cfg->verbose_level > 1)
5881                         g_print ("unreachable code?\n");
5882                 cfg->num_bblocks = dfn + 1;
5883         }
5884
5885         if (cfg->opt & MONO_OPT_LOOP) {
5886                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
5887                 mono_compute_natural_loops (cfg);
5888         }
5889
5890
5891         /* after method_to_ir */
5892         if (parts == 1)
5893                 return cfg;
5894
5895 //#define DEBUGSSA "logic_run"
5896 #define DEBUGSSA_CLASS "Tests"
5897 #ifdef DEBUGSSA
5898
5899
5900         if (!header->num_clauses && !cfg->disable_ssa) {
5901                 mono_local_cprop (cfg);
5902                 mono_ssa_compute (cfg);
5903         }
5904 #else 
5905
5906         /* fixme: add all optimizations which requires SSA */
5907         if (cfg->opt & (MONO_OPT_DEADCE)) {
5908                 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
5909                         mono_local_cprop (cfg);
5910                         mono_ssa_compute (cfg);
5911
5912                         if (cfg->verbose_level >= 2) {
5913                                 print_dfn (cfg);
5914                         }
5915                 }
5916         }
5917 #endif
5918
5919         /* after SSA translation */
5920         if (parts == 2)
5921                 return cfg;
5922
5923         if ((cfg->opt & MONO_OPT_CONSPROP) ||  (cfg->opt & MONO_OPT_COPYPROP)) {
5924                 if (cfg->comp_done & MONO_COMP_SSA) {
5925                         mono_ssa_cprop (cfg);
5926                 } else {
5927                         mono_local_cprop (cfg);
5928                 }
5929         }
5930
5931         if (cfg->comp_done & MONO_COMP_SSA) {                   
5932                 mono_ssa_deadce (cfg);
5933
5934                 //mono_ssa_strength_reduction (cfg);
5935
5936                 mono_ssa_remove (cfg);
5937
5938                 if (cfg->opt & MONO_OPT_BRANCH)
5939                         optimize_branches (cfg);
5940         }
5941
5942         /* after SSA removal */
5943         if (parts == 3)
5944                 return cfg;
5945         
5946         decompose_pass (cfg);
5947
5948         /* FIXME: disabled with exception clauses: bug #42136 */
5949         if ((!header->num_clauses) && (cfg->opt & MONO_OPT_LINEARS)) {
5950                 GList *vars, *regs;
5951
5952                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
5953                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
5954                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
5955                         mono_analyze_liveness (cfg);
5956
5957                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
5958                         regs = mono_arch_get_global_int_regs (cfg);
5959                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
5960                 }
5961         }
5962
5963         //mono_print_code (cfg);
5964         
5965         //print_dfn (cfg);
5966
5967         /* variables are allocated after decompose, since decompose could create temps */
5968         mono_arch_allocate_vars (cfg);
5969
5970         if (cfg->opt & MONO_OPT_CFOLD)
5971                 mono_constant_fold (cfg);
5972
5973         mini_select_instructions (cfg);
5974
5975         mono_codegen (cfg);
5976         if (cfg->verbose_level >= 2) {
5977                 char *id =  mono_method_full_name (cfg->method, FALSE);
5978                 mono_disassemble_code (cfg->native_code, cfg->code_len, id + 3);
5979                 g_free (id);
5980         }
5981         
5982         jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo));
5983
5984         jinfo = g_new0 (MonoJitInfo, 1);
5985         jinfo->method = method;
5986         jinfo->code_start = cfg->native_code;
5987         jinfo->code_size = cfg->code_len;
5988         jinfo->used_regs = cfg->used_int_regs;
5989
5990         if (header->num_clauses) {
5991                 int i;
5992
5993                 jinfo->exvar_offset = cfg->exvar? cfg->exvar->inst_offset: 0;
5994                 jinfo->num_clauses = header->num_clauses;
5995                 jinfo->clauses = mono_mempool_alloc0 (cfg->domain->mp, 
5996                         sizeof (MonoJitExceptionInfo) * header->num_clauses);
5997
5998                 for (i = 0; i < header->num_clauses; i++) {
5999                         MonoExceptionClause *ec = &header->clauses [i];
6000                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
6001                         MonoBasicBlock *tblock;
6002
6003                         ei->flags = ec->flags;
6004
6005                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
6006                                 tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->token_or_filter);
6007                                 g_assert (tblock);
6008                                 ei->data.filter = cfg->native_code + tblock->native_offset;
6009                         } else {
6010                                 ei->data.token = ec->token_or_filter;
6011                         }
6012
6013                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset);
6014                         g_assert (tblock);
6015                         ei->try_start = cfg->native_code + tblock->native_offset;
6016                         g_assert (tblock->native_offset);
6017                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset + ec->try_len);
6018                         g_assert (tblock);
6019                         ei->try_end = cfg->native_code + tblock->native_offset;
6020                         g_assert (tblock->native_offset);
6021                         tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->handler_offset);
6022                         g_assert (tblock);
6023                         ei->handler_start = cfg->native_code + tblock->native_offset;
6024                 }
6025         }
6026
6027         mono_jit_info_table_add (cfg->domain, jinfo);
6028
6029         /* collect statistics */
6030         mono_jit_stats.allocated_code_size += cfg->code_len;
6031         code_size_ratio = cfg->code_len;
6032         if (code_size_ratio > mono_jit_stats.biggest_method_size) {
6033                         mono_jit_stats.biggest_method_size = code_size_ratio;
6034                         mono_jit_stats.biggest_method = method;
6035         }
6036         code_size_ratio = (code_size_ratio * 100) / ((MonoMethodNormal *)method)->header->code_size;
6037         if (code_size_ratio > mono_jit_stats.max_code_size_ratio) {
6038                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
6039                 mono_jit_stats.max_ratio_method = method;
6040         }
6041         mono_jit_stats.native_code_size += cfg->code_len;
6042
6043         if (mono_jit_profile)
6044                 mono_profiler_method_end_jit (method, MONO_PROFILE_OK);
6045
6046         return cfg;
6047 }
6048
6049 static gpointer
6050 mono_jit_compile_method (MonoMethod *method)
6051 {
6052         /* FIXME: later copy the code from mono */
6053         MonoDomain *target_domain, *domain = mono_domain_get ();
6054         MonoCompile *cfg;
6055         GHashTable *jit_code_hash;
6056         gpointer code;
6057
6058         if (default_opt & MONO_OPT_SHARED)
6059                 target_domain = mono_root_domain;
6060         else 
6061                 target_domain = domain;
6062
6063         jit_code_hash = target_domain->jit_code_hash;
6064
6065         if ((code = g_hash_table_lookup (jit_code_hash, method))) {
6066                 mono_jit_stats.methods_lookups++;
6067                 return code;
6068         }
6069
6070 #ifdef MONO_USE_AOT_COMPILER
6071         if (!mono_compile_aot) {
6072                 mono_class_init (method->klass);
6073                 if ((code = mono_aot_get_method (method))) {
6074                         g_hash_table_insert (jit_code_hash, method, code);
6075                         return code;
6076                 }
6077         }
6078 #endif
6079
6080         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
6081             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
6082                 if (!method->info) {
6083                         MonoMethod *nm;
6084
6085                         if (!method->addr && (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
6086                                 mono_lookup_pinvoke_call (method);
6087 #ifdef MONO_USE_EXC_TABLES
6088                         if (mono_method_blittable (method)) {
6089                                 method->info = method->addr;
6090                         } else {
6091 #endif
6092                                 nm = mono_marshal_get_native_wrapper (method);
6093                                 method->info = mono_compile_method (nm);
6094
6095                                 //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE) 
6096                                 //mono_debug_add_wrapper (method, nm);
6097 #ifdef MONO_USE_EXC_TABLES
6098                         }
6099 #endif
6100                 }
6101                 return method->info;
6102         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
6103                 const char *name = method->name;
6104                 MonoMethod *nm;
6105
6106                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
6107                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
6108                                 /* FIXME: uhm, we need a wrapper to handle exceptions? */
6109                                 return (gpointer)mono_delegate_ctor;
6110                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
6111                                 nm = mono_marshal_get_delegate_invoke (method);
6112                                 return mono_jit_compile_method (nm);
6113                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
6114                                 nm = mono_marshal_get_delegate_begin_invoke (method);
6115                                 return mono_jit_compile_method (nm);
6116                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
6117                                 nm = mono_marshal_get_delegate_end_invoke (method);
6118                                 return mono_jit_compile_method (nm);
6119                         }
6120                 }
6121                 return NULL;
6122         }
6123
6124         cfg = mini_method_compile (method, default_opt, target_domain, 0);
6125         code = cfg->native_code;
6126         mono_destroy_compile (cfg);
6127
6128         g_hash_table_insert (jit_code_hash, method, code);
6129
6130         /* make sure runtime_init is called */
6131         mono_class_vtable (target_domain, method->klass);
6132
6133         return code;
6134 }
6135
6136 /**
6137  * mono_jit_runtime_invoke:
6138  * @method: the method to invoke
6139  * @obj: this pointer
6140  * @params: array of parameter values.
6141  * @exc: used to catch exceptions objects
6142  */
6143 static MonoObject*
6144 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
6145 {
6146         MonoMethod *invoke;
6147         MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc);
6148         invoke = mono_marshal_get_runtime_invoke (method);
6149         runtime_invoke = mono_jit_compile_method (invoke);      
6150         return runtime_invoke (obj, params, exc);
6151 }
6152
6153 #ifdef PLATFORM_WIN32
6154 #define GET_CONTEXT \
6155         struct sigcontext *ctx = (struct sigcontext*)_dummy;
6156 #else
6157 #define GET_CONTEXT \
6158         void **_p = (void **)&_dummy; \
6159         struct sigcontext *ctx = (struct sigcontext *)++_p;
6160 #endif
6161
6162 static void
6163 sigfpe_signal_handler (int _dummy)
6164 {
6165         MonoException *exc;
6166         GET_CONTEXT
6167
6168         exc = mono_get_exception_divide_by_zero ();
6169         
6170         mono_arch_handle_exception (ctx, exc, FALSE);
6171 }
6172
6173 static void
6174 sigill_signal_handler (int _dummy)
6175 {
6176         MonoException *exc;
6177         GET_CONTEXT
6178         exc = mono_get_exception_execution_engine ("SIGILL");
6179         
6180         mono_arch_handle_exception (ctx, exc, FALSE);
6181 }
6182
6183 static void
6184 sigsegv_signal_handler (int _dummy)
6185 {
6186         MonoException *exc;
6187         GET_CONTEXT
6188
6189         exc = mono_get_exception_null_reference ();
6190         
6191         mono_arch_handle_exception (ctx, exc, FALSE);
6192 }
6193
6194 static void
6195 sigusr1_signal_handler (int _dummy)
6196 {
6197         MonoThread *thread;
6198         GET_CONTEXT
6199         
6200         thread = mono_thread_current ();
6201         
6202         g_assert (thread->abort_exc);
6203
6204         mono_arch_handle_exception (ctx, thread->abort_exc, FALSE);
6205 }
6206
6207 static void
6208 mono_runtime_install_handlers (void)
6209 {
6210 #ifndef PLATFORM_WIN32
6211         struct sigaction sa;
6212 #endif
6213
6214 #ifdef PLATFORM_WIN32
6215         win32_seh_init();
6216         win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
6217         win32_seh_set_handler(SIGILL, sigill_signal_handler);
6218         win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
6219 #else /* !PLATFORM_WIN32 */
6220
6221         /* libpthreads has its own implementation of sigaction(),
6222          * but it seems to work well with our current exception
6223          * handlers. If not we must call syscall directly instead 
6224          * of sigaction */
6225         
6226         /* catch SIGFPE */
6227         sa.sa_handler = sigfpe_signal_handler;
6228         sigemptyset (&sa.sa_mask);
6229         sa.sa_flags = 0;
6230         //g_assert (syscall (SYS_sigaction, SIGFPE, &sa, NULL) != -1);
6231         g_assert (sigaction (SIGFPE, &sa, NULL) != -1);
6232
6233         /* catch SIGILL */
6234         sa.sa_handler = sigill_signal_handler;
6235         sigemptyset (&sa.sa_mask);
6236         sa.sa_flags = 0;
6237         //g_assert (syscall (SYS_sigaction, SIGILL, &sa, NULL) != -1);
6238         g_assert (sigaction (SIGILL, &sa, NULL) != -1);
6239
6240         /* catch thread abort signal */
6241         sa.sa_handler = sigusr1_signal_handler;
6242         sigemptyset (&sa.sa_mask);
6243         sa.sa_flags = 0;
6244         //g_assert (syscall (SYS_sigaction, SIGILL, &sa, NULL) != -1);
6245         g_assert (sigaction (mono_thread_get_abort_signal (), &sa, NULL) != -1);
6246
6247 #if 1
6248         /* catch SIGSEGV */
6249         sa.sa_handler = sigsegv_signal_handler;
6250         sigemptyset (&sa.sa_mask);
6251         sa.sa_flags = 0;
6252         //g_assert (syscall (SYS_sigaction, SIGSEGV, &sa, NULL) != -1);
6253         g_assert (sigaction (SIGSEGV, &sa, NULL) != -1);
6254 #endif
6255 #endif /* PLATFORM_WIN32 */
6256 }
6257
6258 /* mono_jit_create_remoting_trampoline:
6259  * @method: pointer to the method info
6260  *
6261  * Creates a trampoline which calls the remoting functions. This
6262  * is used in the vtable of transparent proxies.
6263  * 
6264  * Returns: a pointer to the newly created code 
6265  */
6266 static gpointer
6267 mono_jit_create_remoting_trampoline (MonoMethod *method)
6268 {
6269         MonoMethod *nm;
6270         guint8 *addr = NULL;
6271
6272         if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || 
6273             (method->signature->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
6274                 nm = mono_marshal_get_remoting_invoke (method);
6275                 addr = mono_compile_method (nm);
6276         } else {
6277                 addr = mono_compile_method (method);
6278         }
6279         return addr;
6280 }
6281
6282 static CRITICAL_SECTION ms;
6283
6284 MonoDomain *
6285 mini_init (const char *filename)
6286 {
6287         MonoDomain *domain;
6288         
6289         metadata_section = &ms;
6290         InitializeCriticalSection (metadata_section);
6291
6292         mono_jit_tls_id = TlsAlloc ();
6293         mono_thread_start_cb (GetCurrentThreadId (), (gpointer)-1, NULL);
6294
6295         mono_burg_init ();
6296
6297         mono_runtime_install_handlers ();
6298
6299         mono_install_compile_method (mono_jit_compile_method);
6300         mono_install_trampoline (mono_arch_create_jit_trampoline);
6301         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
6302         mono_install_runtime_invoke (mono_jit_runtime_invoke);
6303         mono_install_handler (mono_arch_get_throw_exception ());
6304         mono_install_stack_walk (mono_jit_walk_stack);
6305         mono_install_get_config_dir ();
6306
6307         domain = mono_init (filename);
6308         mono_init_icall ();
6309
6310         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info", 
6311                                 ves_icall_get_frame_info);
6312         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace", 
6313                                 ves_icall_get_trace);
6314         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers", 
6315                                 mono_runtime_install_handlers);
6316
6317
6318         create_helper_signature ();
6319
6320         mono_arch_register_lowlevel_calls ();
6321         mono_register_jit_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
6322         mono_register_jit_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
6323
6324         mono_register_jit_icall (mono_get_lmf_addr, "mono_get_lmf_addr", helper_sig_ptr_void, TRUE);
6325         mono_register_jit_icall (mono_domain_get, "mono_domain_get", helper_sig_domain_get, TRUE);
6326
6327         /* fixme: we cant hanlde vararg methods this way, because the signature is not constant */
6328         //mono_register_jit_icall (ves_array_element_address, "ves_array_element_address", NULL);
6329         //mono_register_jit_icall (mono_array_new_va, "mono_array_new_va", NULL);
6330
6331         mono_register_jit_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", helper_sig_void_obj, TRUE);
6332         mono_register_jit_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", 
6333                                  helper_sig_void_ptr, TRUE);
6334
6335         /* 
6336          * NOTE, NOTE, NOTE, NOTE:
6337          * when adding emulation for some opcodes, remember to also add a dummy
6338          * rule to the burg files, because we need the arity information to be correct.
6339          */
6340         mono_register_opcode_emulation (OP_LMUL, helper_sig_long_long_long, mono_llmult);
6341         mono_register_opcode_emulation (OP_LMUL_OVF_UN, helper_sig_long_long_long, mono_llmult_ovf_un);
6342         mono_register_opcode_emulation (OP_LMUL_OVF, helper_sig_long_long_long, mono_llmult_ovf);
6343         mono_register_opcode_emulation (OP_LDIV, helper_sig_long_long_long, mono_lldiv);
6344         mono_register_opcode_emulation (OP_LDIV_UN, helper_sig_long_long_long, mono_lldiv_un);
6345         mono_register_opcode_emulation (OP_LREM, helper_sig_long_long_long, mono_llrem);
6346         mono_register_opcode_emulation (OP_LREM_UN, helper_sig_long_long_long, mono_llrem_un);
6347
6348         mono_register_opcode_emulation (OP_LSHL, helper_sig_long_long_int, mono_lshl);
6349         mono_register_opcode_emulation (OP_LSHR, helper_sig_long_long_int, mono_lshr);
6350         mono_register_opcode_emulation (OP_LSHR_UN, helper_sig_long_long_int, mono_lshr_un);
6351
6352         mono_register_opcode_emulation (OP_FCONV_TO_U8, helper_sig_ulong_double, mono_fconv_u8);
6353         mono_register_opcode_emulation (OP_FCONV_TO_U4, helper_sig_uint_double, mono_fconv_u4);
6354         mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, helper_sig_long_double, mono_fconv_ovf_i8);
6355         mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, helper_sig_ulong_double, mono_fconv_ovf_u8);
6356
6357 #if SIZEOF_VOID_P == 4
6358         mono_register_opcode_emulation (OP_FCONV_TO_U, helper_sig_uint_double, mono_fconv_u4);
6359 #else
6360 #warning "fixme: add opcode emulation"
6361 #endif
6362
6363         /* other jit icalls */
6364         mono_register_jit_icall (mono_class_static_field_address , "mono_class_static_field_address", 
6365                                  helper_sig_ptr_ptr_ptr, FALSE);
6366         mono_register_jit_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", helper_sig_ptr_ptr_ptr, FALSE);
6367         mono_register_jit_icall (mono_threads_get_static_data, "mono_threads_get_static_data", helper_sig_ptr_int, FALSE);
6368         mono_register_jit_icall (mono_ldstr, "mono_ldstr", helper_sig_ldstr, FALSE);
6369         mono_register_jit_icall (helper_memcpy, "helper_memcpy", helper_sig_memcpy, FALSE);
6370         mono_register_jit_icall (helper_memset, "helper_memset", helper_sig_memset, FALSE);
6371         mono_register_jit_icall (helper_initobj, "helper_initobj", helper_sig_initobj, FALSE);
6372         mono_register_jit_icall (helper_stelem_ref, "helper_stelem_ref", helper_sig_stelem_ref, FALSE);
6373         mono_register_jit_icall (mono_object_new, "mono_object_new", helper_sig_object_new, FALSE);
6374         mono_register_jit_icall (mono_object_new_specific, "mono_object_new_specific", helper_sig_object_new_specific, FALSE);
6375         mono_register_jit_icall (mono_array_new, "mono_array_new", helper_sig_newarr, FALSE);
6376         mono_register_jit_icall (mono_array_new_specific, "mono_array_new_specific", helper_sig_newarr_specific, FALSE);
6377         mono_register_jit_icall (mono_string_to_utf16, "mono_string_to_utf16", helper_sig_ptr_obj, FALSE);
6378         mono_register_jit_icall (mono_string_from_utf16, "mono_string_from_utf16", helper_sig_obj_ptr, FALSE);
6379         mono_register_jit_icall (mono_string_new_wrapper, "mono_string_new_wrapper", helper_sig_obj_ptr, FALSE);
6380         mono_register_jit_icall (mono_string_to_utf8, "mono_string_to_utf8", helper_sig_ptr_obj, FALSE);
6381         mono_register_jit_icall (mono_string_to_bstr, "mono_string_to_bstr", helper_sig_ptr_obj, FALSE);
6382         mono_register_jit_icall (mono_string_to_ansibstr, "mono_string_to_ansibstr", helper_sig_ptr_obj, FALSE);
6383         mono_register_jit_icall (mono_string_builder_to_utf8, "mono_string_builder_to_utf8", helper_sig_ptr_obj, FALSE);
6384         mono_register_jit_icall (mono_array_to_savearray, "mono_array_to_savearray", helper_sig_ptr_obj, FALSE);
6385         mono_register_jit_icall (mono_array_to_lparray, "mono_array_to_lparray", helper_sig_ptr_obj, FALSE);
6386         mono_register_jit_icall (mono_delegate_to_ftnptr, "mono_delegate_to_ftnptr", helper_sig_ptr_obj, FALSE);
6387         mono_register_jit_icall (mono_marshal_string_array, "mono_marshal_string_array", helper_sig_ptr_obj, FALSE);
6388         mono_register_jit_icall (mono_string_utf8_to_builder, "mono_string_utf8_to_builder", helper_sig_void_ptr_ptr, FALSE);
6389         mono_register_jit_icall (mono_marshal_free_array, "mono_marshal_free_array", helper_sig_void_ptr_ptr, FALSE);
6390         mono_register_jit_icall (mono_string_to_byvalstr, "mono_string_to_byvalstr", helper_sig_void_ptr_ptr_ptr, FALSE);
6391         mono_register_jit_icall (mono_string_to_byvalwstr, "mono_string_to_byvalwstr", helper_sig_void_ptr_ptr_ptr, FALSE);
6392         mono_register_jit_icall (g_free, "g_free", helper_sig_void_ptr, FALSE);
6393         mono_register_jit_icall (mono_ldftn, "mono_ldftn", helper_sig_compile, FALSE);
6394         mono_register_jit_icall (mono_ldvirtfn, "mono_ldvirtfn", helper_sig_compile_virt, FALSE);
6395
6396         mono_runtime_init (domain, mono_thread_start_cb,
6397                            mono_thread_attach_cb);
6398
6399         //mono_thread_attach (domain);
6400         return domain;
6401 }
6402
6403 MonoJitStats mono_jit_stats = {0};
6404
6405 static void 
6406 print_jit_stats (void)
6407 {
6408         if (mono_jit_stats.enabled) {
6409                 g_print ("Mono Jit statistics\n");
6410                 g_print ("Compiled methods:       %ld\n", mono_jit_stats.methods_compiled);
6411                 g_print ("Methods from AOT:       %ld\n", mono_jit_stats.methods_aot);
6412                 g_print ("Methods cache lookup:   %ld\n", mono_jit_stats.methods_lookups);
6413                 g_print ("Method trampolines:     %ld\n", mono_jit_stats.method_trampolines);
6414                 g_print ("Basic blocks:           %ld\n", mono_jit_stats.basic_blocks);
6415                 g_print ("Max basic blocks:       %ld\n", mono_jit_stats.max_basic_blocks);
6416                 g_print ("Allocated vars:         %ld\n", mono_jit_stats.allocate_var);
6417                 g_print ("Analyze stack repeat:   %ld\n", mono_jit_stats.analyze_stack_repeat);
6418                 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
6419                 g_print ("Native code size:       %ld\n", mono_jit_stats.native_code_size);
6420                 g_print ("Max code size ratio:    %.2f (%s::%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
6421                                 mono_jit_stats.max_ratio_method->klass->name, mono_jit_stats.max_ratio_method->name);
6422                 g_print ("Biggest method:         %ld (%s::%s)\n", mono_jit_stats.biggest_method_size,
6423                                 mono_jit_stats.biggest_method->klass->name, mono_jit_stats.biggest_method->name);
6424                 g_print ("Code reallocs:          %ld\n", mono_jit_stats.code_reallocs);
6425                 g_print ("Allocated code size:    %ld\n", mono_jit_stats.allocated_code_size);
6426                 g_print ("Inlineable methods:     %ld\n", mono_jit_stats.inlineable_methods);
6427                 g_print ("Inlined methods:        %ld\n", mono_jit_stats.inlined_methods);
6428                 
6429                 g_print ("\nCreated object count:   %ld\n", mono_stats.new_object_count);
6430                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
6431                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
6432                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
6433                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
6434         }
6435 }
6436
6437 void
6438 mini_cleanup (MonoDomain *domain)
6439 {
6440         /* 
6441          * mono_runtime_cleanup() and mono_domain_finalize () need to
6442          * be called early since they need the execution engine still
6443          * fully working (mono_domain_finalize may invoke managed finalizers
6444          * and mono_runtime_cleanup will wait for other threads to finish).
6445          */
6446         mono_domain_finalize (domain);
6447
6448         mono_runtime_cleanup (domain);
6449
6450         mono_profiler_shutdown ();
6451
6452         mono_debug_cleanup ();
6453 #ifdef PLATFORM_WIN32
6454         win32_seh_cleanup();
6455 #endif
6456
6457         mono_domain_unload (domain, TRUE);
6458
6459         print_jit_stats ();
6460         DeleteCriticalSection (metadata_section);
6461 }
6462
6463 void
6464 mono_set_defaults (int verbose_level, guint32 opts)
6465 {
6466         mini_verbose = verbose_level;
6467         default_opt = opts;
6468 }
6469