[runtime] Fix test_op_il_seq_point in amd64.
[mono.git] / mono / mini / mini.c
1 /*
2  * mini.c: The new Mono code generator.
3  *
4  * Authors:
5  *   Paolo Molaro (lupus@ximian.com)
6  *   Dietmar Maurer (dietmar@ximian.com)
7  *
8  * Copyright 2002-2003 Ximian, Inc.
9  * Copyright 2003-2010 Novell, Inc.
10  * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
11  */
12
13 #include <config.h>
14 #ifdef HAVE_ALLOCA_H
15 #include <alloca.h>
16 #endif
17 #ifdef HAVE_UNISTD_H
18 #include <unistd.h>
19 #endif
20 #include <math.h>
21 #ifdef HAVE_SYS_TIME_H
22 #include <sys/time.h>
23 #endif
24
25 #include <mono/utils/memcheck.h>
26
27 #include <mono/metadata/assembly.h>
28 #include <mono/metadata/loader.h>
29 #include <mono/metadata/tabledefs.h>
30 #include <mono/metadata/class.h>
31 #include <mono/metadata/object.h>
32 #include <mono/metadata/tokentype.h>
33 #include <mono/metadata/tabledefs.h>
34 #include <mono/metadata/threads.h>
35 #include <mono/metadata/appdomain.h>
36 #include <mono/metadata/debug-helpers.h>
37 #include "mono/metadata/profiler.h"
38 #include <mono/metadata/profiler-private.h>
39 #include <mono/metadata/mono-config.h>
40 #include <mono/metadata/environment.h>
41 #include <mono/metadata/mono-debug.h>
42 #include <mono/metadata/gc-internal.h>
43 #include <mono/metadata/threads-types.h>
44 #include <mono/metadata/verify.h>
45 #include <mono/metadata/verify-internals.h>
46 #include <mono/metadata/mempool-internals.h>
47 #include <mono/metadata/attach.h>
48 #include <mono/metadata/runtime.h>
49 #include <mono/utils/mono-math.h>
50 #include <mono/utils/mono-compiler.h>
51 #include <mono/utils/mono-counters.h>
52 #include <mono/utils/mono-error-internals.h>
53 #include <mono/utils/mono-logger-internal.h>
54 #include <mono/utils/mono-mmap.h>
55 #include <mono/utils/mono-path.h>
56 #include <mono/utils/mono-tls.h>
57 #include <mono/utils/mono-hwcap.h>
58 #include <mono/utils/dtrace.h>
59 #include <mono/utils/mono-threads.h>
60 #include <mono/io-layer/io-layer.h>
61
62 #include "mini.h"
63 #include "seq-points.h"
64 #include "tasklets.h"
65 #include <string.h>
66 #include <ctype.h>
67 #include "trace.h"
68 #include "version.h"
69 #include "ir-emit.h"
70
71 #include "jit-icalls.h"
72
73 #include "mini-gc.h"
74 #include "debugger-agent.h"
75
76 MonoTraceSpec *mono_jit_trace_calls;
77 MonoMethodDesc *mono_inject_async_exc_method;
78 int mono_inject_async_exc_pos;
79 MonoMethodDesc *mono_break_at_bb_method;
80 int mono_break_at_bb_bb_num;
81 gboolean mono_do_x86_stack_align = TRUE;
82 gboolean mono_using_xdebug;
83
84 #define mono_jit_lock() mono_mutex_lock (&jit_mutex)
85 #define mono_jit_unlock() mono_mutex_unlock (&jit_mutex)
86 static mono_mutex_t jit_mutex;
87
88 gpointer
89 mono_realloc_native_code (MonoCompile *cfg)
90 {
91 #if defined(__default_codegen__)
92         return g_realloc (cfg->native_code, cfg->code_size);
93 #elif defined(__native_client_codegen__)
94         guint old_padding;
95         gpointer native_code;
96         guint alignment_check;
97
98         /* Save the old alignment offset so we can re-align after the realloc. */
99         old_padding = (guint)(cfg->native_code - cfg->native_code_alloc);
100         cfg->code_size = NACL_BUNDLE_ALIGN_UP (cfg->code_size);
101
102         cfg->native_code_alloc = g_realloc ( cfg->native_code_alloc,
103                                                                                  cfg->code_size + kNaClAlignment );
104
105         /* Align native_code to next nearest kNaClAlignment byte. */
106         native_code = (guint)cfg->native_code_alloc + kNaClAlignment;
107         native_code = (guint)native_code & ~kNaClAlignmentMask;
108
109         /* Shift the data to be 32-byte aligned again. */
110         memmove (native_code, cfg->native_code_alloc + old_padding, cfg->code_size);
111
112         alignment_check = (guint)native_code & kNaClAlignmentMask;
113         g_assert (alignment_check == 0);
114         return native_code;
115 #else
116         g_assert_not_reached ();
117         return cfg->native_code;
118 #endif
119 }
120
121 #ifdef __native_client_codegen__
122
123 /* Prevent instructions from straddling a 32-byte alignment boundary.   */
124 /* Instructions longer than 32 bytes must be aligned internally.        */
125 /* IN: pcode, instlen                                                   */
126 /* OUT: pcode                                                           */
127 void mono_nacl_align_inst(guint8 **pcode, int instlen) {
128   int space_in_block;
129
130   space_in_block = kNaClAlignment - ((uintptr_t)(*pcode) & kNaClAlignmentMask);
131
132   if (G_UNLIKELY (instlen >= kNaClAlignment)) {
133     g_assert_not_reached();
134   } else if (instlen > space_in_block) {
135     *pcode = mono_arch_nacl_pad(*pcode, space_in_block);
136   }
137 }
138
139 /* Move emitted call sequence to the end of a kNaClAlignment-byte block.  */
140 /* IN: start    pointer to start of call sequence                         */
141 /* IN: pcode    pointer to end of call sequence (current "IP")            */
142 /* OUT: start   pointer to the start of the call sequence after padding   */
143 /* OUT: pcode   pointer to the end of the call sequence after padding     */
144 void mono_nacl_align_call(guint8 **start, guint8 **pcode) {
145   const size_t MAX_NACL_CALL_LENGTH = kNaClAlignment;
146   guint8 copy_of_call[MAX_NACL_CALL_LENGTH];
147   guint8 *temp;
148
149   const size_t length = (size_t)((*pcode)-(*start));
150   g_assert(length < MAX_NACL_CALL_LENGTH);
151
152   memcpy(copy_of_call, *start, length);
153   temp = mono_nacl_pad_call(*start, (guint8)length);
154   memcpy(temp, copy_of_call, length);
155   (*start) = temp;
156   (*pcode) = temp + length;
157 }
158
159 /* mono_nacl_pad_call(): Insert padding for Native Client call instructions */
160 /*    code     pointer to buffer for emitting code                          */
161 /*    ilength  length of call instruction                                   */
162 guint8 *mono_nacl_pad_call(guint8 *code, guint8 ilength) {
163   int freeSpaceInBlock = kNaClAlignment - ((uintptr_t)code & kNaClAlignmentMask);
164   int padding = freeSpaceInBlock - ilength;
165
166   if (padding < 0) {
167     /* There isn't enough space in this block for the instruction. */
168     /* Fill this block and start a new one.                        */
169     code = mono_arch_nacl_pad(code, freeSpaceInBlock);
170     freeSpaceInBlock = kNaClAlignment;
171     padding = freeSpaceInBlock - ilength;
172   }
173   g_assert(ilength > 0);
174   g_assert(padding >= 0);
175   g_assert(padding < kNaClAlignment);
176   if (0 == padding) return code;
177   return mono_arch_nacl_pad(code, padding);
178 }
179
180 guint8 *mono_nacl_align(guint8 *code) {
181   int padding = kNaClAlignment - ((uintptr_t)code & kNaClAlignmentMask);
182   if (padding != kNaClAlignment) code = mono_arch_nacl_pad(code, padding);
183   return code;
184 }
185
186 void mono_nacl_fix_patches(const guint8 *code, MonoJumpInfo *ji)
187 {
188 #ifndef USE_JUMP_TABLES
189   MonoJumpInfo *patch_info;
190   for (patch_info = ji; patch_info; patch_info = patch_info->next) {
191     unsigned char *ip = patch_info->ip.i + code;
192     ip = mono_arch_nacl_skip_nops(ip);
193     patch_info->ip.i = ip - code;
194   }
195 #endif
196 }
197 #endif  /* __native_client_codegen__ */
198
199 typedef struct {
200         MonoExceptionClause *clause;
201         MonoBasicBlock *basic_block;
202         int start_offset;
203 } TryBlockHole;
204
205 /**
206  * mono_emit_unwind_op:
207  *
208  *   Add an unwind op with the given parameters for the list of unwind ops stored in
209  * cfg->unwind_ops.
210  */
211 void
212 mono_emit_unwind_op (MonoCompile *cfg, int when, int tag, int reg, int val)
213 {
214         MonoUnwindOp *op = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoUnwindOp));
215
216         op->op = tag;
217         op->reg = reg;
218         op->val = val;
219         op->when = when;
220         
221         cfg->unwind_ops = g_slist_append_mempool (cfg->mempool, cfg->unwind_ops, op);
222         if (cfg->verbose_level > 1) {
223                 switch (tag) {
224                 case DW_CFA_def_cfa:
225                         printf ("CFA: [%x] def_cfa: %s+0x%x\n", when, mono_arch_regname (reg), val);
226                         break;
227                 case DW_CFA_def_cfa_register:
228                         printf ("CFA: [%x] def_cfa_reg: %s\n", when, mono_arch_regname (reg));
229                         break;
230                 case DW_CFA_def_cfa_offset:
231                         printf ("CFA: [%x] def_cfa_offset: 0x%x\n", when, val);
232                         break;
233                 case DW_CFA_offset:
234                         printf ("CFA: [%x] offset: %s at cfa-0x%x\n", when, mono_arch_regname (reg), -val);
235                         break;
236                 }
237         }
238 }
239
240 #define MONO_INIT_VARINFO(vi,id) do { \
241         (vi)->range.first_use.pos.bid = 0xffff; \
242         (vi)->reg = -1; \
243         (vi)->idx = (id); \
244 } while (0)
245
246 /**
247  * mono_unlink_bblock:
248  *
249  *   Unlink two basic blocks.
250  */
251 void
252 mono_unlink_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
253 {
254         int i, pos;
255         gboolean found;
256
257         found = FALSE;
258         for (i = 0; i < from->out_count; ++i) {
259                 if (to == from->out_bb [i]) {
260                         found = TRUE;
261                         break;
262                 }
263         }
264         if (found) {
265                 pos = 0;
266                 for (i = 0; i < from->out_count; ++i) {
267                         if (from->out_bb [i] != to)
268                                 from->out_bb [pos ++] = from->out_bb [i];
269                 }
270                 g_assert (pos == from->out_count - 1);
271                 from->out_count--;
272         }
273
274         found = FALSE;
275         for (i = 0; i < to->in_count; ++i) {
276                 if (from == to->in_bb [i]) {
277                         found = TRUE;
278                         break;
279                 }
280         }
281         if (found) {
282                 pos = 0;
283                 for (i = 0; i < to->in_count; ++i) {
284                         if (to->in_bb [i] != from)
285                                 to->in_bb [pos ++] = to->in_bb [i];
286                 }
287                 g_assert (pos == to->in_count - 1);
288                 to->in_count--;
289         }
290 }
291
292 /*
293  * mono_bblocks_linked:
294  *
295  *   Return whenever BB1 and BB2 are linked in the CFG.
296  */
297 gboolean
298 mono_bblocks_linked (MonoBasicBlock *bb1, MonoBasicBlock *bb2)
299 {
300         int i;
301
302         for (i = 0; i < bb1->out_count; ++i) {
303                 if (bb1->out_bb [i] == bb2)
304                         return TRUE;
305         }
306
307         return FALSE;
308 }
309
310 static int
311 mono_find_block_region_notry (MonoCompile *cfg, int offset)
312 {
313         MonoMethodHeader *header = cfg->header;
314         MonoExceptionClause *clause;
315         int i;
316
317         for (i = 0; i < header->num_clauses; ++i) {
318                 clause = &header->clauses [i];
319                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
320                     (offset < (clause->handler_offset)))
321                         return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
322                            
323                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
324                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
325                                 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
326                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
327                                 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
328                         else
329                                 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
330                 }
331         }
332
333         return -1;
334 }
335
336 /*
337  * mono_get_block_region_notry:
338  *
339  *   Return the region corresponding to REGION, ignoring try clauses nested inside
340  * finally clauses.
341  */
342 int
343 mono_get_block_region_notry (MonoCompile *cfg, int region)
344 {
345         if ((region & (0xf << 4)) == MONO_REGION_TRY) {
346                 MonoMethodHeader *header = cfg->header;
347                 
348                 /*
349                  * This can happen if a try clause is nested inside a finally clause.
350                  */
351                 int clause_index = (region >> 8) - 1;
352                 g_assert (clause_index >= 0 && clause_index < header->num_clauses);
353                 
354                 region = mono_find_block_region_notry (cfg, header->clauses [clause_index].try_offset);
355         }
356
357         return region;
358 }
359
360 MonoInst *
361 mono_find_spvar_for_region (MonoCompile *cfg, int region)
362 {
363         region = mono_get_block_region_notry (cfg, region);
364
365         return g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
366 }
367
368 static void
369 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
370 {
371         int i;
372
373         array [*dfn] = start;
374         /* g_print ("visit %d at %p (BB%ld)\n", *dfn, start->cil_code, start->block_num); */
375         for (i = 0; i < start->out_count; ++i) {
376                 if (start->out_bb [i]->dfn)
377                         continue;
378                 (*dfn)++;
379                 start->out_bb [i]->dfn = *dfn;
380                 start->out_bb [i]->df_parent = start;
381                 array [*dfn] = start->out_bb [i];
382                 df_visit (start->out_bb [i], dfn, array);
383         }
384 }
385
386 guint32
387 mono_reverse_branch_op (guint32 opcode)
388 {
389         static const int reverse_map [] = {
390                 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
391                 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
392         };
393         static const int reverse_fmap [] = {
394                 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
395                 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
396         };
397         static const int reverse_lmap [] = {
398                 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
399                 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
400         };
401         static const int reverse_imap [] = {
402                 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
403                 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
404         };
405                                 
406         if (opcode >= CEE_BEQ && opcode <= CEE_BLT_UN) {
407                 opcode = reverse_map [opcode - CEE_BEQ];
408         } else if (opcode >= OP_FBEQ && opcode <= OP_FBLT_UN) {
409                 opcode = reverse_fmap [opcode - OP_FBEQ];
410         } else if (opcode >= OP_LBEQ && opcode <= OP_LBLT_UN) {
411                 opcode = reverse_lmap [opcode - OP_LBEQ];
412         } else if (opcode >= OP_IBEQ && opcode <= OP_IBLT_UN) {
413                 opcode = reverse_imap [opcode - OP_IBEQ];
414         } else
415                 g_assert_not_reached ();
416
417         return opcode;
418 }
419
420 guint
421 mono_type_to_store_membase (MonoCompile *cfg, MonoType *type)
422 {
423         type = mini_get_underlying_type (type);
424
425 handle_enum:
426         switch (type->type) {
427         case MONO_TYPE_I1:
428         case MONO_TYPE_U1:
429                 return OP_STOREI1_MEMBASE_REG;
430         case MONO_TYPE_I2:
431         case MONO_TYPE_U2:
432                 return OP_STOREI2_MEMBASE_REG;
433         case MONO_TYPE_I4:
434         case MONO_TYPE_U4:
435                 return OP_STOREI4_MEMBASE_REG;
436         case MONO_TYPE_I:
437         case MONO_TYPE_U:
438         case MONO_TYPE_PTR:
439         case MONO_TYPE_FNPTR:
440                 return OP_STORE_MEMBASE_REG;
441         case MONO_TYPE_CLASS:
442         case MONO_TYPE_STRING:
443         case MONO_TYPE_OBJECT:
444         case MONO_TYPE_SZARRAY:
445         case MONO_TYPE_ARRAY:    
446                 return OP_STORE_MEMBASE_REG;
447         case MONO_TYPE_I8:
448         case MONO_TYPE_U8:
449                 return OP_STOREI8_MEMBASE_REG;
450         case MONO_TYPE_R4:
451                 return OP_STORER4_MEMBASE_REG;
452         case MONO_TYPE_R8:
453                 return OP_STORER8_MEMBASE_REG;
454         case MONO_TYPE_VALUETYPE:
455                 if (type->data.klass->enumtype) {
456                         type = mono_class_enum_basetype (type->data.klass);
457                         goto handle_enum;
458                 }
459                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
460                         return OP_STOREX_MEMBASE;
461                 return OP_STOREV_MEMBASE;
462         case MONO_TYPE_TYPEDBYREF:
463                 return OP_STOREV_MEMBASE;
464         case MONO_TYPE_GENERICINST:
465                 type = &type->data.generic_class->container_class->byval_arg;
466                 goto handle_enum;
467         case MONO_TYPE_VAR:
468         case MONO_TYPE_MVAR:
469                 g_assert (mini_type_var_is_vt (type));
470                 return OP_STOREV_MEMBASE;
471         default:
472                 g_error ("unknown type 0x%02x in type_to_store_membase", type->type);
473         }
474         return -1;
475 }
476
477 guint
478 mono_type_to_load_membase (MonoCompile *cfg, MonoType *type)
479 {
480         type = mini_get_underlying_type (type);
481
482         switch (type->type) {
483         case MONO_TYPE_I1:
484                 return OP_LOADI1_MEMBASE;
485         case MONO_TYPE_U1:
486                 return OP_LOADU1_MEMBASE;
487         case MONO_TYPE_I2:
488                 return OP_LOADI2_MEMBASE;
489         case MONO_TYPE_U2:
490                 return OP_LOADU2_MEMBASE;
491         case MONO_TYPE_I4:
492                 return OP_LOADI4_MEMBASE;
493         case MONO_TYPE_U4:
494                 return OP_LOADU4_MEMBASE;
495         case MONO_TYPE_I:
496         case MONO_TYPE_U:
497         case MONO_TYPE_PTR:
498         case MONO_TYPE_FNPTR:
499                 return OP_LOAD_MEMBASE;
500         case MONO_TYPE_CLASS:
501         case MONO_TYPE_STRING:
502         case MONO_TYPE_OBJECT:
503         case MONO_TYPE_SZARRAY:
504         case MONO_TYPE_ARRAY:    
505                 return OP_LOAD_MEMBASE;
506         case MONO_TYPE_I8:
507         case MONO_TYPE_U8:
508                 return OP_LOADI8_MEMBASE;
509         case MONO_TYPE_R4:
510                 return OP_LOADR4_MEMBASE;
511         case MONO_TYPE_R8:
512                 return OP_LOADR8_MEMBASE;
513         case MONO_TYPE_VALUETYPE:
514                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
515                         return OP_LOADX_MEMBASE;
516         case MONO_TYPE_TYPEDBYREF:
517                 return OP_LOADV_MEMBASE;
518         case MONO_TYPE_GENERICINST:
519                 if (mono_type_generic_inst_is_valuetype (type))
520                         return OP_LOADV_MEMBASE;
521                 else
522                         return OP_LOAD_MEMBASE;
523                 break;
524         case MONO_TYPE_VAR:
525         case MONO_TYPE_MVAR:
526                 g_assert (cfg->gshared);
527                 g_assert (mini_type_var_is_vt (type));
528                 return OP_LOADV_MEMBASE;
529         default:
530                 g_error ("unknown type 0x%02x in type_to_load_membase", type->type);
531         }
532         return -1;
533 }
534
535 static guint
536 mini_type_to_ldind (MonoCompile* cfg, MonoType *type)
537 {
538         type = mini_get_underlying_type (type);
539         if (cfg->gshared && !type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)) {
540                 g_assert (mini_type_var_is_vt (type));
541                 return CEE_LDOBJ;
542         }
543         return mono_type_to_ldind (type);
544 }
545
546 #ifndef DISABLE_JIT
547
548 guint
549 mini_type_to_stind (MonoCompile* cfg, MonoType *type)
550 {
551         type = mini_get_underlying_type (type);
552         if (cfg->gshared && !type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)) {
553                 g_assert (mini_type_var_is_vt (type));
554                 return CEE_STOBJ;
555         }
556         return mono_type_to_stind (type);
557 }
558
559 int
560 mono_op_imm_to_op (int opcode)
561 {
562         switch (opcode) {
563         case OP_ADD_IMM:
564 #if SIZEOF_REGISTER == 4
565                 return OP_IADD;
566 #else
567                 return OP_LADD;
568 #endif
569         case OP_IADD_IMM:
570                 return OP_IADD;
571         case OP_LADD_IMM:
572                 return OP_LADD;
573         case OP_ISUB_IMM:
574                 return OP_ISUB;
575         case OP_LSUB_IMM:
576                 return OP_LSUB;
577         case OP_IMUL_IMM:
578                 return OP_IMUL;
579         case OP_AND_IMM:
580 #if SIZEOF_REGISTER == 4
581                 return OP_IAND;
582 #else
583                 return OP_LAND;
584 #endif
585         case OP_OR_IMM:
586 #if SIZEOF_REGISTER == 4
587                 return OP_IOR;
588 #else
589                 return OP_LOR;
590 #endif
591         case OP_XOR_IMM:
592 #if SIZEOF_REGISTER == 4
593                 return OP_IXOR;
594 #else
595                 return OP_LXOR;
596 #endif
597         case OP_IAND_IMM:
598                 return OP_IAND;
599         case OP_LAND_IMM:
600                 return OP_LAND;
601         case OP_IOR_IMM:
602                 return OP_IOR;
603         case OP_LOR_IMM:
604                 return OP_LOR;
605         case OP_IXOR_IMM:
606                 return OP_IXOR;
607         case OP_LXOR_IMM:
608                 return OP_LXOR;
609         case OP_ISHL_IMM:
610                 return OP_ISHL;
611         case OP_LSHL_IMM:
612                 return OP_LSHL;
613         case OP_ISHR_IMM:
614                 return OP_ISHR;
615         case OP_LSHR_IMM:
616                 return OP_LSHR;
617         case OP_ISHR_UN_IMM:
618                 return OP_ISHR_UN;
619         case OP_LSHR_UN_IMM:
620                 return OP_LSHR_UN;
621         case OP_IDIV_IMM:
622                 return OP_IDIV;
623         case OP_IDIV_UN_IMM:
624                 return OP_IDIV_UN;
625         case OP_IREM_UN_IMM:
626                 return OP_IREM_UN;
627         case OP_IREM_IMM:
628                 return OP_IREM;
629         case OP_LREM_IMM:
630                 return OP_LREM;
631         case OP_DIV_IMM:
632 #if SIZEOF_REGISTER == 4
633                 return OP_IDIV;
634 #else
635                 return OP_LDIV;
636 #endif
637         case OP_REM_IMM:
638 #if SIZEOF_REGISTER == 4
639                 return OP_IREM;
640 #else
641                 return OP_LREM;
642 #endif
643         case OP_ADDCC_IMM:
644                 return OP_ADDCC;
645         case OP_ADC_IMM:
646                 return OP_ADC;
647         case OP_SUBCC_IMM:
648                 return OP_SUBCC;
649         case OP_SBB_IMM:
650                 return OP_SBB;
651         case OP_IADC_IMM:
652                 return OP_IADC;
653         case OP_ISBB_IMM:
654                 return OP_ISBB;
655         case OP_COMPARE_IMM:
656                 return OP_COMPARE;
657         case OP_ICOMPARE_IMM:
658                 return OP_ICOMPARE;
659         case OP_LOCALLOC_IMM:
660                 return OP_LOCALLOC;
661         default:
662                 printf ("%s\n", mono_inst_name (opcode));
663                 g_assert_not_reached ();
664                 return -1;
665         }
666 }
667
668 /*
669  * mono_decompose_op_imm:
670  *
671  *   Replace the OP_.._IMM INS with its non IMM variant.
672  */
673 void
674 mono_decompose_op_imm (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins)
675 {
676         MonoInst *temp;
677
678         MONO_INST_NEW (cfg, temp, OP_ICONST);
679         temp->inst_c0 = ins->inst_imm;
680         temp->dreg = mono_alloc_ireg (cfg);
681         mono_bblock_insert_before_ins (bb, ins, temp);
682         ins->opcode = mono_op_imm_to_op (ins->opcode);
683         if (ins->opcode == OP_LOCALLOC)
684                 ins->sreg1 = temp->dreg;
685         else
686                 ins->sreg2 = temp->dreg;
687
688         bb->max_vreg = MAX (bb->max_vreg, cfg->next_vreg);
689 }
690
691 #endif
692
693 static void
694 set_vreg_to_inst (MonoCompile *cfg, int vreg, MonoInst *inst)
695 {
696         if (vreg >= cfg->vreg_to_inst_len) {
697                 MonoInst **tmp = cfg->vreg_to_inst;
698                 int size = cfg->vreg_to_inst_len;
699
700                 while (vreg >= cfg->vreg_to_inst_len)
701                         cfg->vreg_to_inst_len = cfg->vreg_to_inst_len ? cfg->vreg_to_inst_len * 2 : 32;
702                 cfg->vreg_to_inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * cfg->vreg_to_inst_len);
703                 if (size)
704                         memcpy (cfg->vreg_to_inst, tmp, size * sizeof (MonoInst*));
705         }
706         cfg->vreg_to_inst [vreg] = inst;
707 }
708
709 #define mono_type_is_long(type) (!(type)->byref && ((mono_type_get_underlying_type (type)->type == MONO_TYPE_I8) || (mono_type_get_underlying_type (type)->type == MONO_TYPE_U8)))
710 #define mono_type_is_float(type) (!(type)->byref && (((type)->type == MONO_TYPE_R8) || ((type)->type == MONO_TYPE_R4)))
711
712 #ifdef DISABLE_JIT
713
714 MonoInst*
715 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
716 {
717         return NULL;
718 }
719
720 #else
721
722 MonoInst*
723 mono_compile_create_var_for_vreg (MonoCompile *cfg, MonoType *type, int opcode, int vreg)
724 {
725         MonoInst *inst;
726         int num = cfg->num_varinfo;
727         gboolean regpair;
728
729         type = mini_get_underlying_type (type);
730
731         if ((num + 1) >= cfg->varinfo_count) {
732                 int orig_count = cfg->varinfo_count;
733                 cfg->varinfo_count = cfg->varinfo_count ? (cfg->varinfo_count * 2) : 32;
734                 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
735                 cfg->vars = (MonoMethodVar *)g_realloc (cfg->vars, sizeof (MonoMethodVar) * cfg->varinfo_count);
736                 memset (&cfg->vars [orig_count], 0, (cfg->varinfo_count - orig_count) * sizeof (MonoMethodVar));
737         }
738
739         cfg->stat_allocate_var++;
740
741         MONO_INST_NEW (cfg, inst, opcode);
742         inst->inst_c0 = num;
743         inst->inst_vtype = type;
744         inst->klass = mono_class_from_mono_type (type);
745         type_to_eval_stack_type (cfg, type, inst);
746         /* if set to 1 the variable is native */
747         inst->backend.is_pinvoke = 0;
748         inst->dreg = vreg;
749
750         if (inst->klass->exception_type)
751                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
752
753         if (cfg->compute_gc_maps) {
754                 if (type->byref) {
755                         mono_mark_vreg_as_mp (cfg, vreg);
756                 } else {
757                         if ((MONO_TYPE_ISSTRUCT (type) && inst->klass->has_references) || mini_type_is_reference (type)) {
758                                 inst->flags |= MONO_INST_GC_TRACK;
759                                 mono_mark_vreg_as_ref (cfg, vreg);
760                         }
761                 }
762         }
763         
764         cfg->varinfo [num] = inst;
765
766         MONO_INIT_VARINFO (&cfg->vars [num], num);
767         MONO_VARINFO (cfg, num)->vreg = vreg;
768
769         if (vreg != -1)
770                 set_vreg_to_inst (cfg, vreg, inst);
771
772 #if SIZEOF_REGISTER == 4
773         if (mono_arch_is_soft_float ()) {
774                 regpair = mono_type_is_long (type) || mono_type_is_float (type);
775         } else {
776                 regpair = mono_type_is_long (type);
777         }
778 #else
779         regpair = FALSE;
780 #endif
781
782         if (regpair) {
783                 MonoInst *tree;
784
785                 /* 
786                  * These two cannot be allocated using create_var_for_vreg since that would
787                  * put it into the cfg->varinfo array, confusing many parts of the JIT.
788                  */
789
790                 /* 
791                  * Set flags to VOLATILE so SSA skips it.
792                  */
793
794                 if (cfg->verbose_level >= 4) {
795                         printf ("  Create LVAR R%d (R%d, R%d)\n", inst->dreg, inst->dreg + 1, inst->dreg + 2);
796                 }
797
798                 if (mono_arch_is_soft_float () && cfg->opt & MONO_OPT_SSA) {
799                         if (mono_type_is_float (type))
800                                 inst->flags = MONO_INST_VOLATILE;
801                 }
802
803                 /* Allocate a dummy MonoInst for the first vreg */
804                 MONO_INST_NEW (cfg, tree, OP_LOCAL);
805                 tree->dreg = inst->dreg + 1;
806                 if (cfg->opt & MONO_OPT_SSA)
807                         tree->flags = MONO_INST_VOLATILE;
808                 tree->inst_c0 = num;
809                 tree->type = STACK_I4;
810                 tree->inst_vtype = &mono_defaults.int32_class->byval_arg;
811                 tree->klass = mono_class_from_mono_type (tree->inst_vtype);
812
813                 set_vreg_to_inst (cfg, inst->dreg + 1, tree);
814
815                 /* Allocate a dummy MonoInst for the second vreg */
816                 MONO_INST_NEW (cfg, tree, OP_LOCAL);
817                 tree->dreg = inst->dreg + 2;
818                 if (cfg->opt & MONO_OPT_SSA)
819                         tree->flags = MONO_INST_VOLATILE;
820                 tree->inst_c0 = num;
821                 tree->type = STACK_I4;
822                 tree->inst_vtype = &mono_defaults.int32_class->byval_arg;
823                 tree->klass = mono_class_from_mono_type (tree->inst_vtype);
824
825                 set_vreg_to_inst (cfg, inst->dreg + 2, tree);
826         }
827
828         cfg->num_varinfo++;
829         if (cfg->verbose_level > 2)
830                 g_print ("created temp %d (R%d) of type %s\n", num, vreg, mono_type_get_name (type));
831         return inst;
832 }
833
834 MonoInst*
835 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
836 {
837         int dreg;
838         type = mini_get_underlying_type (type);
839
840         if (mono_type_is_long (type))
841                 dreg = mono_alloc_dreg (cfg, STACK_I8);
842         else if (mono_arch_is_soft_float () && mono_type_is_float (type))
843                 dreg = mono_alloc_dreg (cfg, STACK_R8);
844         else
845                 /* All the others are unified */
846                 dreg = mono_alloc_preg (cfg);
847
848         return mono_compile_create_var_for_vreg (cfg, type, opcode, dreg);
849 }
850
851 /*
852  * Transform a MonoInst into a load from the variable of index var_index.
853  */
854 void
855 mono_compile_make_var_load (MonoCompile *cfg, MonoInst *dest, gssize var_index)
856 {
857         memset (dest, 0, sizeof (MonoInst));
858         dest->inst_i0 = cfg->varinfo [var_index];
859         dest->opcode = mini_type_to_ldind (cfg, dest->inst_i0->inst_vtype);
860         type_to_eval_stack_type (cfg, dest->inst_i0->inst_vtype, dest);
861         dest->klass = dest->inst_i0->klass;
862 }
863
864 MonoInst*
865 mini_get_int_to_float_spill_area (MonoCompile *cfg)
866 {
867 #ifdef TARGET_X86
868         if (!cfg->iconv_raw_var) {
869                 cfg->iconv_raw_var = mono_compile_create_var (cfg, &mono_defaults.int32_class->byval_arg, OP_LOCAL);
870                 cfg->iconv_raw_var->flags |= MONO_INST_VOLATILE; /*FIXME, use the don't regalloc flag*/
871         }
872         return cfg->iconv_raw_var;
873 #else
874         return NULL;
875 #endif
876 }
877
878 #endif
879
880 void
881 mono_mark_vreg_as_ref (MonoCompile *cfg, int vreg)
882 {
883         if (vreg >= cfg->vreg_is_ref_len) {
884                 gboolean *tmp = cfg->vreg_is_ref;
885                 int size = cfg->vreg_is_ref_len;
886
887                 while (vreg >= cfg->vreg_is_ref_len)
888                         cfg->vreg_is_ref_len = cfg->vreg_is_ref_len ? cfg->vreg_is_ref_len * 2 : 32;
889                 cfg->vreg_is_ref = mono_mempool_alloc0 (cfg->mempool, sizeof (gboolean) * cfg->vreg_is_ref_len);
890                 if (size)
891                         memcpy (cfg->vreg_is_ref, tmp, size * sizeof (gboolean));
892         }
893         cfg->vreg_is_ref [vreg] = TRUE;
894 }       
895
896 void
897 mono_mark_vreg_as_mp (MonoCompile *cfg, int vreg)
898 {
899         if (vreg >= cfg->vreg_is_mp_len) {
900                 gboolean *tmp = cfg->vreg_is_mp;
901                 int size = cfg->vreg_is_mp_len;
902
903                 while (vreg >= cfg->vreg_is_mp_len)
904                         cfg->vreg_is_mp_len = cfg->vreg_is_mp_len ? cfg->vreg_is_mp_len * 2 : 32;
905                 cfg->vreg_is_mp = mono_mempool_alloc0 (cfg->mempool, sizeof (gboolean) * cfg->vreg_is_mp_len);
906                 if (size)
907                         memcpy (cfg->vreg_is_mp, tmp, size * sizeof (gboolean));
908         }
909         cfg->vreg_is_mp [vreg] = TRUE;
910 }       
911
912 static MonoType*
913 type_from_stack_type (MonoInst *ins) {
914         switch (ins->type) {
915         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
916         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
917         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
918         case STACK_R8: return &mono_defaults.double_class->byval_arg;
919         case STACK_MP:
920                 /* 
921                  * this if used to be commented without any specific reason, but
922                  * it breaks #80235 when commented
923                  */
924                 if (ins->klass)
925                         return &ins->klass->this_arg;
926                 else
927                         return &mono_defaults.object_class->this_arg;
928         case STACK_OBJ:
929                 /* ins->klass may not be set for ldnull.
930                  * Also, if we have a boxed valuetype, we want an object lass,
931                  * not the valuetype class
932                  */
933                 if (ins->klass && !ins->klass->valuetype)
934                         return &ins->klass->byval_arg;
935                 return &mono_defaults.object_class->byval_arg;
936         case STACK_VTYPE: return &ins->klass->byval_arg;
937         default:
938                 g_error ("stack type %d to montype not handled\n", ins->type);
939         }
940         return NULL;
941 }
942
943 MonoType*
944 mono_type_from_stack_type (MonoInst *ins) {
945         return type_from_stack_type (ins);
946 }
947
948 /*
949  * mono_add_ins_to_end:
950  *
951  *   Same as MONO_ADD_INS, but add INST before any branches at the end of BB.
952  */
953 void
954 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
955 {
956         int opcode;
957
958         if (!bb->code) {
959                 MONO_ADD_INS (bb, inst);
960                 return;
961         }
962
963         switch (bb->last_ins->opcode) {
964         case OP_BR:
965         case OP_BR_REG:
966         case CEE_BEQ:
967         case CEE_BGE:
968         case CEE_BGT:
969         case CEE_BLE:
970         case CEE_BLT:
971         case CEE_BNE_UN:
972         case CEE_BGE_UN:
973         case CEE_BGT_UN:
974         case CEE_BLE_UN:
975         case CEE_BLT_UN:
976         case OP_SWITCH:
977                 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
978                 break;
979         default:
980                 if (MONO_IS_COND_BRANCH_OP (bb->last_ins)) {
981                         /* Need to insert the ins before the compare */
982                         if (bb->code == bb->last_ins) {
983                                 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
984                                 return;
985                         }
986
987                         if (bb->code->next == bb->last_ins) {
988                                 /* Only two instructions */
989                                 opcode = bb->code->opcode;
990
991                                 if ((opcode == OP_COMPARE) || (opcode == OP_COMPARE_IMM) || (opcode == OP_ICOMPARE) || (opcode == OP_ICOMPARE_IMM) || (opcode == OP_FCOMPARE) || (opcode == OP_LCOMPARE) || (opcode == OP_LCOMPARE_IMM) || (opcode == OP_RCOMPARE)) {
992                                         /* NEW IR */
993                                         mono_bblock_insert_before_ins (bb, bb->code, inst);
994                                 } else {
995                                         mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
996                                 }
997                         } else {
998                                 opcode = bb->last_ins->prev->opcode;
999
1000                                 if ((opcode == OP_COMPARE) || (opcode == OP_COMPARE_IMM) || (opcode == OP_ICOMPARE) || (opcode == OP_ICOMPARE_IMM) || (opcode == OP_FCOMPARE) || (opcode == OP_LCOMPARE) || (opcode == OP_LCOMPARE_IMM) || (opcode == OP_RCOMPARE)) {
1001                                         /* NEW IR */
1002                                         mono_bblock_insert_before_ins (bb, bb->last_ins->prev, inst);
1003                                 } else {
1004                                         mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
1005                                 }                                       
1006                         }
1007                 }
1008                 else
1009                         MONO_ADD_INS (bb, inst);
1010                 break;
1011         }
1012 }
1013
1014 void
1015 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
1016 {
1017         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
1018         MonoJumpInfoBBTable *table;
1019
1020         table = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
1021         table->table = bbs;
1022         table->table_size = num_blocks;
1023         
1024         ji->ip.label = label;
1025         ji->type = MONO_PATCH_INFO_SWITCH;
1026         ji->data.table = table;
1027         ji->next = cfg->patch_info;
1028         cfg->patch_info = ji;
1029 }
1030
1031 static MonoMethodSignature *
1032 mono_get_array_new_va_signature (int arity)
1033 {
1034         static GHashTable *sighash;
1035         MonoMethodSignature *res;
1036         int i;
1037
1038         mono_jit_lock ();
1039         if (!sighash) {
1040                 sighash = g_hash_table_new (NULL, NULL);
1041         }
1042         else if ((res = g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
1043                 mono_jit_unlock ();
1044                 return res;
1045         }
1046
1047         res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
1048
1049         res->pinvoke = 1;
1050         if (ARCH_VARARG_ICALLS)
1051                 /* Only set this only some archs since not all backends can handle varargs+pinvoke */
1052                 res->call_convention = MONO_CALL_VARARG;
1053
1054 #ifdef TARGET_WIN32
1055         res->call_convention = MONO_CALL_C;
1056 #endif
1057
1058         res->params [0] = &mono_defaults.int_class->byval_arg;  
1059         for (i = 0; i < arity; i++)
1060                 res->params [i + 1] = &mono_defaults.int_class->byval_arg;
1061
1062         res->ret = &mono_defaults.object_class->byval_arg;
1063
1064         g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
1065         mono_jit_unlock ();
1066
1067         return res;
1068 }
1069
1070 MonoJitICallInfo *
1071 mono_get_array_new_va_icall (int rank)
1072 {
1073         MonoMethodSignature *esig;
1074         char icall_name [256];
1075         char *name;
1076         MonoJitICallInfo *info;
1077
1078         /* Need to register the icall so it gets an icall wrapper */
1079         sprintf (icall_name, "ves_array_new_va_%d", rank);
1080
1081         mono_jit_lock ();
1082         info = mono_find_jit_icall_by_name (icall_name);
1083         if (info == NULL) {
1084                 esig = mono_get_array_new_va_signature (rank);
1085                 name = g_strdup (icall_name);
1086                 info = mono_register_jit_icall (mono_array_new_va, name, esig, FALSE);
1087         }
1088         mono_jit_unlock ();
1089
1090         return info;
1091 }
1092
1093 gboolean
1094 mini_class_is_system_array (MonoClass *klass)
1095 {
1096         if (klass->parent == mono_defaults.array_class)
1097                 return TRUE;
1098         else
1099                 return FALSE;
1100 }
1101
1102 gboolean
1103 mini_assembly_can_skip_verification (MonoDomain *domain, MonoMethod *method)
1104 {
1105         MonoAssembly *assembly = method->klass->image->assembly;
1106         if (method->wrapper_type != MONO_WRAPPER_NONE && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
1107                 return FALSE;
1108         if (assembly->in_gac || assembly->image == mono_defaults.corlib)
1109                 return FALSE;
1110         return mono_assembly_has_skip_verification (assembly);
1111 }
1112
1113 /*
1114  * mini_method_verify:
1115  * 
1116  * Verify the method using the new verfier.
1117  * 
1118  * Returns true if the method is invalid. 
1119  */
1120 static gboolean
1121 mini_method_verify (MonoCompile *cfg, MonoMethod *method, gboolean fail_compile)
1122 {
1123         GSList *tmp, *res;
1124         gboolean is_fulltrust;
1125         MonoLoaderError *error;
1126
1127         if (method->verification_success)
1128                 return FALSE;
1129
1130         if (!mono_verifier_is_enabled_for_method (method))
1131                 return FALSE;
1132
1133         /*skip verification implies the assembly must be */
1134         is_fulltrust = mono_verifier_is_method_full_trust (method) ||  mini_assembly_can_skip_verification (cfg->domain, method);
1135
1136         res = mono_method_verify_with_current_settings (method, cfg->skip_visibility, is_fulltrust);
1137
1138         if ((error = mono_loader_get_last_error ())) {
1139                 if (fail_compile)
1140                         cfg->exception_type = error->exception_type;
1141                 else
1142                         mono_loader_clear_error ();
1143                 if (res)
1144                         mono_free_verify_list (res);
1145                 return TRUE;
1146         }
1147
1148         if (res) { 
1149                 for (tmp = res; tmp; tmp = tmp->next) {
1150                         MonoVerifyInfoExtended *info = (MonoVerifyInfoExtended *)tmp->data;
1151                         if (info->info.status == MONO_VERIFY_ERROR) {
1152                                 if (fail_compile) {
1153                                 char *method_name = mono_method_full_name (method, TRUE);
1154                                         cfg->exception_type = info->exception_type;
1155                                         cfg->exception_message = g_strdup_printf ("Error verifying %s: %s", method_name, info->info.message);
1156                                         g_free (method_name);
1157                                 }
1158                                 mono_free_verify_list (res);
1159                                 return TRUE;
1160                         }
1161                         if (info->info.status == MONO_VERIFY_NOT_VERIFIABLE && (!is_fulltrust || info->exception_type == MONO_EXCEPTION_METHOD_ACCESS || info->exception_type == MONO_EXCEPTION_FIELD_ACCESS)) {
1162                                 if (fail_compile) {
1163                                         char *method_name = mono_method_full_name (method, TRUE);
1164                                         cfg->exception_type = info->exception_type;
1165                                         cfg->exception_message = g_strdup_printf ("Error verifying %s: %s", method_name, info->info.message);
1166                                         g_free (method_name);
1167                                 }
1168                                 mono_free_verify_list (res);
1169                                 return TRUE;
1170                         }
1171                 }
1172                 mono_free_verify_list (res);
1173         }
1174         method->verification_success = 1;
1175         return FALSE;
1176 }
1177
1178 /*Returns true if something went wrong*/
1179 gboolean
1180 mono_compile_is_broken (MonoCompile *cfg, MonoMethod *method, gboolean fail_compile)
1181 {
1182         MonoMethod *method_definition = method;
1183         gboolean dont_verify = method->klass->image->assembly->corlib_internal;
1184
1185         while (method_definition->is_inflated) {
1186                 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
1187                 method_definition = imethod->declaring;
1188         }
1189
1190         return !dont_verify && mini_method_verify (cfg, method_definition, fail_compile);
1191 }
1192
1193 static void
1194 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
1195 {
1196         if (!domain_jit_info (domain)->dynamic_code_hash)
1197                 domain_jit_info (domain)->dynamic_code_hash = g_hash_table_new (NULL, NULL);
1198         g_hash_table_insert (domain_jit_info (domain)->dynamic_code_hash, method, ji);
1199 }
1200
1201 static MonoJitDynamicMethodInfo*
1202 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
1203 {
1204         MonoJitDynamicMethodInfo *res;
1205
1206         if (domain_jit_info (domain)->dynamic_code_hash)
1207                 res = g_hash_table_lookup (domain_jit_info (domain)->dynamic_code_hash, method);
1208         else
1209                 res = NULL;
1210         return res;
1211 }
1212
1213 typedef struct {
1214         MonoClass *vtype;
1215         GList *active, *inactive;
1216         GSList *slots;
1217 } StackSlotInfo;
1218
1219 static gint 
1220 compare_by_interval_start_pos_func (gconstpointer a, gconstpointer b)
1221 {
1222         MonoMethodVar *v1 = (MonoMethodVar*)a;
1223         MonoMethodVar *v2 = (MonoMethodVar*)b;
1224
1225         if (v1 == v2)
1226                 return 0;
1227         else if (v1->interval->range && v2->interval->range)
1228                 return v1->interval->range->from - v2->interval->range->from;
1229         else if (v1->interval->range)
1230                 return -1;
1231         else
1232                 return 1;
1233 }
1234
1235 #ifndef DISABLE_JIT
1236
1237 #if 0
1238 #define LSCAN_DEBUG(a) do { a; } while (0)
1239 #else
1240 #define LSCAN_DEBUG(a)
1241 #endif
1242
1243 static gint32*
1244 mono_allocate_stack_slots2 (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
1245 {
1246         int i, slot, offset, size;
1247         guint32 align;
1248         MonoMethodVar *vmv;
1249         MonoInst *inst;
1250         gint32 *offsets;
1251         GList *vars = NULL, *l, *unhandled;
1252         StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
1253         MonoType *t;
1254         int nvtypes;
1255         gboolean reuse_slot;
1256
1257         LSCAN_DEBUG (printf ("Allocate Stack Slots 2 for %s:\n", mono_method_full_name (cfg->method, TRUE)));
1258
1259         scalar_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
1260         vtype_stack_slots = NULL;
1261         nvtypes = 0;
1262
1263         offsets = mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
1264         for (i = 0; i < cfg->num_varinfo; ++i)
1265                 offsets [i] = -1;
1266
1267         for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1268                 inst = cfg->varinfo [i];
1269                 vmv = MONO_VARINFO (cfg, i);
1270
1271                 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
1272                         continue;
1273
1274                 vars = g_list_prepend (vars, vmv);
1275         }
1276
1277         vars = g_list_sort (g_list_copy (vars), compare_by_interval_start_pos_func);
1278
1279         /* Sanity check */
1280         /*
1281         i = 0;
1282         for (unhandled = vars; unhandled; unhandled = unhandled->next) {
1283                 MonoMethodVar *current = unhandled->data;
1284
1285                 if (current->interval->range) {
1286                         g_assert (current->interval->range->from >= i);
1287                         i = current->interval->range->from;
1288                 }
1289         }
1290         */
1291
1292         offset = 0;
1293         *stack_align = 0;
1294         for (unhandled = vars; unhandled; unhandled = unhandled->next) {
1295                 MonoMethodVar *current = unhandled->data;
1296
1297                 vmv = current;
1298                 inst = cfg->varinfo [vmv->idx];
1299
1300                 t = mono_type_get_underlying_type (inst->inst_vtype);
1301                 if (cfg->gsharedvt && mini_is_gsharedvt_variable_type (t))
1302                         continue;
1303
1304                 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
1305                 * pinvoke wrappers when they call functions returning structures */
1306                 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (t) && t->type != MONO_TYPE_TYPEDBYREF) {
1307                         size = mono_class_native_size (mono_class_from_mono_type (t), &align);
1308                 }
1309                 else {
1310                         int ialign;
1311
1312                         size = mini_type_stack_size (t, &ialign);
1313                         align = ialign;
1314
1315                         if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (t)))
1316                                 align = 16;
1317                 }
1318
1319                 reuse_slot = TRUE;
1320                 if (cfg->disable_reuse_stack_slots)
1321                         reuse_slot = FALSE;
1322
1323                 t = mini_get_underlying_type (t);
1324                 switch (t->type) {
1325                 case MONO_TYPE_GENERICINST:
1326                         if (!mono_type_generic_inst_is_valuetype (t)) {
1327                                 slot_info = &scalar_stack_slots [t->type];
1328                                 break;
1329                         }
1330                         /* Fall through */
1331                 case MONO_TYPE_VALUETYPE:
1332                         if (!vtype_stack_slots)
1333                                 vtype_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * 256);
1334                         for (i = 0; i < nvtypes; ++i)
1335                                 if (t->data.klass == vtype_stack_slots [i].vtype)
1336                                         break;
1337                         if (i < nvtypes)
1338                                 slot_info = &vtype_stack_slots [i];
1339                         else {
1340                                 g_assert (nvtypes < 256);
1341                                 vtype_stack_slots [nvtypes].vtype = t->data.klass;
1342                                 slot_info = &vtype_stack_slots [nvtypes];
1343                                 nvtypes ++;
1344                         }
1345                         if (cfg->disable_reuse_ref_stack_slots)
1346                                 reuse_slot = FALSE;
1347                         break;
1348
1349                 case MONO_TYPE_PTR:
1350                 case MONO_TYPE_I:
1351                 case MONO_TYPE_U:
1352 #if SIZEOF_VOID_P == 4
1353                 case MONO_TYPE_I4:
1354 #else
1355                 case MONO_TYPE_I8:
1356 #endif
1357                         if (cfg->disable_ref_noref_stack_slot_share) {
1358                                 slot_info = &scalar_stack_slots [MONO_TYPE_I];
1359                                 break;
1360                         }
1361                         /* Fall through */
1362
1363                 case MONO_TYPE_CLASS:
1364                 case MONO_TYPE_OBJECT:
1365                 case MONO_TYPE_ARRAY:
1366                 case MONO_TYPE_SZARRAY:
1367                 case MONO_TYPE_STRING:
1368                         /* Share non-float stack slots of the same size */
1369                         slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
1370                         if (cfg->disable_reuse_ref_stack_slots)
1371                                 reuse_slot = FALSE;
1372                         break;
1373
1374                 default:
1375                         slot_info = &scalar_stack_slots [t->type];
1376                 }
1377
1378                 slot = 0xffffff;
1379                 if (cfg->comp_done & MONO_COMP_LIVENESS) {
1380                         int pos;
1381                         gboolean changed;
1382
1383                         //printf ("START  %2d %08x %08x\n",  vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
1384
1385                         if (!current->interval->range) {
1386                                 if (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))
1387                                         pos = ~0;
1388                                 else {
1389                                         /* Dead */
1390                                         inst->flags |= MONO_INST_IS_DEAD;
1391                                         continue;
1392                                 }
1393                         }
1394                         else
1395                                 pos = current->interval->range->from;
1396
1397                         LSCAN_DEBUG (printf ("process R%d ", inst->dreg));
1398                         if (current->interval->range)
1399                                 LSCAN_DEBUG (mono_linterval_print (current->interval));
1400                         LSCAN_DEBUG (printf ("\n"));
1401
1402                         /* Check for intervals in active which expired or inactive */
1403                         changed = TRUE;
1404                         /* FIXME: Optimize this */
1405                         while (changed) {
1406                                 changed = FALSE;
1407                                 for (l = slot_info->active; l != NULL; l = l->next) {
1408                                         MonoMethodVar *v = (MonoMethodVar*)l->data;
1409
1410                                         if (v->interval->last_range->to < pos) {
1411                                                 slot_info->active = g_list_delete_link (slot_info->active, l);
1412                                                 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [v->idx]));
1413                                                 LSCAN_DEBUG (printf ("Interval R%d has expired, adding 0x%x to slots\n", cfg->varinfo [v->idx]->dreg, offsets [v->idx]));
1414                                                 changed = TRUE;
1415                                                 break;
1416                                         }
1417                                         else if (!mono_linterval_covers (v->interval, pos)) {
1418                                                 slot_info->inactive = g_list_append (slot_info->inactive, v);
1419                                                 slot_info->active = g_list_delete_link (slot_info->active, l);
1420                                                 LSCAN_DEBUG (printf ("Interval R%d became inactive\n", cfg->varinfo [v->idx]->dreg));
1421                                                 changed = TRUE;
1422                                                 break;
1423                                         }
1424                                 }
1425                         }
1426
1427                         /* Check for intervals in inactive which expired or active */
1428                         changed = TRUE;
1429                         /* FIXME: Optimize this */
1430                         while (changed) {
1431                                 changed = FALSE;
1432                                 for (l = slot_info->inactive; l != NULL; l = l->next) {
1433                                         MonoMethodVar *v = (MonoMethodVar*)l->data;
1434
1435                                         if (v->interval->last_range->to < pos) {
1436                                                 slot_info->inactive = g_list_delete_link (slot_info->inactive, l);
1437                                                 // FIXME: Enabling this seems to cause impossible to debug crashes
1438                                                 //slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [v->idx]));
1439                                                 LSCAN_DEBUG (printf ("Interval R%d has expired, adding 0x%x to slots\n", cfg->varinfo [v->idx]->dreg, offsets [v->idx]));
1440                                                 changed = TRUE;
1441                                                 break;
1442                                         }
1443                                         else if (mono_linterval_covers (v->interval, pos)) {
1444                                                 slot_info->active = g_list_append (slot_info->active, v);
1445                                                 slot_info->inactive = g_list_delete_link (slot_info->inactive, l);
1446                                                 LSCAN_DEBUG (printf ("\tInterval R%d became active\n", cfg->varinfo [v->idx]->dreg));
1447                                                 changed = TRUE;
1448                                                 break;
1449                                         }
1450                                 }
1451                         }
1452
1453                         /* 
1454                          * This also handles the case when the variable is used in an
1455                          * exception region, as liveness info is not computed there.
1456                          */
1457                         /* 
1458                          * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
1459                          * opcodes.
1460                          */
1461                         if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
1462                                 if (slot_info->slots) {
1463                                         slot = GPOINTER_TO_INT (slot_info->slots->data);
1464
1465                                         slot_info->slots = slot_info->slots->next;
1466                                 }
1467
1468                                 /* FIXME: We might want to consider the inactive intervals as well if slot_info->slots is empty */
1469
1470                                 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
1471                         }
1472                 }
1473
1474 #if 0
1475                 {
1476                         static int count = 0;
1477                         count ++;
1478
1479                         if (count == atoi (g_getenv ("COUNT3")))
1480                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
1481                         if (count > atoi (g_getenv ("COUNT3")))
1482                                 slot = 0xffffff;
1483                         else {
1484                                 mono_print_ins (inst);
1485                                 }
1486                 }
1487 #endif
1488
1489                 LSCAN_DEBUG (printf ("R%d %s -> 0x%x\n", inst->dreg, mono_type_full_name (t), slot));
1490
1491                 if (inst->flags & MONO_INST_LMF) {
1492                         size = sizeof (MonoLMF);
1493                         align = sizeof (mgreg_t);
1494                         reuse_slot = FALSE;
1495                 }
1496
1497                 if (!reuse_slot)
1498                         slot = 0xffffff;
1499
1500                 if (slot == 0xffffff) {
1501                         /*
1502                          * Allways allocate valuetypes to sizeof (gpointer) to allow more
1503                          * efficient copying (and to work around the fact that OP_MEMCPY
1504                          * and OP_MEMSET ignores alignment).
1505                          */
1506                         if (MONO_TYPE_ISSTRUCT (t)) {
1507                                 align = MAX (align, sizeof (gpointer));
1508                                 align = MAX (align, mono_class_min_align (mono_class_from_mono_type (t)));
1509                         }
1510
1511                         if (backward) {
1512                                 offset += size;
1513                                 offset += align - 1;
1514                                 offset &= ~(align - 1);
1515                                 slot = offset;
1516                         }
1517                         else {
1518                                 offset += align - 1;
1519                                 offset &= ~(align - 1);
1520                                 slot = offset;
1521                                 offset += size;
1522                         }
1523
1524                         if (*stack_align == 0)
1525                                 *stack_align = align;
1526                 }
1527
1528                 offsets [vmv->idx] = slot;
1529         }
1530         g_list_free (vars);
1531         for (i = 0; i < MONO_TYPE_PINNED; ++i) {
1532                 if (scalar_stack_slots [i].active)
1533                         g_list_free (scalar_stack_slots [i].active);
1534         }
1535         for (i = 0; i < nvtypes; ++i) {
1536                 if (vtype_stack_slots [i].active)
1537                         g_list_free (vtype_stack_slots [i].active);
1538         }
1539
1540         cfg->stat_locals_stack_size += offset;
1541
1542         *stack_size = offset;
1543         return offsets;
1544 }
1545
1546 /*
1547  *  mono_allocate_stack_slots:
1548  *
1549  *  Allocate stack slots for all non register allocated variables using a
1550  * linear scan algorithm.
1551  * Returns: an array of stack offsets.
1552  * STACK_SIZE is set to the amount of stack space needed.
1553  * STACK_ALIGN is set to the alignment needed by the locals area.
1554  */
1555 gint32*
1556 mono_allocate_stack_slots (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
1557 {
1558         int i, slot, offset, size;
1559         guint32 align;
1560         MonoMethodVar *vmv;
1561         MonoInst *inst;
1562         gint32 *offsets;
1563         GList *vars = NULL, *l;
1564         StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
1565         MonoType *t;
1566         int nvtypes;
1567         gboolean reuse_slot;
1568
1569         if ((cfg->num_varinfo > 0) && MONO_VARINFO (cfg, 0)->interval)
1570                 return mono_allocate_stack_slots2 (cfg, backward, stack_size, stack_align);
1571
1572         scalar_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
1573         vtype_stack_slots = NULL;
1574         nvtypes = 0;
1575
1576         offsets = mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
1577         for (i = 0; i < cfg->num_varinfo; ++i)
1578                 offsets [i] = -1;
1579
1580         for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1581                 inst = cfg->varinfo [i];
1582                 vmv = MONO_VARINFO (cfg, i);
1583
1584                 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
1585                         continue;
1586
1587                 vars = g_list_prepend (vars, vmv);
1588         }
1589
1590         vars = mono_varlist_sort (cfg, vars, 0);
1591         offset = 0;
1592         *stack_align = sizeof(mgreg_t);
1593         for (l = vars; l; l = l->next) {
1594                 vmv = l->data;
1595                 inst = cfg->varinfo [vmv->idx];
1596
1597                 t = mono_type_get_underlying_type (inst->inst_vtype);
1598                 if (cfg->gsharedvt && mini_is_gsharedvt_variable_type (t))
1599                         continue;
1600
1601                 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
1602                 * pinvoke wrappers when they call functions returning structures */
1603                 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (t) && t->type != MONO_TYPE_TYPEDBYREF) {
1604                         size = mono_class_native_size (mono_class_from_mono_type (t), &align);
1605                 } else {
1606                         int ialign;
1607
1608                         size = mini_type_stack_size (t, &ialign);
1609                         align = ialign;
1610
1611                         if (mono_class_from_mono_type (t)->exception_type)
1612                                 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
1613
1614                         if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (t)))
1615                                 align = 16;
1616                 }
1617
1618                 reuse_slot = TRUE;
1619                 if (cfg->disable_reuse_stack_slots)
1620                         reuse_slot = FALSE;
1621
1622                 t = mini_get_underlying_type (t);
1623                 switch (t->type) {
1624                 case MONO_TYPE_GENERICINST:
1625                         if (!mono_type_generic_inst_is_valuetype (t)) {
1626                                 slot_info = &scalar_stack_slots [t->type];
1627                                 break;
1628                         }
1629                         /* Fall through */
1630                 case MONO_TYPE_VALUETYPE:
1631                         if (!vtype_stack_slots)
1632                                 vtype_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * 256);
1633                         for (i = 0; i < nvtypes; ++i)
1634                                 if (t->data.klass == vtype_stack_slots [i].vtype)
1635                                         break;
1636                         if (i < nvtypes)
1637                                 slot_info = &vtype_stack_slots [i];
1638                         else {
1639                                 g_assert (nvtypes < 256);
1640                                 vtype_stack_slots [nvtypes].vtype = t->data.klass;
1641                                 slot_info = &vtype_stack_slots [nvtypes];
1642                                 nvtypes ++;
1643                         }
1644                         if (cfg->disable_reuse_ref_stack_slots)
1645                                 reuse_slot = FALSE;
1646                         break;
1647
1648                 case MONO_TYPE_PTR:
1649                 case MONO_TYPE_I:
1650                 case MONO_TYPE_U:
1651 #if SIZEOF_VOID_P == 4
1652                 case MONO_TYPE_I4:
1653 #else
1654                 case MONO_TYPE_I8:
1655 #endif
1656                         if (cfg->disable_ref_noref_stack_slot_share) {
1657                                 slot_info = &scalar_stack_slots [MONO_TYPE_I];
1658                                 break;
1659                         }
1660                         /* Fall through */
1661
1662                 case MONO_TYPE_CLASS:
1663                 case MONO_TYPE_OBJECT:
1664                 case MONO_TYPE_ARRAY:
1665                 case MONO_TYPE_SZARRAY:
1666                 case MONO_TYPE_STRING:
1667                         /* Share non-float stack slots of the same size */
1668                         slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
1669                         if (cfg->disable_reuse_ref_stack_slots)
1670                                 reuse_slot = FALSE;
1671                         break;
1672                 case MONO_TYPE_VAR:
1673                 case MONO_TYPE_MVAR:
1674                         slot_info = &scalar_stack_slots [t->type];
1675                         break;
1676                 default:
1677                         slot_info = &scalar_stack_slots [t->type];
1678                         break;
1679                 }
1680
1681                 slot = 0xffffff;
1682                 if (cfg->comp_done & MONO_COMP_LIVENESS) {
1683                         //printf ("START  %2d %08x %08x\n",  vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
1684                         
1685                         /* expire old intervals in active */
1686                         while (slot_info->active) {
1687                                 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
1688
1689                                 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
1690                                         break;
1691
1692                                 //printf ("EXPIR  %2d %08x %08x C%d R%d\n", amv->idx, amv->range.first_use.abs_pos, amv->range.last_use.abs_pos, amv->spill_costs, amv->reg);
1693
1694                                 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
1695                                 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
1696                         }
1697
1698                         /* 
1699                          * This also handles the case when the variable is used in an
1700                          * exception region, as liveness info is not computed there.
1701                          */
1702                         /* 
1703                          * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
1704                          * opcodes.
1705                          */
1706                         if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
1707                                 if (slot_info->slots) {
1708                                         slot = GPOINTER_TO_INT (slot_info->slots->data);
1709
1710                                         slot_info->slots = slot_info->slots->next;
1711                                 }
1712
1713                                 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
1714                         }
1715                 }
1716
1717                 {
1718                         static int count = 0;
1719                         count ++;
1720
1721                         /*
1722                         if (count == atoi (g_getenv ("COUNT")))
1723                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
1724                         if (count > atoi (g_getenv ("COUNT")))
1725                                 slot = 0xffffff;
1726                         else {
1727                                 mono_print_ins (inst);
1728                                 }
1729                         */
1730                 }
1731
1732                 if (inst->flags & MONO_INST_LMF) {
1733                         /*
1734                          * This variable represents a MonoLMF structure, which has no corresponding
1735                          * CLR type, so hard-code its size/alignment.
1736                          */
1737                         size = sizeof (MonoLMF);
1738                         align = sizeof (mgreg_t);
1739                         reuse_slot = FALSE;
1740                 }
1741
1742                 if (!reuse_slot)
1743                         slot = 0xffffff;
1744
1745                 if (slot == 0xffffff) {
1746                         /*
1747                          * Allways allocate valuetypes to sizeof (gpointer) to allow more
1748                          * efficient copying (and to work around the fact that OP_MEMCPY
1749                          * and OP_MEMSET ignores alignment).
1750                          */
1751                         if (MONO_TYPE_ISSTRUCT (t)) {
1752                                 align = MAX (align, sizeof (gpointer));
1753                                 align = MAX (align, mono_class_min_align (mono_class_from_mono_type (t)));
1754                                 /* 
1755                                  * Align the size too so the code generated for passing vtypes in
1756                                  * registers doesn't overwrite random locals.
1757                                  */
1758                                 size = (size + (align - 1)) & ~(align -1);
1759                         }
1760
1761                         if (backward) {
1762                                 offset += size;
1763                                 offset += align - 1;
1764                                 offset &= ~(align - 1);
1765                                 slot = offset;
1766                         }
1767                         else {
1768                                 offset += align - 1;
1769                                 offset &= ~(align - 1);
1770                                 slot = offset;
1771                                 offset += size;
1772                         }
1773
1774                         *stack_align = MAX (*stack_align, align);
1775                 }
1776
1777                 offsets [vmv->idx] = slot;
1778         }
1779         g_list_free (vars);
1780         for (i = 0; i < MONO_TYPE_PINNED; ++i) {
1781                 if (scalar_stack_slots [i].active)
1782                         g_list_free (scalar_stack_slots [i].active);
1783         }
1784         for (i = 0; i < nvtypes; ++i) {
1785                 if (vtype_stack_slots [i].active)
1786                         g_list_free (vtype_stack_slots [i].active);
1787         }
1788
1789         cfg->stat_locals_stack_size += offset;
1790
1791         *stack_size = offset;
1792         return offsets;
1793 }
1794
1795 #else
1796
1797 gint32*
1798 mono_allocate_stack_slots (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
1799 {
1800         g_assert_not_reached ();
1801         return NULL;
1802 }
1803
1804 #endif /* DISABLE_JIT */
1805
1806 #define EMUL_HIT_SHIFT 3
1807 #define EMUL_HIT_MASK ((1 << EMUL_HIT_SHIFT) - 1)
1808 /* small hit bitmap cache */
1809 static mono_byte emul_opcode_hit_cache [(OP_LAST>>EMUL_HIT_SHIFT) + 1] = {0};
1810 static short emul_opcode_num = 0;
1811 static short emul_opcode_alloced = 0;
1812 static short *emul_opcode_opcodes;
1813 static MonoJitICallInfo **emul_opcode_map;
1814
1815 MonoJitICallInfo *
1816 mono_find_jit_opcode_emulation (int opcode)
1817 {
1818         g_assert (opcode >= 0 && opcode <= OP_LAST);
1819         if (emul_opcode_hit_cache [opcode >> (EMUL_HIT_SHIFT + 3)] & (1 << (opcode & EMUL_HIT_MASK))) {
1820                 int i;
1821                 for (i = 0; i < emul_opcode_num; ++i) {
1822                         if (emul_opcode_opcodes [i] == opcode)
1823                                 return emul_opcode_map [i];
1824                 }
1825         }
1826         return NULL;
1827 }
1828
1829 void
1830 mini_register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, const char *symbol, gboolean no_throw)
1831 {
1832         MonoJitICallInfo *info;
1833         MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
1834
1835         g_assert (!sig->hasthis);
1836         g_assert (sig->param_count < 3);
1837
1838         /* Opcode emulation functions are assumed to don't call mono_raise_exception () */
1839         info = mono_register_jit_icall_full (func, name, sig, no_throw, TRUE, symbol);
1840
1841         if (emul_opcode_num >= emul_opcode_alloced) {
1842                 int incr = emul_opcode_alloced? emul_opcode_alloced/2: 16;
1843                 emul_opcode_alloced += incr;
1844                 emul_opcode_map = g_realloc (emul_opcode_map, sizeof (emul_opcode_map [0]) * emul_opcode_alloced);
1845                 emul_opcode_opcodes = g_realloc (emul_opcode_opcodes, sizeof (emul_opcode_opcodes [0]) * emul_opcode_alloced);
1846         }
1847         emul_opcode_map [emul_opcode_num] = info;
1848         emul_opcode_opcodes [emul_opcode_num] = opcode;
1849         emul_opcode_num++;
1850         emul_opcode_hit_cache [opcode >> (EMUL_HIT_SHIFT + 3)] |= (1 << (opcode & EMUL_HIT_MASK));
1851 }
1852
1853 static void
1854 print_dfn (MonoCompile *cfg) {
1855         int i, j;
1856         char *code;
1857         MonoBasicBlock *bb;
1858         MonoInst *c;
1859
1860         {
1861                 char *method_name = mono_method_full_name (cfg->method, TRUE);
1862                 g_print ("IR code for method %s\n", method_name);
1863                 g_free (method_name);
1864         }
1865
1866         for (i = 0; i < cfg->num_bblocks; ++i) {
1867                 bb = cfg->bblocks [i];
1868                 /*if (bb->cil_code) {
1869                         char* code1, *code2;
1870                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
1871                         if (bb->last_ins->cil_code)
1872                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
1873                         else
1874                                 code2 = g_strdup ("");
1875
1876                         code1 [strlen (code1) - 1] = 0;
1877                         code = g_strdup_printf ("%s -> %s", code1, code2);
1878                         g_free (code1);
1879                         g_free (code2);
1880                 } else*/
1881                         code = g_strdup ("\n");
1882                 g_print ("\nBB%d (%d) (len: %d): %s", bb->block_num, i, bb->cil_length, code);
1883                 MONO_BB_FOR_EACH_INS (bb, c) {
1884                         mono_print_ins_index (-1, c);
1885                 }
1886
1887                 g_print ("\tprev:");
1888                 for (j = 0; j < bb->in_count; ++j) {
1889                         g_print (" BB%d", bb->in_bb [j]->block_num);
1890                 }
1891                 g_print ("\t\tsucc:");
1892                 for (j = 0; j < bb->out_count; ++j) {
1893                         g_print (" BB%d", bb->out_bb [j]->block_num);
1894                 }
1895                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
1896
1897                 if (bb->idom)
1898                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
1899
1900                 if (bb->dominators)
1901                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
1902                 if (bb->dfrontier)
1903                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
1904                 g_free (code);
1905         }
1906
1907         g_print ("\n");
1908 }
1909
1910 void
1911 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
1912 {
1913         MONO_ADD_INS (bb, inst);
1914 }
1915
1916 void
1917 mono_bblock_insert_after_ins (MonoBasicBlock *bb, MonoInst *ins, MonoInst *ins_to_insert)
1918 {
1919         if (ins == NULL) {
1920                 ins = bb->code;
1921                 bb->code = ins_to_insert;
1922
1923                 /* Link with next */
1924                 ins_to_insert->next = ins;
1925                 if (ins)
1926                         ins->prev = ins_to_insert;
1927
1928                 if (bb->last_ins == NULL)
1929                         bb->last_ins = ins_to_insert;
1930         } else {
1931                 /* Link with next */
1932                 ins_to_insert->next = ins->next;
1933                 if (ins->next)
1934                         ins->next->prev = ins_to_insert;
1935
1936                 /* Link with previous */
1937                 ins->next = ins_to_insert;
1938                 ins_to_insert->prev = ins;
1939
1940                 if (bb->last_ins == ins)
1941                         bb->last_ins = ins_to_insert;
1942         }
1943 }
1944
1945 void
1946 mono_bblock_insert_before_ins (MonoBasicBlock *bb, MonoInst *ins, MonoInst *ins_to_insert)
1947 {
1948         if (ins == NULL) {
1949                 ins = bb->code;
1950                 if (ins)
1951                         ins->prev = ins_to_insert;
1952                 bb->code = ins_to_insert;
1953                 ins_to_insert->next = ins;
1954                 if (bb->last_ins == NULL)
1955                         bb->last_ins = ins_to_insert;
1956         } else {
1957                 /* Link with previous */
1958                 if (ins->prev)
1959                         ins->prev->next = ins_to_insert;
1960                 ins_to_insert->prev = ins->prev;
1961
1962                 /* Link with next */
1963                 ins->prev = ins_to_insert;
1964                 ins_to_insert->next = ins;
1965
1966                 if (bb->code == ins)
1967                         bb->code = ins_to_insert;
1968         }
1969 }
1970
1971 /*
1972  * mono_verify_bblock:
1973  *
1974  *   Verify that the next and prev pointers are consistent inside the instructions in BB.
1975  */
1976 void
1977 mono_verify_bblock (MonoBasicBlock *bb)
1978 {
1979         MonoInst *ins, *prev;
1980
1981         prev = NULL;
1982         for (ins = bb->code; ins; ins = ins->next) {
1983                 g_assert (ins->prev == prev);
1984                 prev = ins;
1985         }
1986         if (bb->last_ins)
1987                 g_assert (!bb->last_ins->next);
1988 }
1989
1990 /*
1991  * mono_verify_cfg:
1992  *
1993  *   Perform consistency checks on the JIT data structures and the IR
1994  */
1995 void
1996 mono_verify_cfg (MonoCompile *cfg)
1997 {
1998         MonoBasicBlock *bb;
1999
2000         for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2001                 mono_verify_bblock (bb);
2002 }
2003
2004 void
2005 mono_destroy_compile (MonoCompile *cfg)
2006 {
2007 #ifndef DISABLE_JIT
2008         GSList *l;
2009
2010         if (cfg->header)
2011                 mono_metadata_free_mh (cfg->header);
2012         //mono_mempool_stats (cfg->mempool);
2013         mono_free_loop_info (cfg);
2014         if (cfg->rs)
2015                 mono_regstate_free (cfg->rs);
2016         if (cfg->spvars)
2017                 g_hash_table_destroy (cfg->spvars);
2018         if (cfg->exvars)
2019                 g_hash_table_destroy (cfg->exvars);
2020         for (l = cfg->headers_to_free; l; l = l->next)
2021                 mono_metadata_free_mh (l->data);
2022         g_list_free (cfg->ldstr_list);
2023         g_hash_table_destroy (cfg->token_info_hash);
2024         if (cfg->abs_patches)
2025                 g_hash_table_destroy (cfg->abs_patches);
2026         mono_mempool_destroy (cfg->mempool);
2027
2028         mono_debug_free_method (cfg);
2029
2030         g_free (cfg->varinfo);
2031         g_free (cfg->vars);
2032         g_free (cfg->exception_message);
2033         g_free (cfg);
2034 #endif
2035 }
2036
2037 #ifndef DISABLE_JIT
2038
2039 static MonoInst*
2040 mono_create_tls_get_offset (MonoCompile *cfg, int offset)
2041 {
2042         MonoInst* ins;
2043
2044         if (!MONO_ARCH_HAVE_TLS_GET)
2045                 return NULL;
2046
2047         if (offset == -1)
2048                 return NULL;
2049
2050         MONO_INST_NEW (cfg, ins, OP_TLS_GET);
2051         ins->dreg = mono_alloc_preg (cfg);
2052         ins->inst_offset = offset;
2053         return ins;
2054 }
2055
2056 gboolean
2057 mini_tls_get_supported (MonoCompile *cfg, MonoTlsKey key)
2058 {
2059         if (!MONO_ARCH_HAVE_TLS_GET)
2060                 return FALSE;
2061
2062         if (cfg->compile_aot)
2063                 return ARCH_HAVE_TLS_GET_REG;
2064         else
2065                 return mini_get_tls_offset (key) != -1;
2066 }
2067
2068 MonoInst*
2069 mono_create_tls_get (MonoCompile *cfg, MonoTlsKey key)
2070 {
2071         if (!MONO_ARCH_HAVE_TLS_GET)
2072                 return NULL;
2073
2074         /*
2075          * TLS offsets might be different at AOT time, so load them from a GOT slot and
2076          * use a different opcode.
2077          */
2078         if (cfg->compile_aot) {
2079                 if (ARCH_HAVE_TLS_GET_REG) {
2080                         MonoInst *ins, *c;
2081
2082                         EMIT_NEW_TLS_OFFSETCONST (cfg, c, key);
2083                         MONO_INST_NEW (cfg, ins, OP_TLS_GET_REG);
2084                         ins->dreg = mono_alloc_preg (cfg);
2085                         ins->sreg1 = c->dreg;
2086                         return ins;
2087                 } else {
2088                         return NULL;
2089                 }
2090         }
2091
2092         return mono_create_tls_get_offset (cfg, mini_get_tls_offset (key));
2093 }
2094
2095 MonoInst*
2096 mono_get_jit_tls_intrinsic (MonoCompile *cfg)
2097 {
2098         return mono_create_tls_get (cfg, TLS_KEY_JIT_TLS);
2099 }
2100
2101 MonoInst*
2102 mono_get_domain_intrinsic (MonoCompile* cfg)
2103 {
2104         return mono_create_tls_get (cfg, TLS_KEY_DOMAIN);
2105 }
2106
2107 MonoInst*
2108 mono_get_thread_intrinsic (MonoCompile* cfg)
2109 {
2110         return mono_create_tls_get (cfg, TLS_KEY_THREAD);
2111 }
2112
2113 MonoInst*
2114 mono_get_lmf_intrinsic (MonoCompile* cfg)
2115 {
2116         return mono_create_tls_get (cfg, TLS_KEY_LMF);
2117 }
2118
2119 MonoInst*
2120 mono_get_lmf_addr_intrinsic (MonoCompile* cfg)
2121 {
2122         return mono_create_tls_get (cfg, TLS_KEY_LMF_ADDR);
2123 }
2124
2125 #endif /* !DISABLE_JIT */
2126
2127
2128 void
2129 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
2130 {
2131         MonoJumpInfo *ji = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfo));
2132
2133         ji->ip.i = ip;
2134         ji->type = type;
2135         ji->data.target = target;
2136         ji->next = cfg->patch_info;
2137
2138         cfg->patch_info = ji;
2139 }
2140
2141 void
2142 mono_add_patch_info_rel (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target, int relocation)
2143 {
2144         MonoJumpInfo *ji = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfo));
2145
2146         ji->ip.i = ip;
2147         ji->type = type;
2148         ji->relocation = relocation;
2149         ji->data.target = target;
2150         ji->next = cfg->patch_info;
2151
2152         cfg->patch_info = ji;
2153 }
2154
2155 void
2156 mono_remove_patch_info (MonoCompile *cfg, int ip)
2157 {
2158         MonoJumpInfo **ji = &cfg->patch_info;
2159
2160         while (*ji) {
2161                 if ((*ji)->ip.i == ip)
2162                         *ji = (*ji)->next;
2163                 else
2164                         ji = &((*ji)->next);
2165         }
2166 }
2167
2168 void
2169 mono_add_seq_point (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, int native_offset)
2170 {
2171         ins->inst_offset = native_offset;
2172         g_ptr_array_add (cfg->seq_points, ins);
2173         if (bb) {
2174                 bb->seq_points = g_slist_prepend_mempool (cfg->mempool, bb->seq_points, ins);
2175                 bb->last_seq_point = ins;
2176         }
2177 }
2178
2179 void
2180 mono_add_var_location (MonoCompile *cfg, MonoInst *var, gboolean is_reg, int reg, int offset, int from, int to)
2181 {
2182         MonoDwarfLocListEntry *entry = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoDwarfLocListEntry));
2183
2184         if (is_reg)
2185                 g_assert (offset == 0);
2186
2187         entry->is_reg = is_reg;
2188         entry->reg = reg;
2189         entry->offset = offset;
2190         entry->from = from;
2191         entry->to = to;
2192
2193         if (var == cfg->args [0])
2194                 cfg->this_loclist = g_slist_append_mempool (cfg->mempool, cfg->this_loclist, entry);
2195         else if (var == cfg->rgctx_var)
2196                 cfg->rgctx_loclist = g_slist_append_mempool (cfg->mempool, cfg->rgctx_loclist, entry);
2197 }
2198
2199 #ifndef DISABLE_JIT
2200
2201 static void
2202 mono_compile_create_vars (MonoCompile *cfg)
2203 {
2204         MonoMethodSignature *sig;
2205         MonoMethodHeader *header;
2206         int i;
2207
2208         header = cfg->header;
2209
2210         sig = mono_method_signature (cfg->method);
2211         
2212         if (!MONO_TYPE_IS_VOID (sig->ret)) {
2213                 cfg->ret = mono_compile_create_var (cfg, sig->ret, OP_ARG);
2214                 /* Inhibit optimizations */
2215                 cfg->ret->flags |= MONO_INST_VOLATILE;
2216         }
2217         if (cfg->verbose_level > 2)
2218                 g_print ("creating vars\n");
2219
2220         cfg->args = mono_mempool_alloc0 (cfg->mempool, (sig->param_count + sig->hasthis) * sizeof (MonoInst*));
2221
2222         if (sig->hasthis)
2223                 cfg->args [0] = mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
2224
2225         for (i = 0; i < sig->param_count; ++i) {
2226                 cfg->args [i + sig->hasthis] = mono_compile_create_var (cfg, sig->params [i], OP_ARG);
2227         }
2228
2229         if (cfg->verbose_level > 2) {
2230                 if (cfg->ret) {
2231                         printf ("\treturn : ");
2232                         mono_print_ins (cfg->ret);
2233                 }
2234
2235                 if (sig->hasthis) {
2236                         printf ("\tthis: ");
2237                         mono_print_ins (cfg->args [0]);
2238                 }
2239
2240                 for (i = 0; i < sig->param_count; ++i) {
2241                         printf ("\targ [%d]: ", i);
2242                         mono_print_ins (cfg->args [i + sig->hasthis]);
2243                 }
2244         }
2245
2246         cfg->locals_start = cfg->num_varinfo;
2247         cfg->locals = mono_mempool_alloc0 (cfg->mempool, header->num_locals * sizeof (MonoInst*));
2248
2249         if (cfg->verbose_level > 2)
2250                 g_print ("creating locals\n");
2251
2252         for (i = 0; i < header->num_locals; ++i)
2253                 cfg->locals [i] = mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
2254
2255         if (cfg->verbose_level > 2)
2256                 g_print ("locals done\n");
2257
2258         mono_arch_create_vars (cfg);
2259
2260         if (cfg->method->save_lmf && cfg->create_lmf_var) {
2261                 MonoInst *lmf_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
2262                 lmf_var->flags |= MONO_INST_VOLATILE;
2263                 lmf_var->flags |= MONO_INST_LMF;
2264                 cfg->lmf_var = lmf_var;
2265         }
2266 }
2267
2268 void
2269 mono_print_code (MonoCompile *cfg, const char* msg)
2270 {
2271         MonoBasicBlock *bb;
2272         
2273         for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2274                 mono_print_bb (bb, msg);
2275 }
2276
2277 static void
2278 mono_postprocess_patches (MonoCompile *cfg)
2279 {
2280         MonoJumpInfo *patch_info;
2281         int i;
2282
2283         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2284                 switch (patch_info->type) {
2285                 case MONO_PATCH_INFO_ABS: {
2286                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
2287
2288                         /*
2289                          * Change patches of type MONO_PATCH_INFO_ABS into patches describing the 
2290                          * absolute address.
2291                          */
2292                         if (info) {
2293                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
2294                                 /* for these array methods we currently register the same function pointer
2295                                  * since it's a vararg function. But this means that mono_find_jit_icall_by_addr ()
2296                                  * will return the incorrect one depending on the order they are registered.
2297                                  * See tests/test-arr.cs
2298                                  */
2299                                 if (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL) {
2300                                         patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
2301                                         patch_info->data.name = info->name;
2302                                 }
2303                         }
2304
2305                         if (patch_info->type == MONO_PATCH_INFO_ABS) {
2306                                 if (cfg->abs_patches) {
2307                                         MonoJumpInfo *abs_ji = g_hash_table_lookup (cfg->abs_patches, patch_info->data.target);
2308                                         if (abs_ji) {
2309                                                 patch_info->type = abs_ji->type;
2310                                                 patch_info->data.target = abs_ji->data.target;
2311                                         }
2312                                 }
2313                         }
2314
2315                         break;
2316                 }
2317                 case MONO_PATCH_INFO_SWITCH: {
2318                         gpointer *table;
2319 #if defined(__native_client__) && defined(__native_client_codegen__)
2320                         /* This memory will leak.  */
2321                         /* TODO: can we free this when  */
2322                         /* making the final jump table? */
2323                         table = g_malloc0 (sizeof(gpointer) * patch_info->data.table->table_size);
2324 #else
2325                         if (cfg->method->dynamic) {
2326                                 table = mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
2327                         } else {
2328                                 table = mono_domain_code_reserve (cfg->domain, sizeof (gpointer) * patch_info->data.table->table_size);
2329                         }
2330 #endif
2331
2332                         for (i = 0; i < patch_info->data.table->table_size; i++) {
2333                                 /* Might be NULL if the switch is eliminated */
2334                                 if (patch_info->data.table->table [i]) {
2335                                         g_assert (patch_info->data.table->table [i]->native_offset);
2336                                         table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
2337                                 } else {
2338                                         table [i] = NULL;
2339                                 }
2340                         }
2341                         patch_info->data.table->table = (MonoBasicBlock**)table;
2342                         break;
2343                 }
2344                 case MONO_PATCH_INFO_METHOD_JUMP: {
2345                         MonoJumpList *jlist;
2346                         MonoDomain *domain = cfg->domain;
2347                         unsigned char *ip = cfg->native_code + patch_info->ip.i;
2348 #if defined(__native_client__) && defined(__native_client_codegen__)
2349                         /* When this jump target gets evaluated, the method */
2350                         /* will be installed in the dynamic code section,   */
2351                         /* not at the location of cfg->native_code.         */
2352                         ip = nacl_inverse_modify_patch_target (cfg->native_code) + patch_info->ip.i;
2353 #endif
2354
2355                         mono_domain_lock (domain);
2356                         jlist = g_hash_table_lookup (domain_jit_info (domain)->jump_target_hash, patch_info->data.method);
2357                         if (!jlist) {
2358                                 jlist = mono_domain_alloc0 (domain, sizeof (MonoJumpList));
2359                                 g_hash_table_insert (domain_jit_info (domain)->jump_target_hash, patch_info->data.method, jlist);
2360                         }
2361                         jlist->list = g_slist_prepend (jlist->list, ip);
2362                         mono_domain_unlock (domain);
2363                         break;
2364                 }
2365                 default:
2366                         /* do nothing */
2367                         break;
2368                 }
2369         }
2370 }
2371
2372 void
2373 mono_codegen (MonoCompile *cfg)
2374 {
2375         MonoBasicBlock *bb;
2376         int max_epilog_size;
2377         guint8 *code;
2378         MonoDomain *code_domain;
2379         guint unwindlen = 0;
2380
2381         if (mono_using_xdebug)
2382                 /*
2383                  * Recent gdb versions have trouble processing symbol files containing
2384                  * overlapping address ranges, so allocate all code from the code manager
2385                  * of the root domain. (#666152).
2386                  */
2387                 code_domain = mono_get_root_domain ();
2388         else
2389                 code_domain = cfg->domain;
2390
2391 #if defined(__native_client_codegen__) && defined(__native_client__)
2392         void *code_dest;
2393
2394         /* This keeps patch targets from being transformed during
2395          * ordinary method compilation, for local branches and jumps.
2396          */
2397         nacl_allow_target_modification (FALSE);
2398 #endif
2399
2400         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2401                 cfg->spill_count = 0;
2402                 /* we reuse dfn here */
2403                 /* bb->dfn = bb_count++; */
2404
2405                 mono_arch_lowering_pass (cfg, bb);
2406
2407                 if (cfg->opt & MONO_OPT_PEEPHOLE)
2408                         mono_arch_peephole_pass_1 (cfg, bb);
2409
2410                 mono_local_regalloc (cfg, bb);
2411
2412                 if (cfg->opt & MONO_OPT_PEEPHOLE)
2413                         mono_arch_peephole_pass_2 (cfg, bb);
2414
2415                 if (cfg->gen_seq_points && !cfg->gen_sdb_seq_points)
2416                         mono_bb_deduplicate_op_il_seq_points (cfg, bb);
2417         }
2418
2419         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
2420                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
2421
2422         code = mono_arch_emit_prolog (cfg);
2423
2424         cfg->code_len = code - cfg->native_code;
2425         cfg->prolog_end = cfg->code_len;
2426         cfg->cfa_reg = cfg->cur_cfa_reg;
2427         cfg->cfa_offset = cfg->cur_cfa_offset;
2428
2429         mono_debug_open_method (cfg);
2430
2431         /* emit code all basic blocks */
2432         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2433                 bb->native_offset = cfg->code_len;
2434                 bb->real_native_offset = cfg->code_len;
2435                 //if ((bb == cfg->bb_entry) || !(bb->region == -1 && !bb->dfn))
2436                         mono_arch_output_basic_block (cfg, bb);
2437                 bb->native_length = cfg->code_len - bb->native_offset;
2438
2439                 if (bb == cfg->bb_exit) {
2440                         cfg->epilog_begin = cfg->code_len;
2441                         mono_arch_emit_epilog (cfg);
2442                         cfg->epilog_end = cfg->code_len;
2443                 }
2444         }
2445
2446 #ifdef __native_client_codegen__
2447         mono_nacl_fix_patches (cfg->native_code, cfg->patch_info);
2448 #endif
2449         mono_arch_emit_exceptions (cfg);
2450
2451         max_epilog_size = 0;
2452
2453         /* we always allocate code in cfg->domain->code_mp to increase locality */
2454         cfg->code_size = cfg->code_len + max_epilog_size;
2455 #ifdef __native_client_codegen__
2456         cfg->code_size = NACL_BUNDLE_ALIGN_UP (cfg->code_size);
2457 #endif
2458         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
2459
2460 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
2461         unwindlen = mono_arch_unwindinfo_get_size (cfg->arch.unwindinfo);
2462 #endif
2463
2464         if (cfg->method->dynamic) {
2465                 /* Allocate the code into a separate memory pool so it can be freed */
2466                 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
2467                 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
2468                 mono_domain_lock (cfg->domain);
2469                 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
2470                 mono_domain_unlock (cfg->domain);
2471
2472                 if (mono_using_xdebug)
2473                         /* See the comment for cfg->code_domain */
2474                         code = mono_domain_code_reserve (code_domain, cfg->code_size + cfg->thunk_area + unwindlen);
2475                 else
2476                         code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size + cfg->thunk_area + unwindlen);
2477         } else {
2478                 code = mono_domain_code_reserve (code_domain, cfg->code_size + cfg->thunk_area + unwindlen);
2479         }
2480 #if defined(__native_client_codegen__) && defined(__native_client__)
2481         nacl_allow_target_modification (TRUE);
2482 #endif
2483         if (cfg->thunk_area) {
2484                 cfg->thunks_offset = cfg->code_size + unwindlen;
2485                 cfg->thunks = code + cfg->thunks_offset;
2486                 memset (cfg->thunks, 0, cfg->thunk_area);
2487         }
2488
2489         g_assert (code);
2490         memcpy (code, cfg->native_code, cfg->code_len);
2491 #if defined(__default_codegen__)
2492         g_free (cfg->native_code);
2493 #elif defined(__native_client_codegen__)
2494         if (cfg->native_code_alloc) {
2495                 g_free (cfg->native_code_alloc);
2496                 cfg->native_code_alloc = 0;
2497         }
2498         else if (cfg->native_code) {
2499                 g_free (cfg->native_code);
2500         }
2501 #endif /* __native_client_codegen__ */
2502         cfg->native_code = code;
2503         code = cfg->native_code + cfg->code_len;
2504   
2505         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
2506         mono_postprocess_patches (cfg);
2507
2508 #ifdef VALGRIND_JIT_REGISTER_MAP
2509         if (valgrind_register){
2510                 char* nm = mono_method_full_name (cfg->method, TRUE);
2511                 VALGRIND_JIT_REGISTER_MAP (nm, cfg->native_code, cfg->native_code + cfg->code_len);
2512                 g_free (nm);
2513         }
2514 #endif
2515  
2516         if (cfg->verbose_level > 0) {
2517                 char* nm = mono_method_full_name (cfg->method, TRUE);
2518                 g_print ("Method %s emitted at %p to %p (code length %d) [%s]\n", 
2519                                  nm, 
2520                                  cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
2521                 g_free (nm);
2522         }
2523
2524         {
2525                 gboolean is_generic = FALSE;
2526
2527                 if (cfg->method->is_inflated || mono_method_get_generic_container (cfg->method) ||
2528                                 cfg->method->klass->generic_container || cfg->method->klass->generic_class) {
2529                         is_generic = TRUE;
2530                 }
2531
2532                 if (cfg->gshared)
2533                         g_assert (is_generic);
2534         }
2535
2536 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
2537         mono_arch_save_unwind_info (cfg);
2538 #endif
2539
2540 #if defined(__native_client_codegen__) && defined(__native_client__)
2541         if (!cfg->compile_aot) {
2542                 if (cfg->method->dynamic) {
2543                         code_dest = nacl_code_manager_get_code_dest(cfg->dynamic_info->code_mp, cfg->native_code);
2544                 } else {
2545                         code_dest = nacl_domain_get_code_dest(cfg->domain, cfg->native_code);
2546                 }
2547         }
2548 #endif
2549
2550 #if defined(__native_client_codegen__)
2551         mono_nacl_fix_patches (cfg->native_code, cfg->patch_info);
2552 #endif
2553
2554 #ifdef MONO_ARCH_HAVE_PATCH_CODE_NEW
2555         {
2556                 MonoJumpInfo *ji;
2557                 gpointer target;
2558
2559                 for (ji = cfg->patch_info; ji; ji = ji->next) {
2560                         if (cfg->compile_aot) {
2561                                 switch (ji->type) {
2562                                 case MONO_PATCH_INFO_BB:
2563                                 case MONO_PATCH_INFO_LABEL:
2564                                         break;
2565                                 default:
2566                                         /* No need to patch these */
2567                                         continue;
2568                                 }
2569                         }
2570
2571                         if (ji->type == MONO_PATCH_INFO_NONE)
2572                                 continue;
2573
2574                         target = mono_resolve_patch_target (cfg->method, cfg->domain, cfg->native_code, ji, cfg->run_cctors);
2575                         mono_arch_patch_code_new (cfg, cfg->domain, cfg->native_code, ji, target);
2576                 }
2577         }
2578 #else
2579         mono_arch_patch_code (cfg, cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
2580 #endif
2581
2582         if (cfg->method->dynamic) {
2583                 if (mono_using_xdebug)
2584                         mono_domain_code_commit (code_domain, cfg->native_code, cfg->code_size, cfg->code_len);
2585                 else
2586                         mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
2587         } else {
2588                 mono_domain_code_commit (code_domain, cfg->native_code, cfg->code_size, cfg->code_len);
2589         }
2590 #if defined(__native_client_codegen__) && defined(__native_client__)
2591         cfg->native_code = code_dest;
2592 #endif
2593         mono_profiler_code_buffer_new (cfg->native_code, cfg->code_len, MONO_PROFILER_CODE_BUFFER_METHOD, cfg->method);
2594         
2595         mono_arch_flush_icache (cfg->native_code, cfg->code_len);
2596
2597         mono_debug_close_method (cfg);
2598
2599 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
2600         mono_arch_unwindinfo_install_unwind_info (&cfg->arch.unwindinfo, cfg->native_code, cfg->code_len);
2601 #endif
2602 }
2603
2604 static void
2605 compute_reachable (MonoBasicBlock *bb)
2606 {
2607         int i;
2608
2609         if (!(bb->flags & BB_VISITED)) {
2610                 bb->flags |= BB_VISITED;
2611                 for (i = 0; i < bb->out_count; ++i)
2612                         compute_reachable (bb->out_bb [i]);
2613         }
2614 }
2615
2616 static void
2617 mono_handle_out_of_line_bblock (MonoCompile *cfg)
2618 {
2619         MonoBasicBlock *bb;
2620         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2621                 if (bb->next_bb && bb->next_bb->out_of_line && bb->last_ins && !MONO_IS_BRANCH_OP (bb->last_ins)) {
2622                         MonoInst *ins;
2623                         MONO_INST_NEW (cfg, ins, OP_BR);
2624                         MONO_ADD_INS (bb, ins);
2625                         ins->inst_target_bb = bb->next_bb;
2626                 }
2627         }
2628 }
2629
2630 #endif /* #ifndef DISABLE_JIT */
2631
2632 static MonoJitInfo*
2633 create_jit_info_for_trampoline (MonoMethod *wrapper, MonoTrampInfo *info)
2634 {
2635         MonoDomain *domain = mono_get_root_domain ();
2636         MonoJitInfo *jinfo;
2637         guint8 *uw_info;
2638         guint32 info_len;
2639
2640         if (info->uw_info) {
2641                 uw_info = info->uw_info;
2642                 info_len = info->uw_info_len;
2643         } else {
2644                 uw_info = mono_unwind_ops_encode (info->unwind_ops, &info_len);
2645         }
2646
2647         jinfo = mono_domain_alloc0 (domain, MONO_SIZEOF_JIT_INFO);
2648         jinfo->d.method = wrapper;
2649         jinfo->code_start = info->code;
2650         jinfo->code_size = info->code_size;
2651         jinfo->unwind_info = mono_cache_unwind_info (uw_info, info_len);
2652
2653         if (!info->uw_info)
2654                 g_free (uw_info);
2655
2656         return jinfo;
2657 }
2658
2659 #ifndef DISABLE_JIT
2660
2661 static MonoJitInfo*
2662 create_jit_info (MonoCompile *cfg, MonoMethod *method_to_compile)
2663 {
2664         GSList *tmp;
2665         MonoMethodHeader *header;
2666         MonoJitInfo *jinfo;
2667         MonoJitInfoFlags flags = JIT_INFO_NONE;
2668         int num_clauses, num_holes = 0;
2669         guint32 stack_size = 0;
2670
2671         g_assert (method_to_compile == cfg->method);
2672         header = cfg->header;
2673
2674         if (cfg->gshared)
2675                 flags |= JIT_INFO_HAS_GENERIC_JIT_INFO;
2676
2677         if (cfg->arch_eh_jit_info) {
2678                 MonoJitArgumentInfo *arg_info;
2679                 MonoMethodSignature *sig = mono_method_signature (cfg->method_to_register);
2680
2681                 /*
2682                  * This cannot be computed during stack walking, as
2683                  * mono_arch_get_argument_info () is not signal safe.
2684                  */
2685                 arg_info = g_newa (MonoJitArgumentInfo, sig->param_count + 1);
2686                 stack_size = mono_arch_get_argument_info (sig, sig->param_count, arg_info);
2687
2688                 if (stack_size)
2689                         flags |= JIT_INFO_HAS_ARCH_EH_INFO;
2690         }
2691
2692         if (cfg->has_unwind_info_for_epilog && !(flags & JIT_INFO_HAS_ARCH_EH_INFO))
2693                 flags |= JIT_INFO_HAS_ARCH_EH_INFO;
2694
2695         if (cfg->thunk_area)
2696                 flags |= JIT_INFO_HAS_THUNK_INFO;
2697
2698         if (cfg->try_block_holes) {
2699                 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
2700                         TryBlockHole *hole = tmp->data;
2701                         MonoExceptionClause *ec = hole->clause;
2702                         int hole_end = hole->basic_block->native_offset + hole->basic_block->native_length;
2703                         MonoBasicBlock *clause_last_bb = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
2704                         g_assert (clause_last_bb);
2705
2706                         /* Holes at the end of a try region can be represented by simply reducing the size of the block itself.*/
2707                         if (clause_last_bb->native_offset != hole_end)
2708                                 ++num_holes;
2709                 }
2710                 if (num_holes)
2711                         flags |= JIT_INFO_HAS_TRY_BLOCK_HOLES;
2712                 if (G_UNLIKELY (cfg->verbose_level >= 4))
2713                         printf ("Number of try block holes %d\n", num_holes);
2714         }
2715
2716         if (COMPILE_LLVM (cfg))
2717                 num_clauses = cfg->llvm_ex_info_len;
2718         else
2719                 num_clauses = header->num_clauses;
2720
2721         if (cfg->method->dynamic)
2722                 jinfo = g_malloc0 (mono_jit_info_size (flags, num_clauses, num_holes));
2723         else
2724                 jinfo = mono_domain_alloc0 (cfg->domain, mono_jit_info_size (flags, num_clauses, num_holes));
2725         mono_jit_info_init (jinfo, cfg->method_to_register, cfg->native_code, cfg->code_len, flags, num_clauses, num_holes);
2726         jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
2727
2728         if (COMPILE_LLVM (cfg))
2729                 jinfo->from_llvm = TRUE;
2730
2731         if (cfg->gshared) {
2732                 MonoInst *inst;
2733                 MonoGenericJitInfo *gi;
2734                 GSList *loclist = NULL;
2735
2736                 gi = mono_jit_info_get_generic_jit_info (jinfo);
2737                 g_assert (gi);
2738
2739                 if (cfg->method->dynamic)
2740                         gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
2741                 else
2742                         gi->generic_sharing_context = mono_domain_alloc0 (cfg->domain, sizeof (MonoGenericSharingContext));
2743                 mini_init_gsctx (cfg->method->dynamic ? NULL : cfg->domain, NULL, cfg->gsctx_context, gi->generic_sharing_context);
2744
2745                 if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
2746                                 mini_method_get_context (method_to_compile)->method_inst ||
2747                                 method_to_compile->klass->valuetype) {
2748                         g_assert (cfg->rgctx_var);
2749                 }
2750
2751                 gi->has_this = 1;
2752
2753                 if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
2754                                 mini_method_get_context (method_to_compile)->method_inst ||
2755                                 method_to_compile->klass->valuetype) {
2756                         inst = cfg->rgctx_var;
2757                         if (!COMPILE_LLVM (cfg))
2758                                 g_assert (inst->opcode == OP_REGOFFSET);
2759                         loclist = cfg->rgctx_loclist;
2760                 } else {
2761                         inst = cfg->args [0];
2762                         loclist = cfg->this_loclist;
2763                 }
2764
2765                 if (loclist) {
2766                         /* Needed to handle async exceptions */
2767                         GSList *l;
2768                         int i;
2769
2770                         gi->nlocs = g_slist_length (loclist);
2771                         if (cfg->method->dynamic)
2772                                 gi->locations = g_malloc0 (gi->nlocs * sizeof (MonoDwarfLocListEntry));
2773                         else
2774                                 gi->locations = mono_domain_alloc0 (cfg->domain, gi->nlocs * sizeof (MonoDwarfLocListEntry));
2775                         i = 0;
2776                         for (l = loclist; l; l = l->next) {
2777                                 memcpy (&(gi->locations [i]), l->data, sizeof (MonoDwarfLocListEntry));
2778                                 i ++;
2779                         }
2780                 }
2781
2782                 if (COMPILE_LLVM (cfg)) {
2783                         g_assert (cfg->llvm_this_reg != -1);
2784                         gi->this_in_reg = 0;
2785                         gi->this_reg = cfg->llvm_this_reg;
2786                         gi->this_offset = cfg->llvm_this_offset;
2787                 } else if (inst->opcode == OP_REGVAR) {
2788                         gi->this_in_reg = 1;
2789                         gi->this_reg = inst->dreg;
2790                 } else {
2791                         g_assert (inst->opcode == OP_REGOFFSET);
2792 #ifdef TARGET_X86
2793                         g_assert (inst->inst_basereg == X86_EBP);
2794 #elif defined(TARGET_AMD64)
2795                         g_assert (inst->inst_basereg == X86_EBP || inst->inst_basereg == X86_ESP);
2796 #endif
2797                         g_assert (inst->inst_offset >= G_MININT32 && inst->inst_offset <= G_MAXINT32);
2798
2799                         gi->this_in_reg = 0;
2800                         gi->this_reg = inst->inst_basereg;
2801                         gi->this_offset = inst->inst_offset;
2802                 }
2803         }
2804
2805         if (num_holes) {
2806                 MonoTryBlockHoleTableJitInfo *table;
2807                 int i;
2808
2809                 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
2810                 table->num_holes = (guint16)num_holes;
2811                 i = 0;
2812                 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
2813                         guint32 start_bb_offset;
2814                         MonoTryBlockHoleJitInfo *hole;
2815                         TryBlockHole *hole_data = tmp->data;
2816                         MonoExceptionClause *ec = hole_data->clause;
2817                         int hole_end = hole_data->basic_block->native_offset + hole_data->basic_block->native_length;
2818                         MonoBasicBlock *clause_last_bb = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
2819                         g_assert (clause_last_bb);
2820
2821                         /* Holes at the end of a try region can be represented by simply reducing the size of the block itself.*/
2822                         if (clause_last_bb->native_offset == hole_end)
2823                                 continue;
2824
2825                         start_bb_offset = hole_data->start_offset - hole_data->basic_block->native_offset;
2826                         hole = &table->holes [i++];
2827                         hole->clause = hole_data->clause - &header->clauses [0];
2828                         hole->offset = (guint32)hole_data->start_offset;
2829                         hole->length = (guint16)(hole_data->basic_block->native_length - start_bb_offset);
2830
2831                         if (G_UNLIKELY (cfg->verbose_level >= 4))
2832                                 printf ("\tTry block hole at eh clause %d offset %x length %x\n", hole->clause, hole->offset, hole->length);
2833                 }
2834                 g_assert (i == num_holes);
2835         }
2836
2837         if (jinfo->has_arch_eh_info) {
2838                 MonoArchEHJitInfo *info;
2839
2840                 info = mono_jit_info_get_arch_eh_info (jinfo);
2841
2842                 info->stack_size = stack_size;
2843         }
2844
2845         if (cfg->thunk_area) {
2846                 MonoThunkJitInfo *info;
2847
2848                 info = mono_jit_info_get_thunk_info (jinfo);
2849                 info->thunks_offset = cfg->thunks_offset;
2850                 info->thunks_size = cfg->thunk_area;
2851         }
2852
2853         if (COMPILE_LLVM (cfg)) {
2854                 if (num_clauses)
2855                         memcpy (&jinfo->clauses [0], &cfg->llvm_ex_info [0], num_clauses * sizeof (MonoJitExceptionInfo));
2856         } else if (header->num_clauses) {
2857                 int i;
2858
2859                 for (i = 0; i < header->num_clauses; i++) {
2860                         MonoExceptionClause *ec = &header->clauses [i];
2861                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
2862                         MonoBasicBlock *tblock;
2863                         MonoInst *exvar, *spvar;
2864
2865                         ei->flags = ec->flags;
2866
2867                         if (G_UNLIKELY (cfg->verbose_level >= 4))
2868                                 printf ("IL clause: try 0x%x-0x%x handler 0x%x-0x%x filter 0x%x\n", ec->try_offset, ec->try_offset + ec->try_len, ec->handler_offset, ec->handler_offset + ec->handler_len, ec->flags == MONO_EXCEPTION_CLAUSE_FILTER ? ec->data.filter_offset : 0);
2869
2870                         /*
2871                          * The spvars are needed by mono_arch_install_handler_block_guard ().
2872                          */
2873                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
2874                                 int region;
2875
2876                                 region = ((i + 1) << 8) | MONO_REGION_FINALLY | ec->flags;
2877                                 spvar = mono_find_spvar_for_region (cfg, region);
2878                                 g_assert (spvar);
2879                                 ei->exvar_offset = spvar->inst_offset;
2880                         } else {
2881                                 exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
2882                                 ei->exvar_offset = exvar ? exvar->inst_offset : 0;
2883                         }
2884
2885                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2886                                 tblock = cfg->cil_offset_to_bb [ec->data.filter_offset];
2887                                 g_assert (tblock);
2888                                 ei->data.filter = cfg->native_code + tblock->native_offset;
2889                         } else {
2890                                 ei->data.catch_class = ec->data.catch_class;
2891                         }
2892
2893                         tblock = cfg->cil_offset_to_bb [ec->try_offset];
2894                         g_assert (tblock);
2895                         g_assert (tblock->native_offset);
2896                         ei->try_start = cfg->native_code + tblock->native_offset;
2897                         if (tblock->extend_try_block) {
2898                                 /*
2899                                  * Extend the try block backwards to include parts of the previous call
2900                                  * instruction.
2901                                  */
2902                                 ei->try_start = (guint8*)ei->try_start - MONO_ARCH_MONITOR_ENTER_ADJUSTMENT;
2903                         }
2904                         tblock = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
2905                         g_assert (tblock);
2906                         if (!tblock->native_offset) {
2907                                 int j, end;
2908                                 for (j = ec->try_offset + ec->try_len, end = ec->try_offset; j >= end; --j) {
2909                                         MonoBasicBlock *bb = cfg->cil_offset_to_bb [j];
2910                                         if (bb && bb->native_offset) {
2911                                                 tblock = bb;
2912                                                 break;
2913                                         }
2914                                 }
2915                         }
2916                         ei->try_end = cfg->native_code + tblock->native_offset;
2917                         g_assert (tblock->native_offset);
2918                         tblock = cfg->cil_offset_to_bb [ec->handler_offset];
2919                         g_assert (tblock);
2920                         ei->handler_start = cfg->native_code + tblock->native_offset;
2921
2922                         for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
2923                                 TryBlockHole *hole = tmp->data;
2924                                 gpointer hole_end = cfg->native_code + (hole->basic_block->native_offset + hole->basic_block->native_length);
2925                                 if (hole->clause == ec && hole_end == ei->try_end) {
2926                                         if (G_UNLIKELY (cfg->verbose_level >= 4))
2927                                                 printf ("\tShortening try block %d from %x to %x\n", i, (int)((guint8*)ei->try_end - cfg->native_code), hole->start_offset);
2928
2929                                         ei->try_end = cfg->native_code + hole->start_offset;
2930                                         break;
2931                                 }
2932                         }
2933
2934                         if (ec->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
2935                                 int end_offset;
2936                                 if (ec->handler_offset + ec->handler_len < header->code_size) {
2937                                         tblock = cfg->cil_offset_to_bb [ec->handler_offset + ec->handler_len];
2938                                         if (tblock->native_offset) {
2939                                                 end_offset = tblock->native_offset;
2940                                         } else {
2941                                                 int j, end;
2942
2943                                                 for (j = ec->handler_offset + ec->handler_len, end = ec->handler_offset; j >= end; --j) {
2944                                                         MonoBasicBlock *bb = cfg->cil_offset_to_bb [j];
2945                                                         if (bb && bb->native_offset) {
2946                                                                 tblock = bb;
2947                                                                 break;
2948                                                         }
2949                                                 }
2950                                                 end_offset = tblock->native_offset +  tblock->native_length;
2951                                         }
2952                                 } else {
2953                                         end_offset = cfg->epilog_begin;
2954                                 }
2955                                 ei->data.handler_end = cfg->native_code + end_offset;
2956                         }
2957                 }
2958         }
2959
2960         if (G_UNLIKELY (cfg->verbose_level >= 4)) {
2961                 int i;
2962                 for (i = 0; i < jinfo->num_clauses; i++) {
2963                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
2964                         int start = (guint8*)ei->try_start - cfg->native_code;
2965                         int end = (guint8*)ei->try_end - cfg->native_code;
2966                         int handler = (guint8*)ei->handler_start - cfg->native_code;
2967                         int handler_end = (guint8*)ei->data.handler_end - cfg->native_code;
2968
2969                         printf ("JitInfo EH clause %d flags %x try %x-%x handler %x-%x\n", i, ei->flags, start, end, handler, handler_end);
2970                 }
2971         }
2972
2973         if (cfg->encoded_unwind_ops) {
2974                 /* Generated by LLVM */
2975                 jinfo->unwind_info = mono_cache_unwind_info (cfg->encoded_unwind_ops, cfg->encoded_unwind_ops_len);
2976                 g_free (cfg->encoded_unwind_ops);
2977         } else if (cfg->unwind_ops) {
2978                 guint32 info_len;
2979                 guint8 *unwind_info = mono_unwind_ops_encode (cfg->unwind_ops, &info_len);
2980                 guint32 unwind_desc;
2981
2982                 unwind_desc = mono_cache_unwind_info (unwind_info, info_len);
2983
2984                 if (cfg->has_unwind_info_for_epilog) {
2985                         MonoArchEHJitInfo *info;
2986
2987                         info = mono_jit_info_get_arch_eh_info (jinfo);
2988                         g_assert (info);
2989                         info->epilog_size = cfg->code_len - cfg->epilog_begin;
2990                 }
2991                 jinfo->unwind_info = unwind_desc;
2992                 g_free (unwind_info);
2993         } else {
2994                 jinfo->unwind_info = cfg->used_int_regs;
2995         }
2996
2997         return jinfo;
2998 }
2999 #endif
3000
3001 /* Return whenever METHOD is a gsharedvt method */
3002 static gboolean
3003 is_gsharedvt_method (MonoMethod *method)
3004 {
3005         MonoGenericContext *context;
3006         MonoGenericInst *inst;
3007         int i;
3008
3009         if (!method->is_inflated)
3010                 return FALSE;
3011         context = mono_method_get_context (method);
3012         inst = context->class_inst;
3013         if (inst) {
3014                 for (i = 0; i < inst->type_argc; ++i)
3015                         if (mini_is_gsharedvt_gparam (inst->type_argv [i]))
3016                                 return TRUE;
3017         }
3018         inst = context->method_inst;
3019         if (inst) {
3020                 for (i = 0; i < inst->type_argc; ++i)
3021                         if (mini_is_gsharedvt_gparam (inst->type_argv [i]))
3022                                 return TRUE;
3023         }
3024         return FALSE;
3025 }
3026
3027 static gboolean
3028 is_open_method (MonoMethod *method)
3029 {
3030         MonoGenericContext *context;
3031
3032         if (!method->is_inflated)
3033                 return FALSE;
3034         context = mono_method_get_context (method);
3035         if (context->class_inst && context->class_inst->is_open)
3036                 return TRUE;
3037         if (context->method_inst && context->method_inst->is_open)
3038                 return TRUE;
3039         return FALSE;
3040 }
3041
3042 #ifndef DISABLE_JIT
3043
3044 #if defined(__native_client_codegen__) || USE_COOP_GC
3045
3046 static void
3047 mono_create_gc_safepoint (MonoCompile *cfg, MonoBasicBlock *bblock)
3048 {
3049         MonoInst *poll_addr, *ins;
3050         if (cfg->verbose_level > 1)
3051                 printf ("ADDING SAFE POINT TO BB %d\n", bblock->block_num);
3052
3053 #if defined(__native_client_codegen__)
3054         NEW_AOTCONST (cfg, poll_addr, MONO_PATCH_INFO_GC_SAFE_POINT_FLAG, (gpointer)&__nacl_thread_suspension_needed);
3055 #else
3056         NEW_AOTCONST (cfg, poll_addr, MONO_PATCH_INFO_GC_SAFE_POINT_FLAG, (gpointer)&mono_polling_required);
3057 #endif
3058
3059         MONO_INST_NEW (cfg, ins, OP_GC_SAFE_POINT);
3060         ins->sreg1 = poll_addr->dreg;
3061
3062          if (bblock->flags & BB_EXCEPTION_HANDLER) {
3063                 MonoInst *eh_op = bblock->code;
3064
3065                 if (eh_op && eh_op->opcode != OP_START_HANDLER && eh_op->opcode != OP_GET_EX_OBJ) {
3066                         eh_op = NULL;
3067                 } else {
3068                         MonoInst *next_eh_op = eh_op ? eh_op->next : NULL;
3069                         // skip all EH relateds ops
3070                         while (next_eh_op && (next_eh_op->opcode == OP_START_HANDLER || next_eh_op->opcode == OP_GET_EX_OBJ)) {
3071                                 eh_op = next_eh_op;
3072                                 next_eh_op = eh_op->next;
3073                         }
3074                 }
3075
3076                 mono_bblock_insert_after_ins (bblock, eh_op, poll_addr);
3077                 mono_bblock_insert_after_ins (bblock, poll_addr, ins);
3078         } else if (bblock == cfg->bb_entry) {
3079                 mono_bblock_insert_after_ins (bblock, bblock->last_ins, poll_addr);
3080                 mono_bblock_insert_after_ins (bblock, poll_addr, ins);
3081
3082         } else {
3083                 mono_bblock_insert_before_ins (bblock, NULL, poll_addr);
3084                 mono_bblock_insert_after_ins (bblock, poll_addr, ins);
3085         }
3086 }
3087
3088 /*
3089 This code inserts safepoints into managed code at important code paths.
3090 Those are:
3091
3092 -the first basic block
3093 -landing BB for exception handlers
3094 -loop body starts.
3095
3096 */
3097 static void
3098 mono_insert_safepoints (MonoCompile *cfg)
3099 {
3100         MonoBasicBlock *bb;
3101
3102         if (cfg->verbose_level > 1)
3103                 printf ("INSERTING SAFEPOINTS\n");
3104         if (cfg->verbose_level > 2)
3105                 mono_print_code (cfg, "BEFORE SAFEPOINTS");
3106
3107         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3108                 if (bb->loop_body_start || bb == cfg->bb_entry || bb->flags & BB_EXCEPTION_HANDLER)
3109                         mono_create_gc_safepoint (cfg, bb);
3110         }
3111
3112         if (cfg->verbose_level > 2)
3113                 mono_print_code (cfg, "AFTER SAFEPOINTS");
3114
3115 }
3116
3117 #else
3118
3119 static void
3120 mono_insert_safepoints (MonoCompile *cfg)
3121 {
3122 }
3123
3124 #endif
3125
3126 /*
3127  * mini_method_compile:
3128  * @method: the method to compile
3129  * @opts: the optimization flags to use
3130  * @domain: the domain where the method will be compiled in
3131  * @flags: compilation flags
3132  * @parts: debug flag
3133  *
3134  * Returns: a MonoCompile* pointer. Caller must check the exception_type
3135  * field in the returned struct to see if compilation succeded.
3136  */
3137 MonoCompile*
3138 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFlags flags, int parts, int aot_method_index)
3139 {
3140         MonoMethodHeader *header;
3141         MonoMethodSignature *sig;
3142         MonoError err;
3143         MonoCompile *cfg;
3144         int dfn, i, code_size_ratio;
3145         gboolean try_generic_shared, try_llvm = FALSE;
3146         MonoMethod *method_to_compile, *method_to_register;
3147         gboolean method_is_gshared = FALSE;
3148         gboolean run_cctors = (flags & JIT_FLAG_RUN_CCTORS) ? 1 : 0;
3149         gboolean compile_aot = (flags & JIT_FLAG_AOT) ? 1 : 0;
3150         gboolean full_aot = (flags & JIT_FLAG_FULL_AOT) ? 1 : 0;
3151         gboolean disable_direct_icalls = (flags & JIT_FLAG_NO_DIRECT_ICALLS) ? 1 : 0;
3152         gboolean gsharedvt_method = FALSE;
3153 #ifdef ENABLE_LLVM
3154         gboolean llvm = (flags & JIT_FLAG_LLVM) ? 1 : 0;
3155 #endif
3156         static gboolean verbose_method_inited;
3157         static const char *verbose_method_name;
3158
3159         InterlockedIncrement (&mono_jit_stats.methods_compiled);
3160         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
3161                 mono_profiler_method_jit (method);
3162         if (MONO_METHOD_COMPILE_BEGIN_ENABLED ())
3163                 MONO_PROBE_METHOD_COMPILE_BEGIN (method);
3164
3165         gsharedvt_method = is_gsharedvt_method (method);
3166
3167         /*
3168          * In AOT mode, method can be the following:
3169          * - a gsharedvt method.
3170          * - a method inflated with type parameters. This is for ref/partial sharing.
3171          * - a method inflated with concrete types.
3172          */
3173         if (compile_aot) {
3174                 if (is_open_method (method)) {
3175                         try_generic_shared = TRUE;
3176                         method_is_gshared = TRUE;
3177                 } else {
3178                         try_generic_shared = FALSE;
3179                 }
3180                 g_assert (opts & MONO_OPT_GSHARED);
3181         } else {
3182                 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
3183                         (opts & MONO_OPT_GSHARED) && mono_method_is_generic_sharable (method, FALSE);
3184                 if (mini_is_gsharedvt_sharable_method (method)) {
3185                         if (!mono_debug_count ())
3186                                 try_generic_shared = FALSE;
3187                 }
3188         }
3189
3190         /*
3191         if (try_generic_shared && !mono_debug_count ())
3192                 try_generic_shared = FALSE;
3193         */
3194
3195         if (opts & MONO_OPT_GSHARED) {
3196                 if (try_generic_shared)
3197                         mono_stats.generics_sharable_methods++;
3198                 else if (mono_method_is_generic_impl (method))
3199                         mono_stats.generics_unsharable_methods++;
3200         }
3201
3202 #ifdef ENABLE_LLVM
3203         try_llvm = mono_use_llvm || llvm;
3204 #endif
3205
3206  restart_compile:
3207         if (method_is_gshared) {
3208                 method_to_compile = method;
3209         } else {
3210                 if (try_generic_shared) {
3211                         method_to_compile = mini_get_shared_method (method);
3212                         g_assert (method_to_compile);
3213                 } else {
3214                         method_to_compile = method;
3215                 }
3216         }
3217
3218         cfg = g_new0 (MonoCompile, 1);
3219         cfg->method = method_to_compile;
3220         cfg->header = mono_method_get_header (cfg->method);
3221         cfg->mempool = mono_mempool_new ();
3222         cfg->opt = opts;
3223         cfg->prof_options = mono_profiler_get_events ();
3224         cfg->run_cctors = run_cctors;
3225         cfg->domain = domain;
3226         cfg->verbose_level = mini_verbose;
3227         cfg->compile_aot = compile_aot;
3228         cfg->full_aot = full_aot;
3229         cfg->skip_visibility = method->skip_visibility;
3230         cfg->orig_method = method;
3231         cfg->gen_seq_points = debug_options.gen_seq_points_compact_data || debug_options.gen_sdb_seq_points;
3232         cfg->gen_sdb_seq_points = debug_options.gen_sdb_seq_points;
3233
3234 #ifdef PLATFORM_ANDROID
3235         if (cfg->method->wrapper_type != MONO_WRAPPER_NONE) {
3236                 /* FIXME: Why is this needed */
3237                 cfg->gen_seq_points = FALSE;
3238                 cfg->gen_sdb_seq_points = FALSE;
3239         }
3240 #endif
3241         /* coop / nacl requires loop detection to happen */
3242 #if defined(__native_client_codegen__) || defined(USE_COOP_GC)
3243         cfg->opt |= MONO_OPT_LOOP;
3244 #endif
3245
3246         cfg->explicit_null_checks = debug_options.explicit_null_checks;
3247         cfg->soft_breakpoints = debug_options.soft_breakpoints;
3248         cfg->check_pinvoke_callconv = debug_options.check_pinvoke_callconv;
3249         cfg->disable_direct_icalls = disable_direct_icalls;
3250         if (try_generic_shared)
3251                 cfg->gshared = TRUE;
3252         cfg->compile_llvm = try_llvm;
3253         cfg->token_info_hash = g_hash_table_new (NULL, NULL);
3254         if (cfg->compile_aot)
3255                 cfg->method_index = aot_method_index;
3256
3257         if (!mono_debug_count ())
3258                 cfg->opt &= ~MONO_OPT_FLOAT32;
3259         cfg->r4fp = (cfg->opt & MONO_OPT_FLOAT32) ? 1 : 0;
3260         cfg->r4_stack_type = cfg->r4fp ? STACK_R4 : STACK_R8;
3261
3262         if (cfg->gen_seq_points)
3263                 cfg->seq_points = g_ptr_array_new ();
3264         mono_error_init (&cfg->error);
3265
3266         if (cfg->compile_aot && !try_generic_shared && (method->is_generic || method->klass->generic_container || method_is_gshared)) {
3267                 cfg->exception_type = MONO_EXCEPTION_GENERIC_SHARING_FAILED;
3268                 return cfg;
3269         }
3270
3271         if (cfg->gshared && (gsharedvt_method || mini_is_gsharedvt_sharable_method (method))) {
3272                 MonoMethodInflated *inflated;
3273                 MonoGenericContext *context;
3274
3275                 if (gsharedvt_method) {
3276                         g_assert (method->is_inflated);
3277                         inflated = (MonoMethodInflated*)method;
3278                         context = &inflated->context;
3279
3280                         /* We are compiling a gsharedvt method directly */
3281                         g_assert (compile_aot);
3282                 } else {
3283                         g_assert (method_to_compile->is_inflated);
3284                         inflated = (MonoMethodInflated*)method_to_compile;
3285                         context = &inflated->context;
3286                 }
3287
3288                 mini_init_gsctx (NULL, cfg->mempool, context, &cfg->gsctx);
3289                 cfg->gsctx_context = context;
3290
3291                 cfg->gsharedvt = TRUE;
3292                 // FIXME:
3293                 cfg->disable_llvm = TRUE;
3294                 cfg->exception_message = g_strdup ("gsharedvt");
3295         }
3296
3297         if (cfg->gshared) {
3298                 method_to_register = method_to_compile;
3299         } else {
3300                 g_assert (method == method_to_compile);
3301                 method_to_register = method;
3302         }
3303         cfg->method_to_register = method_to_register;
3304
3305         mono_error_init (&err);
3306         sig = mono_method_signature_checked (cfg->method, &err);        
3307         if (!sig) {
3308                 cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
3309                 cfg->exception_message = g_strdup (mono_error_get_message (&err));
3310                 mono_error_cleanup (&err);
3311                 if (MONO_METHOD_COMPILE_END_ENABLED ())
3312                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3313                 return cfg;
3314         }
3315
3316         header = cfg->header;
3317         if (!header) {
3318                 MonoLoaderError *error;
3319
3320                 if ((error = mono_loader_get_last_error ())) {
3321                         cfg->exception_type = error->exception_type;
3322                 } else {
3323                         cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
3324                         cfg->exception_message = g_strdup_printf ("Missing or incorrect header for method %s", cfg->method->name);
3325                 }
3326                 if (MONO_METHOD_COMPILE_END_ENABLED ())
3327                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3328                 return cfg;
3329         }
3330
3331 #ifdef ENABLE_LLVM
3332         {
3333                 static gboolean inited;
3334
3335                 if (!inited)
3336                         inited = TRUE;
3337
3338                 /* 
3339                  * Check for methods which cannot be compiled by LLVM early, to avoid
3340                  * the extra compilation pass.
3341                  */
3342                 if (COMPILE_LLVM (cfg)) {
3343                         mono_llvm_check_method_supported (cfg);
3344                         if (cfg->disable_llvm) {
3345                                 if (cfg->verbose_level >= 1) {
3346                                         //nm = mono_method_full_name (cfg->method, TRUE);
3347                                         printf ("LLVM failed for '%s': %s\n", method->name, cfg->exception_message);
3348                                         //g_free (nm);
3349                                 }
3350                                 mono_destroy_compile (cfg);
3351                                 try_llvm = FALSE;
3352                                 goto restart_compile;
3353                         }
3354                 }
3355         }
3356 #endif
3357
3358         /* The debugger has no liveness information, so avoid sharing registers/stack slots */
3359         if (debug_options.mdb_optimizations) {
3360                 cfg->disable_reuse_registers = TRUE;
3361                 cfg->disable_reuse_stack_slots = TRUE;
3362                 /* 
3363                  * This decreases the change the debugger will read registers/stack slots which are
3364                  * not yet initialized.
3365                  */
3366                 cfg->disable_initlocals_opt = TRUE;
3367
3368                 cfg->extend_live_ranges = TRUE;
3369
3370                 /* Temporarily disable this when running in the debugger until we have support
3371                  * for this in the debugger. */
3372                 /* This is no longer needed with sdb */
3373                 //cfg->disable_omit_fp = TRUE;
3374
3375                 /* The debugger needs all locals to be on the stack or in a global register */
3376                 cfg->disable_vreg_to_lvreg = TRUE;
3377
3378                 /* Don't remove unused variables when running inside the debugger since the user
3379                  * may still want to view them. */
3380                 cfg->disable_deadce_vars = TRUE;
3381
3382                 // cfg->opt |= MONO_OPT_SHARED;
3383                 cfg->opt &= ~MONO_OPT_DEADCE;
3384                 cfg->opt &= ~MONO_OPT_INLINE;
3385                 cfg->opt &= ~MONO_OPT_COPYPROP;
3386                 cfg->opt &= ~MONO_OPT_CONSPROP;
3387                 /* This is no longer needed with sdb */
3388                 //cfg->opt &= ~MONO_OPT_GSHARED;
3389
3390                 /* This is needed for the soft debugger, which doesn't like code after the epilog */
3391                 cfg->disable_out_of_line_bblocks = TRUE;
3392         }
3393
3394         if (mono_using_xdebug) {
3395                 /* 
3396                  * Make each variable use its own register/stack slot and extend 
3397                  * their liveness to cover the whole method, making them displayable
3398                  * in gdb even after they are dead.
3399                  */
3400                 cfg->disable_reuse_registers = TRUE;
3401                 cfg->disable_reuse_stack_slots = TRUE;
3402                 cfg->extend_live_ranges = TRUE;
3403                 cfg->compute_precise_live_ranges = TRUE;
3404         }
3405
3406         mini_gc_init_cfg (cfg);
3407
3408         if (COMPILE_LLVM (cfg)) {
3409                 cfg->opt |= MONO_OPT_ABCREM;
3410         }
3411
3412         if (!verbose_method_inited) {
3413                 verbose_method_name = g_getenv ("MONO_VERBOSE_METHOD");
3414                 verbose_method_inited = TRUE;
3415         }
3416         if (verbose_method_name) {
3417                 const char *name = verbose_method_name;
3418
3419                 if ((strchr (name, '.') > name) || strchr (name, ':')) {
3420                         MonoMethodDesc *desc;
3421                         
3422                         desc = mono_method_desc_new (name, TRUE);
3423                         if (mono_method_desc_full_match (desc, cfg->method)) {
3424                                 cfg->verbose_level = 4;
3425                         }
3426                         mono_method_desc_free (desc);
3427                 } else {
3428                         if (strcmp (cfg->method->name, name) == 0)
3429                                 cfg->verbose_level = 4;
3430                 }
3431         }
3432
3433         cfg->intvars = mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * header->max_stack);
3434
3435         if (cfg->verbose_level > 0) {
3436                 char *method_name;
3437
3438                 method_name = mono_method_full_name (method, TRUE);
3439                 g_print ("converting %s%s%smethod %s\n", COMPILE_LLVM (cfg) ? "llvm " : "", cfg->gsharedvt ? "gsharedvt " : "", (cfg->gshared && !cfg->gsharedvt) ? "gshared " : "", method_name);
3440                 /*
3441                 if (COMPILE_LLVM (cfg))
3442                         g_print ("converting llvm method %s\n", method_name = mono_method_full_name (method, TRUE));
3443                 else if (cfg->gsharedvt)
3444                         g_print ("converting gsharedvt method %s\n", method_name = mono_method_full_name (method_to_compile, TRUE));
3445                 else if (cfg->gshared)
3446                         g_print ("converting shared method %s\n", method_name = mono_method_full_name (method_to_compile, TRUE));
3447                 else
3448                         g_print ("converting method %s\n", method_name = mono_method_full_name (method, TRUE));
3449                 */
3450                 g_free (method_name);
3451         }
3452
3453         if (cfg->opt & MONO_OPT_ABCREM)
3454                 cfg->opt |= MONO_OPT_SSA;
3455
3456         cfg->rs = mono_regstate_new ();
3457         cfg->next_vreg = cfg->rs->next_vreg;
3458
3459         /* FIXME: Fix SSA to handle branches inside bblocks */
3460         if (cfg->opt & MONO_OPT_SSA)
3461                 cfg->enable_extended_bblocks = FALSE;
3462
3463         /*
3464          * FIXME: This confuses liveness analysis because variables which are assigned after
3465          * a branch inside a bblock become part of the kill set, even though the assignment
3466          * might not get executed. This causes the optimize_initlocals pass to delete some
3467          * assignments which are needed.
3468          * Also, the mono_if_conversion pass needs to be modified to recognize the code
3469          * created by this.
3470          */
3471         //cfg->enable_extended_bblocks = TRUE;
3472
3473         /*We must verify the method before doing any IR generation as mono_compile_create_vars can assert.*/
3474         if (mono_compile_is_broken (cfg, cfg->method, TRUE)) {
3475                 if (mini_get_debug_options ()->break_on_unverified)
3476                         G_BREAKPOINT ();
3477                 return cfg;
3478         }
3479
3480         /*
3481          * create MonoInst* which represents arguments and local variables
3482          */
3483         mono_compile_create_vars (cfg);
3484
3485         i = mono_method_to_ir (cfg, method_to_compile, NULL, NULL, NULL, NULL, 0, FALSE);
3486
3487         if (i < 0) {
3488                 if (try_generic_shared && cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3489                         if (compile_aot) {
3490                                 if (MONO_METHOD_COMPILE_END_ENABLED ())
3491                                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3492                                 return cfg;
3493                         }
3494                         mono_destroy_compile (cfg);
3495                         try_generic_shared = FALSE;
3496                         goto restart_compile;
3497                 }
3498                 g_assert (cfg->exception_type != MONO_EXCEPTION_GENERIC_SHARING_FAILED);
3499
3500                 if (MONO_METHOD_COMPILE_END_ENABLED ())
3501                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3502                 /* cfg contains the details of the failure, so let the caller cleanup */
3503                 return cfg;
3504         }
3505
3506         cfg->stat_basic_blocks += cfg->num_bblocks;
3507
3508         if (COMPILE_LLVM (cfg)) {
3509                 MonoInst *ins;
3510
3511                 /* The IR has to be in SSA form for LLVM */
3512                 cfg->opt |= MONO_OPT_SSA;
3513
3514                 // FIXME:
3515                 if (cfg->ret) {
3516                         // Allow SSA on the result value
3517                         cfg->ret->flags &= ~MONO_INST_VOLATILE;
3518
3519                         // Add an explicit return instruction referencing the return value
3520                         MONO_INST_NEW (cfg, ins, OP_SETRET);
3521                         ins->sreg1 = cfg->ret->dreg;
3522
3523                         MONO_ADD_INS (cfg->bb_exit, ins);
3524                 }
3525
3526                 cfg->opt &= ~MONO_OPT_LINEARS;
3527
3528                 /* FIXME: */
3529                 cfg->opt &= ~MONO_OPT_BRANCH;
3530         }
3531
3532         /* todo: remove code when we have verified that the liveness for try/catch blocks
3533          * works perfectly 
3534          */
3535         /* 
3536          * Currently, this can't be commented out since exception blocks are not
3537          * processed during liveness analysis.
3538          * It is also needed, because otherwise the local optimization passes would
3539          * delete assignments in cases like this:
3540          * r1 <- 1
3541          * <something which throws>
3542          * r1 <- 2
3543          * This also allows SSA to be run on methods containing exception clauses, since
3544          * SSA will ignore variables marked VOLATILE.
3545          */
3546         mono_liveness_handle_exception_clauses (cfg);
3547
3548         mono_handle_out_of_line_bblock (cfg);
3549
3550         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
3551
3552         if (!COMPILE_LLVM (cfg))
3553                 mono_decompose_long_opts (cfg);
3554
3555         /* Should be done before branch opts */
3556         if (cfg->opt & (MONO_OPT_CONSPROP | MONO_OPT_COPYPROP))
3557                 mono_local_cprop (cfg);
3558
3559         if (cfg->opt & MONO_OPT_BRANCH)
3560                 mono_optimize_branches (cfg);
3561
3562         /* This must be done _before_ global reg alloc and _after_ decompose */
3563         mono_handle_global_vregs (cfg);
3564         if (cfg->opt & MONO_OPT_DEADCE)
3565                 mono_local_deadce (cfg);
3566         if (cfg->opt & MONO_OPT_ALIAS_ANALYSIS)
3567                 mono_local_alias_analysis (cfg);
3568         /* Disable this for LLVM to make the IR easier to handle */
3569         if (!COMPILE_LLVM (cfg))
3570                 mono_if_conversion (cfg);
3571
3572         /* Depth-first ordering on basic blocks */
3573         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
3574
3575         cfg->max_block_num = cfg->num_bblocks;
3576
3577         dfn = 0;
3578         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
3579         if (cfg->num_bblocks != dfn + 1) {
3580                 MonoBasicBlock *bb;
3581
3582                 cfg->num_bblocks = dfn + 1;
3583
3584                 /* remove unreachable code, because the code in them may be 
3585                  * inconsistent  (access to dead variables for example) */
3586                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
3587                         bb->flags &= ~BB_VISITED;
3588                 compute_reachable (cfg->bb_entry);
3589                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
3590                         if (bb->flags & BB_EXCEPTION_HANDLER)
3591                                 compute_reachable (bb);
3592                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3593                         if (!(bb->flags & BB_VISITED)) {
3594                                 if (cfg->verbose_level > 1)
3595                                         g_print ("found unreachable code in BB%d\n", bb->block_num);
3596                                 bb->code = bb->last_ins = NULL;
3597                                 while (bb->out_count)
3598                                         mono_unlink_bblock (cfg, bb, bb->out_bb [0]);
3599                         }
3600                 }
3601                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
3602                         bb->flags &= ~BB_VISITED;
3603         }
3604
3605         if (((cfg->num_varinfo > 2000) || (cfg->num_bblocks > 1000)) && !cfg->compile_aot) {
3606                 /* 
3607                  * we disable some optimizations if there are too many variables
3608                  * because JIT time may become too expensive. The actual number needs 
3609                  * to be tweaked and eventually the non-linear algorithms should be fixed.
3610                  */
3611                 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
3612                 cfg->disable_ssa = TRUE;
3613         }
3614
3615         if (cfg->opt & MONO_OPT_LOOP) {
3616                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
3617                 mono_compute_natural_loops (cfg);
3618         }
3619
3620         mono_insert_safepoints (cfg);
3621
3622         /* after method_to_ir */
3623         if (parts == 1) {
3624                 if (MONO_METHOD_COMPILE_END_ENABLED ())
3625                         MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
3626                 return cfg;
3627         }
3628
3629         /*
3630           if (header->num_clauses)
3631           cfg->disable_ssa = TRUE;
3632         */
3633
3634 //#define DEBUGSSA "logic_run"
3635 //#define DEBUGSSA_CLASS "Tests"
3636 #ifdef DEBUGSSA
3637
3638         if (!cfg->disable_ssa) {
3639                 mono_local_cprop (cfg);
3640
3641 #ifndef DISABLE_SSA
3642                 mono_ssa_compute (cfg);
3643 #endif
3644         }
3645 #else 
3646         if (cfg->opt & MONO_OPT_SSA) {
3647                 if (!(cfg->comp_done & MONO_COMP_SSA) && !cfg->disable_ssa) {
3648 #ifndef DISABLE_SSA
3649                         mono_ssa_compute (cfg);
3650 #endif
3651
3652                         if (cfg->verbose_level >= 2) {
3653                                 print_dfn (cfg);
3654                         }
3655                 }
3656         }
3657 #endif
3658
3659         /* after SSA translation */
3660         if (parts == 2) {
3661                 if (MONO_METHOD_COMPILE_END_ENABLED ())
3662                         MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
3663                 return cfg;
3664         }
3665
3666         if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
3667                 if (cfg->comp_done & MONO_COMP_SSA && !COMPILE_LLVM (cfg)) {
3668 #ifndef DISABLE_SSA
3669                         mono_ssa_cprop (cfg);
3670 #endif
3671                 }
3672         }
3673
3674 #ifndef DISABLE_SSA
3675         if (cfg->comp_done & MONO_COMP_SSA && !COMPILE_LLVM (cfg)) {
3676                 //mono_ssa_strength_reduction (cfg);
3677
3678                 if (cfg->opt & MONO_OPT_DEADCE)
3679                         mono_ssa_deadce (cfg);
3680
3681                 if ((cfg->flags & (MONO_CFG_HAS_LDELEMA|MONO_CFG_HAS_CHECK_THIS)) && (cfg->opt & MONO_OPT_ABCREM))
3682                         mono_perform_abc_removal (cfg);
3683
3684                 mono_ssa_remove (cfg);
3685                 mono_local_cprop (cfg);
3686                 mono_handle_global_vregs (cfg);
3687                 if (cfg->opt & MONO_OPT_DEADCE)
3688                         mono_local_deadce (cfg);
3689
3690                 if (cfg->opt & MONO_OPT_BRANCH)
3691                         mono_optimize_branches (cfg);
3692         }
3693 #endif
3694
3695         if (cfg->comp_done & MONO_COMP_SSA && COMPILE_LLVM (cfg)) {
3696                 mono_ssa_loop_invariant_code_motion (cfg);
3697                 /* This removes MONO_INST_FAULT flags too so perform it unconditionally */
3698                 if (cfg->opt & MONO_OPT_ABCREM)
3699                         mono_perform_abc_removal (cfg);
3700         }
3701
3702         /* after SSA removal */
3703         if (parts == 3) {
3704                 if (MONO_METHOD_COMPILE_END_ENABLED ())
3705                         MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
3706                 return cfg;
3707         }
3708
3709 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
3710         if (COMPILE_SOFT_FLOAT (cfg))
3711                 mono_decompose_soft_float (cfg);
3712 #endif
3713         if (COMPILE_LLVM (cfg))
3714                 mono_decompose_vtype_opts_llvm (cfg);
3715         else
3716                 mono_decompose_vtype_opts (cfg);
3717         if (cfg->flags & MONO_CFG_HAS_ARRAY_ACCESS)
3718                 mono_decompose_array_access_opts (cfg);
3719
3720         if (cfg->got_var) {
3721 #ifndef MONO_ARCH_GOT_REG
3722                 GList *regs;
3723 #endif
3724                 int got_reg;
3725
3726                 g_assert (cfg->got_var_allocated);
3727
3728                 /* 
3729                  * Allways allocate the GOT var to a register, because keeping it
3730                  * in memory will increase the number of live temporaries in some
3731                  * code created by inssel.brg, leading to the well known spills+
3732                  * branches problem. Testcase: mcs crash in 
3733                  * System.MonoCustomAttrs:GetCustomAttributes.
3734                  */
3735 #ifdef MONO_ARCH_GOT_REG
3736                 got_reg = MONO_ARCH_GOT_REG;
3737 #else
3738                 regs = mono_arch_get_global_int_regs (cfg);
3739                 g_assert (regs);
3740                 got_reg = GPOINTER_TO_INT (regs->data);
3741                 g_list_free (regs);
3742 #endif
3743                 cfg->got_var->opcode = OP_REGVAR;
3744                 cfg->got_var->dreg = got_reg;
3745                 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
3746         }
3747
3748         /*
3749          * Have to call this again to process variables added since the first call.
3750          */
3751         mono_liveness_handle_exception_clauses (cfg);
3752
3753         if (cfg->opt & MONO_OPT_LINEARS) {
3754                 GList *vars, *regs, *l;
3755                 
3756                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
3757                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
3758                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
3759                         mono_analyze_liveness (cfg);
3760
3761                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
3762                         regs = mono_arch_get_global_int_regs (cfg);
3763                         /* Remove the reg reserved for holding the GOT address */
3764                         if (cfg->got_var) {
3765                                 for (l = regs; l; l = l->next) {
3766                                         if (GPOINTER_TO_UINT (l->data) == cfg->got_var->dreg) {
3767                                                 regs = g_list_delete_link (regs, l);
3768                                                 break;
3769                                         }
3770                                 }
3771                         }
3772                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
3773                 }
3774         }
3775
3776         //mono_print_code (cfg, "");
3777
3778     //print_dfn (cfg);
3779         
3780         /* variables are allocated after decompose, since decompose could create temps */
3781         if (!COMPILE_LLVM (cfg)) {
3782                 mono_arch_allocate_vars (cfg);
3783                 if (cfg->exception_type)
3784                         return cfg;
3785         }
3786
3787         {
3788                 MonoBasicBlock *bb;
3789                 gboolean need_local_opts;
3790
3791                 if (!COMPILE_LLVM (cfg)) {
3792                         mono_spill_global_vars (cfg, &need_local_opts);
3793
3794                         if (need_local_opts || cfg->compile_aot) {
3795                                 /* To optimize code created by spill_global_vars */
3796                                 mono_local_cprop (cfg);
3797                                 if (cfg->opt & MONO_OPT_DEADCE)
3798                                         mono_local_deadce (cfg);
3799                         }
3800                 }
3801
3802                 /* Add branches between non-consecutive bblocks */
3803                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3804                         if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
3805                                 bb->last_ins->inst_false_bb && bb->next_bb != bb->last_ins->inst_false_bb) {
3806                                 /* we are careful when inverting, since bugs like #59580
3807                                  * could show up when dealing with NaNs.
3808                                  */
3809                                 if (MONO_IS_COND_BRANCH_NOFP(bb->last_ins) && bb->next_bb == bb->last_ins->inst_true_bb) {
3810                                         MonoBasicBlock *tmp =  bb->last_ins->inst_true_bb;
3811                                         bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb;
3812                                         bb->last_ins->inst_false_bb = tmp;
3813
3814                                         bb->last_ins->opcode = mono_reverse_branch_op (bb->last_ins->opcode);
3815                                 } else {                        
3816                                         MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
3817                                         inst->opcode = OP_BR;
3818                                         inst->inst_target_bb = bb->last_ins->inst_false_bb;
3819                                         mono_bblock_add_inst (bb, inst);
3820                                 }
3821                         }
3822                 }
3823
3824                 if (cfg->verbose_level >= 4) {
3825                         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3826                                 MonoInst *tree = bb->code;      
3827                                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
3828                                 if (!tree)
3829                                         continue;
3830                                 for (; tree; tree = tree->next) {
3831                                         mono_print_ins_index (-1, tree);
3832                                 }
3833                         }
3834                 }
3835
3836                 /* FIXME: */
3837                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3838                         bb->max_vreg = cfg->next_vreg;
3839                 }
3840         }
3841
3842         if (COMPILE_LLVM (cfg)) {
3843 #ifdef ENABLE_LLVM
3844                 char *nm;
3845
3846                 /* The IR has to be in SSA form for LLVM */
3847                 if (!(cfg->comp_done & MONO_COMP_SSA)) {
3848                         cfg->exception_message = g_strdup ("SSA disabled.");
3849                         cfg->disable_llvm = TRUE;
3850                 }
3851
3852                 if (cfg->flags & MONO_CFG_HAS_ARRAY_ACCESS)
3853                         mono_decompose_array_access_opts (cfg);
3854
3855                 if (!cfg->disable_llvm)
3856                         mono_llvm_emit_method (cfg);
3857                 if (cfg->disable_llvm) {
3858                         if (cfg->verbose_level >= 1) {
3859                                 //nm = mono_method_full_name (cfg->method, TRUE);
3860                                 printf ("LLVM failed for '%s': %s\n", method->name, cfg->exception_message);
3861                                 //g_free (nm);
3862                         }
3863                         mono_destroy_compile (cfg);
3864                         try_llvm = FALSE;
3865                         goto restart_compile;
3866                 }
3867
3868                 if (cfg->verbose_level > 0 && !cfg->compile_aot) {
3869                         nm = mono_method_full_name (cfg->method, TRUE);
3870                         g_print ("LLVM Method %s emitted at %p to %p (code length %d) [%s]\n", 
3871                                          nm, 
3872                                          cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
3873                         g_free (nm);
3874                 }
3875 #endif
3876         } else {
3877                 mono_codegen (cfg);
3878         }
3879
3880         if (COMPILE_LLVM (cfg))
3881                 InterlockedIncrement (&mono_jit_stats.methods_with_llvm);
3882         else
3883                 InterlockedIncrement (&mono_jit_stats.methods_without_llvm);
3884
3885         cfg->jit_info = create_jit_info (cfg, method_to_compile);
3886
3887 #ifdef MONO_ARCH_HAVE_LIVERANGE_OPS
3888         if (cfg->extend_live_ranges) {
3889                 /* Extend live ranges to cover the whole method */
3890                 for (i = 0; i < cfg->num_varinfo; ++i)
3891                         MONO_VARINFO (cfg, i)->live_range_end = cfg->code_len;
3892         }
3893 #endif
3894
3895         if (!cfg->compile_aot)
3896                 mono_save_xdebug_info (cfg);
3897
3898         mini_gc_create_gc_map (cfg);
3899  
3900         mono_save_seq_point_info (cfg);
3901
3902         if (cfg->verbose_level >= 2) {
3903                 char *id =  mono_method_full_name (cfg->method, FALSE);
3904                 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
3905                 g_free (id);
3906         }
3907
3908         if (!cfg->compile_aot) {
3909                 mono_domain_lock (cfg->domain);
3910                 mono_jit_info_table_add (cfg->domain, cfg->jit_info);
3911
3912                 if (cfg->method->dynamic)
3913                         mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = cfg->jit_info;
3914                 mono_domain_unlock (cfg->domain);
3915         }
3916
3917 #if 0
3918         if (cfg->gsharedvt)
3919                 printf ("GSHAREDVT: %s\n", mono_method_full_name (cfg->method, TRUE));
3920 #endif
3921
3922         /* collect statistics */
3923 #ifndef DISABLE_PERFCOUNTERS
3924         mono_perfcounters->jit_methods++;
3925         mono_perfcounters->jit_bytes += header->code_size;
3926 #endif
3927         mono_jit_stats.allocated_code_size += cfg->code_len;
3928         code_size_ratio = cfg->code_len;
3929         if (code_size_ratio > mono_jit_stats.biggest_method_size && mono_jit_stats.enabled) {
3930                 mono_jit_stats.biggest_method_size = code_size_ratio;
3931                 g_free (mono_jit_stats.biggest_method);
3932                 mono_jit_stats.biggest_method = g_strdup_printf ("%s::%s)", method->klass->name, method->name);
3933         }
3934         code_size_ratio = (code_size_ratio * 100) / header->code_size;
3935         if (code_size_ratio > mono_jit_stats.max_code_size_ratio && mono_jit_stats.enabled) {
3936                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
3937                 g_free (mono_jit_stats.max_ratio_method);
3938                 mono_jit_stats.max_ratio_method = g_strdup_printf ("%s::%s)", method->klass->name, method->name);
3939         }
3940         mono_jit_stats.native_code_size += cfg->code_len;
3941
3942         if (MONO_METHOD_COMPILE_END_ENABLED ())
3943                 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
3944
3945         return cfg;
3946 }
3947
3948 #else
3949
3950 MonoCompile*
3951 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFlags flags, int parts, int aot_method_index)
3952 {
3953         g_assert_not_reached ();
3954         return NULL;
3955 }
3956
3957 #endif /* DISABLE_JIT */
3958
3959 gpointer
3960 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt, MonoException **jit_ex)
3961 {
3962         MonoCompile *cfg;
3963         gpointer code = NULL;
3964         MonoJitInfo *jinfo, *info;
3965         MonoVTable *vtable;
3966         MonoException *ex = NULL;
3967         guint32 prof_options;
3968         GTimer *jit_timer;
3969         MonoMethod *prof_method, *shared;
3970
3971         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3972             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
3973                 MonoMethod *nm;
3974                 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
3975
3976                 if (!piinfo->addr) {
3977                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3978                                 piinfo->addr = mono_lookup_internal_call (method);
3979                         else if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
3980 #ifdef HOST_WIN32
3981                                 g_warning ("Method '%s' in assembly '%s' contains native code that cannot be executed by Mono in modules loaded from byte arrays. The assembly was probably created using C++/CLI.\n", mono_method_full_name (method, TRUE), method->klass->image->name);
3982 #else
3983                                 g_warning ("Method '%s' in assembly '%s' contains native code that cannot be executed by Mono on this platform. The assembly was probably created using C++/CLI.\n", mono_method_full_name (method, TRUE), method->klass->image->name);
3984 #endif
3985                         else
3986                                 mono_lookup_pinvoke_call (method, NULL, NULL);
3987                 }
3988                 nm = mono_marshal_get_native_wrapper (method, TRUE, mono_aot_only);
3989                 code = mono_get_addr_from_ftnptr (mono_compile_method (nm));
3990                 jinfo = mono_jit_info_table_find (target_domain, code);
3991                 if (!jinfo)
3992                         jinfo = mono_jit_info_table_find (mono_domain_get (), code);
3993                 if (jinfo)
3994                         mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
3995                 return code;
3996         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
3997                 const char *name = method->name;
3998                 char *full_name, *msg;
3999                 MonoMethod *nm;
4000
4001                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
4002                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
4003                                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name ("mono_delegate_ctor");
4004                                 g_assert (mi);
4005                                 /*
4006                                  * We need to make sure this wrapper
4007                                  * is compiled because it might end up
4008                                  * in an (M)RGCTX if generic sharing
4009                                  * is enabled, and would be called
4010                                  * indirectly.  If it were a
4011                                  * trampoline we'd try to patch that
4012                                  * indirect call, which is not
4013                                  * possible.
4014                                  */
4015                                 return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper_full (mi, TRUE));
4016                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
4017                                 return mono_create_delegate_trampoline (target_domain, method->klass);
4018                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
4019                                 nm = mono_marshal_get_delegate_begin_invoke (method);
4020                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
4021                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
4022                                 nm = mono_marshal_get_delegate_end_invoke (method);
4023                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
4024                         }
4025                 }
4026
4027                 full_name = mono_method_full_name (method, TRUE);
4028                 msg = g_strdup_printf ("Unrecognizable runtime implemented method '%s'", full_name);
4029                 *jit_ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", msg);
4030                 g_free (full_name);
4031                 g_free (msg);
4032                 return NULL;
4033         }
4034
4035         if (method->wrapper_type == MONO_WRAPPER_UNKNOWN) {
4036                 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
4037
4038                 if (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT) {
4039                         static MonoTrampInfo *in_tinfo, *out_tinfo;
4040                         MonoTrampInfo *tinfo;
4041                         MonoJitInfo *jinfo;
4042                         gboolean is_in = info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN;
4043
4044                         if (is_in && in_tinfo)
4045                                 return in_tinfo->code;
4046                         else if (!is_in && out_tinfo)
4047                                 return out_tinfo->code;
4048
4049                         /*
4050                          * This is a special wrapper whose body is implemented in assembly, like a trampoline. We use a wrapper so EH
4051                          * works.
4052                          * FIXME: The caller signature doesn't match the callee, which might cause problems on some platforms
4053                          */
4054                         if (mono_aot_only)
4055                                 mono_aot_get_trampoline_full (is_in ? "gsharedvt_trampoline" : "gsharedvt_out_trampoline", &tinfo);
4056                         else
4057                                 mono_arch_get_gsharedvt_trampoline (&tinfo, FALSE);
4058                         jinfo = create_jit_info_for_trampoline (method, tinfo);
4059                         mono_jit_info_table_add (mono_get_root_domain (), jinfo);
4060                         if (is_in)
4061                                 in_tinfo = tinfo;
4062                         else
4063                                 out_tinfo = tinfo;
4064                         return tinfo->code;
4065                 }
4066         }
4067
4068         if (mono_aot_only) {
4069                 char *fullname = mono_method_full_name (method, TRUE);
4070                 char *msg = g_strdup_printf ("Attempting to JIT compile method '%s' while running with --aot-only. See http://docs.xamarin.com/ios/about/limitations for more information.\n", fullname);
4071
4072                 *jit_ex = mono_get_exception_execution_engine (msg);
4073                 g_free (fullname);
4074                 g_free (msg);
4075                 
4076                 return NULL;
4077         }
4078
4079         jit_timer = g_timer_new ();
4080
4081         cfg = mini_method_compile (method, opt, target_domain, JIT_FLAG_RUN_CCTORS, 0, -1);
4082         prof_method = cfg->method;
4083
4084         g_timer_stop (jit_timer);
4085         mono_jit_stats.jit_time += g_timer_elapsed (jit_timer, NULL);
4086         g_timer_destroy (jit_timer);
4087
4088         switch (cfg->exception_type) {
4089         case MONO_EXCEPTION_NONE:
4090                 break;
4091         case MONO_EXCEPTION_TYPE_LOAD:
4092         case MONO_EXCEPTION_MISSING_FIELD:
4093         case MONO_EXCEPTION_MISSING_METHOD:
4094         case MONO_EXCEPTION_FILE_NOT_FOUND:
4095         case MONO_EXCEPTION_BAD_IMAGE: {
4096                 /* Throw a type load exception if needed */
4097                 MonoLoaderError *error = mono_loader_get_last_error ();
4098
4099                 if (error) {
4100                         ex = mono_loader_error_prepare_exception (error);
4101                 } else {
4102                         if (cfg->exception_ptr) {
4103                                 ex = mono_class_get_exception_for_failure (cfg->exception_ptr);
4104                         } else {
4105                                 if (cfg->exception_type == MONO_EXCEPTION_MISSING_FIELD)
4106                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingFieldException", cfg->exception_message);
4107                                 else if (cfg->exception_type == MONO_EXCEPTION_MISSING_METHOD)
4108                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingMethodException", cfg->exception_message);
4109                                 else if (cfg->exception_type == MONO_EXCEPTION_TYPE_LOAD)
4110                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "TypeLoadException", cfg->exception_message);
4111                                 else if (cfg->exception_type == MONO_EXCEPTION_FILE_NOT_FOUND)
4112                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.IO", "FileNotFoundException", cfg->exception_message);
4113                                 else if (cfg->exception_type == MONO_EXCEPTION_BAD_IMAGE)
4114                                         ex = mono_get_exception_bad_image_format (cfg->exception_message);
4115                                 else
4116                                         g_assert_not_reached ();
4117                         }
4118                 }
4119                 break;
4120         }
4121         case MONO_EXCEPTION_INVALID_PROGRAM:
4122                 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", cfg->exception_message);
4123                 break;
4124         case MONO_EXCEPTION_UNVERIFIABLE_IL:
4125                 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.Security", "VerificationException", cfg->exception_message);
4126                 break;
4127         case MONO_EXCEPTION_METHOD_ACCESS:
4128                 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MethodAccessException", cfg->exception_message);
4129                 break;
4130         case MONO_EXCEPTION_FIELD_ACCESS:
4131                 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FieldAccessException", cfg->exception_message);
4132                 break;
4133         case MONO_EXCEPTION_OBJECT_SUPPLIED: {
4134                 MonoException *exp = cfg->exception_ptr;
4135                 MONO_GC_UNREGISTER_ROOT (cfg->exception_ptr);
4136
4137                 ex = exp;
4138                 break;
4139         }
4140         case MONO_EXCEPTION_OUT_OF_MEMORY:
4141                 ex = mono_domain_get ()->out_of_memory_ex;
4142                 break;
4143         case MONO_EXCEPTION_MONO_ERROR:
4144                 g_assert (!mono_error_ok (&cfg->error));
4145                 ex = mono_error_convert_to_exception (&cfg->error);
4146                 break;
4147         default:
4148                 g_assert_not_reached ();
4149         }
4150
4151         if (ex) {
4152                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
4153                         mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
4154
4155                 mono_destroy_compile (cfg);
4156                 *jit_ex = ex;
4157
4158                 return NULL;
4159         }
4160
4161         if (mono_method_is_generic_sharable (method, FALSE))
4162                 shared = mini_get_shared_method (method);
4163         else
4164                 shared = NULL;
4165
4166         mono_domain_lock (target_domain);
4167
4168         /* Check if some other thread already did the job. In this case, we can
4169        discard the code this thread generated. */
4170
4171         info = mini_lookup_method (target_domain, method, shared);
4172         if (info) {
4173                 /* We can't use a domain specific method in another domain */
4174                 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
4175                         code = info->code_start;
4176 //                      printf("Discarding code for method %s\n", method->name);
4177                 }
4178         }
4179         if (code == NULL) {
4180                 /* The lookup + insert is atomic since this is done inside the domain lock */
4181                 mono_domain_jit_code_hash_lock (target_domain);
4182                 mono_internal_hash_table_insert (&target_domain->jit_code_hash, cfg->jit_info->d.method, cfg->jit_info);
4183                 mono_domain_jit_code_hash_unlock (target_domain);
4184
4185                 code = cfg->native_code;
4186
4187                 if (cfg->gshared && mono_method_is_generic_sharable (method, FALSE))
4188                         mono_stats.generics_shared_methods++;
4189                 if (cfg->gsharedvt)
4190                         mono_stats.gsharedvt_methods++;
4191         }
4192
4193         jinfo = cfg->jit_info;
4194
4195         prof_options = cfg->prof_options;
4196
4197         /*
4198          * Update global stats while holding a lock, instead of doing many
4199          * InterlockedIncrement operations during JITting.
4200          */
4201         mono_jit_stats.allocate_var += cfg->stat_allocate_var;
4202         mono_jit_stats.locals_stack_size += cfg->stat_locals_stack_size;
4203         mono_jit_stats.basic_blocks += cfg->stat_basic_blocks;
4204         mono_jit_stats.max_basic_blocks = MAX (cfg->stat_basic_blocks, mono_jit_stats.max_basic_blocks);
4205         mono_jit_stats.cil_code_size += cfg->stat_cil_code_size;
4206         mono_jit_stats.regvars += cfg->stat_n_regvars;
4207         mono_jit_stats.inlineable_methods += cfg->stat_inlineable_methods;
4208         mono_jit_stats.inlined_methods += cfg->stat_inlined_methods;
4209         mono_jit_stats.code_reallocs += cfg->stat_code_reallocs;
4210
4211         mono_destroy_compile (cfg);
4212
4213 #ifndef DISABLE_JIT
4214         if (domain_jit_info (target_domain)->jump_target_hash) {
4215                 MonoJumpInfo patch_info;
4216                 MonoJumpList *jlist;
4217                 GSList *tmp;
4218                 jlist = g_hash_table_lookup (domain_jit_info (target_domain)->jump_target_hash, method);
4219                 if (jlist) {
4220                         patch_info.next = NULL;
4221                         patch_info.ip.i = 0;
4222                         patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
4223                         patch_info.data.method = method;
4224                         g_hash_table_remove (domain_jit_info (target_domain)->jump_target_hash, method);
4225
4226 #if defined(__native_client_codegen__) && defined(__native_client__)
4227                         /* These patches are applied after a method has been installed, no target munging is needed. */
4228                         nacl_allow_target_modification (FALSE);
4229 #endif
4230 #ifdef MONO_ARCH_HAVE_PATCH_CODE_NEW
4231                         for (tmp = jlist->list; tmp; tmp = tmp->next) {
4232                                 gpointer target = mono_resolve_patch_target (NULL, target_domain, tmp->data, &patch_info, TRUE);
4233                                 mono_arch_patch_code_new (NULL, target_domain, tmp->data, &patch_info, target);
4234                         }
4235 #else
4236                         for (tmp = jlist->list; tmp; tmp = tmp->next)
4237                                 mono_arch_patch_code (NULL, NULL, target_domain, tmp->data, &patch_info, TRUE);
4238 #endif
4239 #if defined(__native_client_codegen__) && defined(__native_client__)
4240                         nacl_allow_target_modification (TRUE);
4241 #endif
4242                 }
4243         }
4244
4245         mono_emit_jit_map (jinfo);
4246 #endif
4247         mono_domain_unlock (target_domain);
4248
4249         vtable = mono_class_vtable (target_domain, method->klass);
4250         if (!vtable) {
4251                 ex = mono_class_get_exception_for_failure (method->klass);
4252                 g_assert (ex);
4253                 *jit_ex = ex;
4254                 return NULL;
4255         }
4256
4257         if (prof_options & MONO_PROFILE_JIT_COMPILATION) {
4258                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
4259                         if (mono_marshal_method_from_wrapper (method)) {
4260                                 /* Native func wrappers have no method */
4261                                 /* The profiler doesn't know about wrappers, so pass the original icall method */
4262                                 mono_profiler_method_end_jit (mono_marshal_method_from_wrapper (method), jinfo, MONO_PROFILE_OK);
4263                         }
4264                 }
4265                 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
4266                 if (prof_method != method) {
4267                         mono_profiler_method_end_jit (prof_method, jinfo, MONO_PROFILE_OK);
4268                 }
4269         }
4270
4271         ex = mono_runtime_class_init_full (vtable, FALSE);
4272         if (ex) {
4273                 *jit_ex = ex;
4274                 return NULL;
4275         }
4276         return code;
4277 }
4278
4279 #ifndef DISABLE_JIT
4280
4281 void*
4282 mono_arch_instrument_epilog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments) {
4283         return mono_arch_instrument_epilog_full (cfg, func, p, enable_arguments, FALSE);
4284 }
4285
4286 void
4287 mono_cfg_add_try_hole (MonoCompile *cfg, MonoExceptionClause *clause, guint8 *start, MonoBasicBlock *bb)
4288 {
4289         TryBlockHole *hole = mono_mempool_alloc (cfg->mempool, sizeof (TryBlockHole));
4290         hole->clause = clause;
4291         hole->start_offset = start - cfg->native_code;
4292         hole->basic_block = bb;
4293
4294         cfg->try_block_holes = g_slist_append_mempool (cfg->mempool, cfg->try_block_holes, hole);
4295 }
4296
4297 void
4298 mono_cfg_set_exception (MonoCompile *cfg, int type)
4299 {
4300         cfg->exception_type = type;
4301 }
4302
4303 #endif
4304
4305 /* Dummy versions of some arch specific functions to avoid ifdefs at call sites */
4306
4307 #ifndef MONO_ARCH_GSHAREDVT_SUPPORTED
4308
4309 gboolean
4310 mono_arch_gsharedvt_sig_supported (MonoMethodSignature *sig)
4311 {
4312         return FALSE;
4313 }
4314
4315 gpointer
4316 mono_arch_get_gsharedvt_call_info (gpointer addr, MonoMethodSignature *normal_sig, MonoMethodSignature *gsharedvt_sig, gboolean gsharedvt_in, gint32 vcall_offset, gboolean calli)
4317 {
4318         g_assert_not_reached ();
4319         return NULL;
4320 }
4321
4322 gpointer
4323 mono_arch_get_gsharedvt_arg_trampoline (MonoDomain *domain, gpointer arg, gpointer addr)
4324 {
4325         g_assert_not_reached ();
4326         return NULL;
4327 }
4328
4329 gpointer
4330 mono_arch_get_gsharedvt_trampoline (MonoTrampInfo **info, gboolean aot)
4331 {
4332         g_assert_not_reached ();
4333         return NULL;
4334 }
4335
4336 #endif
4337
4338 #if defined(MONO_ARCH_GSHAREDVT_SUPPORTED) && !defined(ENABLE_GSHAREDVT)
4339
4340 gboolean
4341 mono_arch_gsharedvt_sig_supported (MonoMethodSignature *sig)
4342 {
4343         return FALSE;
4344 }
4345
4346 gpointer
4347 mono_arch_get_gsharedvt_call_info (gpointer addr, MonoMethodSignature *normal_sig, MonoMethodSignature *gsharedvt_sig, gboolean gsharedvt_in, gint32 vcall_offset, gboolean calli)
4348 {
4349         NOT_IMPLEMENTED;
4350         return NULL;
4351 }
4352
4353 #endif
4354
4355 #ifndef ENABLE_LLVM
4356 void
4357 mono_llvm_emit_aot_file_info (MonoAotFileInfo *info, gboolean has_jitted_code)
4358 {
4359         g_assert_not_reached ();
4360 }
4361
4362 void mono_llvm_emit_aot_data (const char *symbol, guint8 *data, int data_len)
4363 {
4364         g_assert_not_reached ();
4365 }
4366 #endif
4367
4368 #ifdef USE_JUMP_TABLES
4369 #define DEFAULT_JUMPTABLE_CHUNK_ELEMENTS 128
4370
4371 typedef struct MonoJumpTableChunk {
4372         guint32 total;
4373         guint32 active;
4374         struct MonoJumpTableChunk *previous;
4375         /* gpointer entries[total]; */
4376 } MonoJumpTableChunk;
4377
4378 static MonoJumpTableChunk* g_jumptable;
4379 #define mono_jumptable_lock() mono_mutex_lock (&jumptable_mutex)
4380 #define mono_jumptable_unlock() mono_mutex_unlock (&jumptable_mutex)
4381 static mono_mutex_t jumptable_mutex;
4382
4383 static  MonoJumpTableChunk*
4384 mono_create_jumptable_chunk (guint32 max_entries)
4385 {
4386         guint32 size = sizeof (MonoJumpTableChunk) + max_entries * sizeof(gpointer);
4387         MonoJumpTableChunk *chunk = (MonoJumpTableChunk*) g_new0 (guchar, size);
4388         chunk->total = max_entries;
4389         return chunk;
4390 }
4391
4392 void
4393 mono_jumptable_init (void)
4394 {
4395         if (g_jumptable == NULL) {
4396                 mono_mutex_init_recursive (&jumptable_mutex);
4397                 g_jumptable = mono_create_jumptable_chunk (DEFAULT_JUMPTABLE_CHUNK_ELEMENTS);
4398         }
4399 }
4400
4401 gpointer*
4402 mono_jumptable_add_entry (void)
4403 {
4404         return mono_jumptable_add_entries (1);
4405 }
4406
4407 gpointer*
4408 mono_jumptable_add_entries (guint32 entries)
4409 {
4410         guint32 index;
4411         gpointer *result;
4412
4413         mono_jumptable_init ();
4414         mono_jumptable_lock ();
4415         index = g_jumptable->active;
4416         if (index + entries >= g_jumptable->total) {
4417                 /*
4418                  * Grow jumptable, by adding one more chunk.
4419                  * We cannot realloc jumptable, as there could be pointers
4420                  * to existing jump table entries in the code, so instead
4421                  * we just add one more chunk.
4422                  */
4423                 guint32 max_entries = entries;
4424                 MonoJumpTableChunk *new_chunk;
4425
4426                 if (max_entries < DEFAULT_JUMPTABLE_CHUNK_ELEMENTS)
4427                         max_entries = DEFAULT_JUMPTABLE_CHUNK_ELEMENTS;
4428                 new_chunk = mono_create_jumptable_chunk (max_entries);
4429                 /* Link old jumptable, so that we could free it up later. */
4430                 new_chunk->previous = g_jumptable;
4431                 g_jumptable = new_chunk;
4432                 index = 0;
4433         }
4434         g_jumptable->active = index + entries;
4435         result = (gpointer*)((guchar*)g_jumptable + sizeof(MonoJumpTableChunk)) + index;
4436         mono_jumptable_unlock();
4437
4438         return result;
4439 }
4440
4441 void
4442 mono_jumptable_cleanup (void)
4443 {
4444         if (g_jumptable) {
4445                 MonoJumpTableChunk *current = g_jumptable, *prev;
4446                 while (current != NULL) {
4447                         prev = current->previous;
4448                         g_free (current);
4449                         current = prev;
4450                 }
4451                 g_jumptable = NULL;
4452                 mono_mutex_destroy (&jumptable_mutex);
4453         }
4454 }
4455
4456 gpointer*
4457 mono_jumptable_get_entry (guint8 *code_ptr)
4458 {
4459         return mono_arch_jumptable_entry_from_code (code_ptr);
4460 }
4461 #endif
4462
4463 /*
4464  * mini_get_underlying_type:
4465  *
4466  *   Return the type the JIT will use during compilation.
4467  * Handles: byref, enums, native types, generic sharing.
4468  * For gsharedvt types, it will return the original VAR/MVAR.
4469  */
4470 MonoType*
4471 mini_get_underlying_type (MonoType *type)
4472 {
4473         return mini_type_get_underlying_type (type);
4474 }
4475
4476 void
4477 mini_jit_init (void)
4478 {
4479         mono_mutex_init_recursive (&jit_mutex);
4480 }
4481
4482 void
4483 mini_jit_cleanup (void)
4484 {
4485         g_free (emul_opcode_map);
4486         g_free (emul_opcode_opcodes);
4487 }