Merged in rest of Native Client changes, untested
[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  * Coprygith 2003-2010 Novell, Inc.
10  */
11
12 #define MONO_LLVM_IN_MINI 1
13 #include <config.h>
14 #include <signal.h>
15 #ifdef HAVE_ALLOCA_H
16 #include <alloca.h>
17 #endif
18 #ifdef HAVE_UNISTD_H
19 #include <unistd.h>
20 #endif
21 #include <math.h>
22 #ifdef HAVE_SYS_TIME_H
23 #include <sys/time.h>
24 #endif
25
26 #include <mono/utils/memcheck.h>
27
28 #include <mono/metadata/assembly.h>
29 #include <mono/metadata/loader.h>
30 #include <mono/metadata/tabledefs.h>
31 #include <mono/metadata/class.h>
32 #include <mono/metadata/object.h>
33 #include <mono/metadata/tokentype.h>
34 #include <mono/metadata/tabledefs.h>
35 #include <mono/metadata/threads.h>
36 #include <mono/metadata/appdomain.h>
37 #include <mono/metadata/debug-helpers.h>
38 #include <mono/io-layer/io-layer.h>
39 #include "mono/metadata/profiler.h"
40 #include <mono/metadata/profiler-private.h>
41 #include <mono/metadata/mono-config.h>
42 #include <mono/metadata/environment.h>
43 #include <mono/metadata/mono-debug.h>
44 #include <mono/metadata/gc-internal.h>
45 #include <mono/metadata/threads-types.h>
46 #include <mono/metadata/verify.h>
47 #include <mono/metadata/verify-internals.h>
48 #include <mono/metadata/mempool-internals.h>
49 #include <mono/metadata/attach.h>
50 #include <mono/metadata/runtime.h>
51 #include <mono/utils/mono-math.h>
52 #include <mono/utils/mono-compiler.h>
53 #include <mono/utils/mono-counters.h>
54 #include <mono/utils/mono-logger-internal.h>
55 #include <mono/utils/mono-mmap.h>
56 #include <mono/utils/dtrace.h>
57
58 #include "mini.h"
59 #include "mini-llvm.h"
60 #include "tasklets.h"
61 #include <string.h>
62 #include <ctype.h>
63 #include "trace.h"
64 #include "version.h"
65
66 #include "jit-icalls.h"
67
68 #include "debug-mini.h"
69 #include "mini-gc.h"
70 #include "debugger-agent.h"
71
72 #if defined(HAVE_KW_THREAD)
73 #define MINI_FAST_TLS_SET(x,y) x = y
74 #define MINI_FAST_TLS_GET(x) x
75 #define MINI_FAST_TLS_INIT(x)
76 #define MINI_FAST_TLS_DECLARE(x) static __thread gpointer x MONO_TLS_FAST;
77 #define MINI_HAVE_FAST_TLS
78 #define MINI_THREAD_VAR_OFFSET(x,y) MONO_THREAD_VAR_OFFSET(x,y)
79 #elif (defined(__APPLE__) && defined(__i386__))
80 #define MINI_FAST_TLS_SET(x,y) pthread_setspecific(x, y)
81 #define MINI_FAST_TLS_GET(x) pthread_getspecific(x)
82 #define MINI_FAST_TLS_INIT(x) pthread_key_create(&x, NULL)
83 #define MINI_FAST_TLS_DECLARE(x) static pthread_key_t x;
84 #define MINI_HAVE_FAST_TLS
85 #define MINI_THREAD_VAR_OFFSET(x,y) y = (gint32) x
86 #else
87 #define MINI_THREAD_VAR_OFFSET(x,y) MONO_THREAD_VAR_OFFSET(x,y)
88 #endif
89
90 static gpointer mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt, MonoException **ex);
91
92 #ifdef __native_client_codegen__
93 /* Default alignment for Native Client is 32-byte. */
94 guint8 nacl_align_byte = 0xe0;
95 #endif
96
97 static guint32 default_opt = 0;
98 static gboolean default_opt_set = FALSE;
99
100 guint32 mono_jit_tls_id = -1;
101
102 #ifdef MINI_HAVE_FAST_TLS
103 MINI_FAST_TLS_DECLARE(mono_jit_tls);
104 #endif
105
106 MonoTraceSpec *mono_jit_trace_calls = NULL;
107 gboolean mono_break_on_exc = FALSE;
108 gboolean mono_compile_aot = FALSE;
109 /* If this is set, no code is generated dynamically, everything is taken from AOT files */
110 gboolean mono_aot_only = FALSE;
111 /* Whenever to use IMT */
112 #ifdef MONO_ARCH_HAVE_IMT
113 gboolean mono_use_imt = TRUE;
114 #else
115 gboolean mono_use_imt = FALSE;
116 #endif
117 MonoMethodDesc *mono_inject_async_exc_method = NULL;
118 int mono_inject_async_exc_pos;
119 MonoMethodDesc *mono_break_at_bb_method = NULL;
120 int mono_break_at_bb_bb_num;
121 gboolean mono_do_x86_stack_align = TRUE;
122 const char *mono_build_date;
123 gboolean mono_do_signal_chaining;
124 static gboolean mono_using_xdebug;
125 static int mini_verbose = 0;
126
127 /*
128  * This flag controls whenever the runtime uses LLVM for JIT compilation, and whenever
129  * it can load AOT code compiled by LLVM.
130  */
131 gboolean mono_use_llvm = FALSE;
132
133 #define mono_jit_lock() EnterCriticalSection (&jit_mutex)
134 #define mono_jit_unlock() LeaveCriticalSection (&jit_mutex)
135 static CRITICAL_SECTION jit_mutex;
136
137 static MonoCodeManager *global_codeman = NULL;
138
139 static GHashTable *jit_icall_name_hash = NULL;
140
141 static MonoDebugOptions debug_options;
142
143 #ifdef VALGRIND_JIT_REGISTER_MAP
144 static int valgrind_register = 0;
145 #endif
146
147 /*
148  * Table written to by the debugger with a 1-based index into the
149  * mono_breakpoint_info table, which contains changes made to
150  * the JIT instructions by the debugger.
151  */
152 gssize
153 mono_breakpoint_info_index [MONO_BREAKPOINT_ARRAY_SIZE];
154
155 /* Whenever to check for pending exceptions in managed-to-native wrappers */
156 gboolean check_for_pending_exc = TRUE;
157
158 /* Whenever to disable passing/returning small valuetypes in registers for managed methods */
159 gboolean disable_vtypes_in_regs = FALSE;
160
161 gboolean mono_dont_free_global_codeman;
162
163 gpointer
164 mono_realloc_native_code (MonoCompile *cfg)
165 {
166 #if defined(__default_codegen__)
167         return g_realloc (cfg->native_code, cfg->code_size);
168 #elif defined(__native_client_codegen__)
169         guint old_padding;
170         gpointer native_code;
171         guint alignment_check;
172
173         /* Save the old alignment offset so we can re-align after the realloc. */
174         old_padding = (guint)(cfg->native_code - cfg->native_code_alloc);
175
176         cfg->native_code_alloc = g_realloc ( cfg->native_code_alloc,
177                                                                                  cfg->code_size + kNaClAlignment );
178
179         /* Align native_code to next nearest kNaClAlignment byte. */
180         native_code = (guint)cfg->native_code_alloc + kNaClAlignment;
181         native_code = (guint)native_code & ~kNaClAlignmentMask;
182
183         /* Shift the data to be 32-byte aligned again. */
184         memmove (native_code, cfg->native_code_alloc + old_padding, cfg->code_size);
185
186         alignment_check = (guint)native_code & kNaClAlignmentMask;
187         g_assert (alignment_check == 0);
188         return native_code;
189 #else
190         g_assert_not_reached ();
191         return cfg->native_code;
192 #endif
193 }
194
195 #ifdef __native_client_codegen__
196
197 /* Prevent instructions from straddling a 32-byte alignment boundary.   */
198 /* Instructions longer than 32 bytes must be aligned internally.        */
199 /* IN: pcode, instlen                                                   */
200 /* OUT: pcode                                                           */
201 void mono_nacl_align_inst(guint8 **pcode, int instlen) {
202   int space_in_block;
203
204   space_in_block = kNaClAlignment - ((uintptr_t)(*pcode) & kNaClAlignmentMask);
205
206   if (G_UNLIKELY (instlen >= kNaClAlignment)) {
207     g_assert_not_reached();
208   } else if (instlen > space_in_block) {
209     *pcode = mono_arch_nacl_pad(*pcode, space_in_block);
210   }
211 }
212
213 /* Move emitted call sequence to the end of a kNaClAlignment-byte block.  */
214 /* IN: start    pointer to start of call sequence                         */
215 /* IN: pcode    pointer to end of call sequence (current "IP")            */
216 /* OUT: start   pointer to the start of the call sequence after padding   */
217 /* OUT: pcode   pointer to the end of the call sequence after padding     */
218 void mono_nacl_align_call(guint8 **start, guint8 **pcode) {
219   const size_t MAX_NACL_CALL_LENGTH = kNaClAlignment;
220   guint8 copy_of_call[MAX_NACL_CALL_LENGTH];
221   guint8 *temp;
222
223   const size_t length = (size_t)((*pcode)-(*start));
224   g_assert(length < MAX_NACL_CALL_LENGTH);
225
226   memcpy(copy_of_call, *start, length);
227   temp = mono_nacl_pad_call(*start, (guint8)length);
228   memcpy(temp, copy_of_call, length);
229   (*start) = temp;
230   (*pcode) = temp + length;
231 }
232
233 /* mono_nacl_pad_call(): Insert padding for Native Client call instructions */
234 /*    code     pointer to buffer for emitting code                          */
235 /*    ilength  length of call instruction                                   */
236 guint8 *mono_nacl_pad_call(guint8 *code, guint8 ilength) {
237   int freeSpaceInBlock = kNaClAlignment - ((uintptr_t)code & kNaClAlignmentMask);
238   int padding = freeSpaceInBlock - ilength;
239
240   if (padding < 0) {
241     /* There isn't enough space in this block for the instruction. */
242     /* Fill this block and start a new one.                        */
243     code = mono_arch_nacl_pad(code, freeSpaceInBlock);
244     freeSpaceInBlock = kNaClAlignment;
245     padding = freeSpaceInBlock - ilength;
246   }
247   g_assert(ilength > 0);
248   g_assert(padding >= 0);
249   g_assert(padding < kNaClAlignment);
250   if (0 == padding) return code;
251   return mono_arch_nacl_pad(code, padding);
252 }
253
254 guint8 *mono_nacl_align(guint8 *code) {
255   int padding = kNaClAlignment - ((uintptr_t)code & kNaClAlignmentMask);
256   if (padding != kNaClAlignment) code = mono_arch_nacl_pad(code, padding);
257   return code;
258 }
259
260 void mono_nacl_fix_patches(const guint8 *code, MonoJumpInfo *ji)
261 {
262   MonoJumpInfo *patch_info;
263   for (patch_info = ji; patch_info; patch_info = patch_info->next) {
264     unsigned char *ip = patch_info->ip.i + code;
265     ip = mono_arch_nacl_skip_nops(ip);
266     patch_info->ip.i = ip - code;
267   }
268 }
269 #endif  /* __native_client_codegen__ */
270
271 gboolean
272 mono_running_on_valgrind (void)
273 {
274         if (RUNNING_ON_VALGRIND){
275 #ifdef VALGRIND_JIT_REGISTER_MAP
276                 valgrind_register = TRUE;
277 #endif
278                 return TRUE;
279         } else
280                 return FALSE;
281 }
282
283 typedef struct {
284         MonoExceptionClause *clause;
285         MonoBasicBlock *basic_block;
286         int start_offset;
287 } TryBlockHole;
288
289 typedef struct {
290         void *ip;
291         MonoMethod *method;
292 } FindTrampUserData;
293
294 static void
295 find_tramp (gpointer key, gpointer value, gpointer user_data)
296 {
297         FindTrampUserData *ud = (FindTrampUserData*)user_data;
298
299         if (value == ud->ip)
300                 ud->method = (MonoMethod*)key;
301 }
302
303 /* debug function */
304 G_GNUC_UNUSED static char*
305 get_method_from_ip (void *ip)
306 {
307         MonoJitInfo *ji;
308         char *method;
309         char *res;
310         MonoDomain *domain = mono_domain_get ();
311         MonoDebugSourceLocation *location;
312         FindTrampUserData user_data;
313         
314         ji = mono_jit_info_table_find (domain, ip);
315         if (!ji) {
316                 user_data.ip = ip;
317                 user_data.method = NULL;
318                 mono_domain_lock (domain);
319                 g_hash_table_foreach (domain_jit_info (domain)->jit_trampoline_hash, find_tramp, &user_data);
320                 mono_domain_unlock (domain);
321                 if (user_data.method) {
322                         char *mname = mono_method_full_name (user_data.method, TRUE);
323                         res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
324                         g_free (mname);
325                         return res;
326                 }
327                 else
328                         return NULL;
329         }
330         method = mono_method_full_name (ji->method, TRUE);
331         /* FIXME: unused ? */
332         location = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
333
334         res = g_strdup_printf (" %s + 0x%x (%p %p) [%p - %s]", method, (int)((char*)ip - (char*)ji->code_start), ji->code_start, (char*)ji->code_start + ji->code_size, domain, domain->friendly_name);
335
336         mono_debug_free_source_location (location);
337         g_free (method);
338
339         return res;
340 }
341
342 /** 
343  * mono_pmip:
344  * @ip: an instruction pointer address
345  *
346  * This method is used from a debugger to get the name of the
347  * method at address @ip.   This routine is typically invoked from
348  * a debugger like this:
349  *
350  * (gdb) print mono_pmip ($pc)
351  *
352  * Returns: the name of the method at address @ip.
353  */
354 G_GNUC_UNUSED char *
355 mono_pmip (void *ip)
356 {
357         return get_method_from_ip (ip);
358 }
359
360 /** 
361  * mono_print_method_from_ip
362  * @ip: an instruction pointer address
363  *
364  * This method is used from a debugger to get the name of the
365  * method at address @ip.
366  *
367  * This prints the name of the method at address @ip in the standard
368  * output.  Unlike mono_pmip which returns a string, this routine
369  * prints the value on the standard output. 
370  */
371 void
372 mono_print_method_from_ip (void *ip)
373 {
374         MonoJitInfo *ji;
375         char *method;
376         MonoDebugSourceLocation *source;
377         MonoDomain *domain = mono_domain_get ();
378         MonoDomain *target_domain = mono_domain_get ();
379         FindTrampUserData user_data;
380         
381         ji = mini_jit_info_table_find (domain, ip, &target_domain);
382         if (!ji) {
383                 user_data.ip = ip;
384                 user_data.method = NULL;
385                 mono_domain_lock (domain);
386                 g_hash_table_foreach (domain_jit_info (domain)->jit_trampoline_hash, find_tramp, &user_data);
387                 mono_domain_unlock (domain);
388                 if (user_data.method) {
389                         char *mname = mono_method_full_name (user_data.method, TRUE);
390                         printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
391                         g_free (mname);
392                 }
393                 else
394                         g_print ("No method at %p\n", ip);
395                 return;
396         }
397         method = mono_method_full_name (ji->method, TRUE);
398         source = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), target_domain);
399
400         g_print ("IP %p at offset 0x%x of method %s (%p %p)[domain %p - %s]\n", ip, (int)((char*)ip - (char*)ji->code_start), method, ji->code_start, (char*)ji->code_start + ji->code_size, target_domain, target_domain->friendly_name);
401
402         if (source)
403                 g_print ("%s:%d\n", source->source_file, source->row);
404
405         mono_debug_free_source_location (source);
406         g_free (method);
407 }
408         
409 /* 
410  * mono_method_same_domain:
411  *
412  * Determine whenever two compiled methods are in the same domain, thus
413  * the address of the callee can be embedded in the caller.
414  */
415 gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
416 {
417         if (!caller || !callee)
418                 return FALSE;
419
420         /*
421          * If the call was made from domain-neutral to domain-specific 
422          * code, we can't patch the call site.
423          */
424         if (caller->domain_neutral && !callee->domain_neutral)
425                 return FALSE;
426
427         if ((caller->method->klass == mono_defaults.appdomain_class) &&
428                 (strstr (caller->method->name, "InvokeInDomain"))) {
429                  /* The InvokeInDomain methods change the current appdomain */
430                 return FALSE;
431         }
432
433         return TRUE;
434 }
435
436 /*
437  * mono_global_codeman_reserve:
438  *
439  *  Allocate code memory from the global code manager.
440  */
441 void *mono_global_codeman_reserve (int size)
442 {
443         void *ptr;
444
445         if (mono_aot_only)
446                 g_error ("Attempting to allocate from the global code manager while running with --aot-only.\n");
447
448         if (!global_codeman) {
449                 /* This can happen during startup */
450                 global_codeman = mono_code_manager_new ();
451                 return mono_code_manager_reserve (global_codeman, size);
452         }
453         else {
454                 mono_jit_lock ();
455                 ptr = mono_code_manager_reserve (global_codeman, size);
456                 mono_jit_unlock ();
457                 return ptr;
458         }
459 }
460
461 #if defined(__native_client_codegen__) && defined(__native_client__)
462 /* Given the temporary buffer (allocated by mono_global_codeman_reserve) into
463  * which we are generating code, return a pointer to the destination in the
464  * dynamic code segment into which the code will be copied when
465  * mono_global_codeman_commit is called.
466  * LOCKING: Acquires the jit lock.
467  */
468 void*
469 nacl_global_codeman_get_dest (void *data)
470 {
471         void *dest;
472         mono_jit_lock ();
473         dest = nacl_code_manager_get_code_dest (global_codeman, data);
474         mono_jit_unlock ();
475         return dest;
476 }
477
478 void
479 mono_global_codeman_commit (void *data, int size, int newsize)
480 {
481         mono_jit_lock ();
482         mono_code_manager_commit (global_codeman, data, size, newsize);
483         mono_jit_unlock ();
484 }
485
486 /* 
487  * Convenience function which calls mono_global_codeman_commit to validate and
488  * copy the code. The caller sets *buf_base and *buf_size to the start and size
489  * of the buffer (allocated by mono_global_codeman_reserve), and *code_end to
490  * the byte after the last instruction byte. On return, *buf_base will point to
491  * the start of the copied in the code segment, and *code_end will point after
492  * the end of the copied code.
493  */
494 void
495 nacl_global_codeman_validate (guint8 **buf_base, int buf_size, guint8 **code_end)
496 {
497         guint8 *tmp = nacl_global_codeman_get_dest (*buf_base);
498         mono_global_codeman_commit (*buf_base, buf_size, *code_end - *buf_base);
499         *code_end = tmp + (*code_end - *buf_base);
500         *buf_base = tmp;
501 }
502 #endif /* __native_client__ */
503
504 /**
505  * mono_create_unwind_op:
506  *
507  *   Create an unwind op with the given parameters.
508  */
509 MonoUnwindOp*
510 mono_create_unwind_op (int when, int tag, int reg, int val)
511 {
512         MonoUnwindOp *op = g_new0 (MonoUnwindOp, 1);
513
514         op->op = tag;
515         op->reg = reg;
516         op->val = val;
517         op->when = when;
518
519         return op;
520 }
521
522 /**
523  * mono_emit_unwind_op:
524  *
525  *   Add an unwind op with the given parameters for the list of unwind ops stored in
526  * cfg->unwind_ops.
527  */
528 void
529 mono_emit_unwind_op (MonoCompile *cfg, int when, int tag, int reg, int val)
530 {
531         MonoUnwindOp *op = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoUnwindOp));
532
533         op->op = tag;
534         op->reg = reg;
535         op->val = val;
536         op->when = when;
537         
538         cfg->unwind_ops = g_slist_append_mempool (cfg->mempool, cfg->unwind_ops, op);
539 }
540
541 MonoJumpInfoToken *
542 mono_jump_info_token_new2 (MonoMemPool *mp, MonoImage *image, guint32 token, MonoGenericContext *context)
543 {
544         MonoJumpInfoToken *res = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
545         res->image = image;
546         res->token = token;
547         res->has_context = context != NULL;
548         if (context)
549                 memcpy (&res->context, context, sizeof (MonoGenericContext));
550
551         return res;
552 }
553
554 MonoJumpInfoToken *
555 mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
556 {
557         return mono_jump_info_token_new2 (mp, image, token, NULL);
558 }
559  
560 /*
561  * mono_tramp_info_create:
562  *
563  *   Create a MonoTrampInfo structure from the arguments. This function assumes ownership
564  * of NAME, JI, and UNWIND_OPS.
565  */
566 MonoTrampInfo*
567 mono_tramp_info_create (const char *name, guint8 *code, guint32 code_size, MonoJumpInfo *ji, GSList *unwind_ops)
568 {
569         MonoTrampInfo *info = g_new0 (MonoTrampInfo, 1);
570
571         info->name = (char*)name;
572         info->code = code;
573         info->code_size = code_size;
574         info->ji = ji;
575         info->unwind_ops = unwind_ops;
576
577         return info;
578 }
579
580 void
581 mono_tramp_info_free (MonoTrampInfo *info)
582 {
583         GSList *l;
584
585         g_free (info->name);
586
587         // FIXME: ji
588         for (l = info->unwind_ops; l; l = l->next)
589                 g_free (l->data);
590         g_slist_free (info->unwind_ops);
591         g_free (info);
592 }
593
594 #define MONO_INIT_VARINFO(vi,id) do { \
595         (vi)->range.first_use.pos.bid = 0xffff; \
596         (vi)->reg = -1; \
597         (vi)->idx = (id); \
598 } while (0)
599
600 /**
601  * mono_unlink_bblock:
602  *
603  *   Unlink two basic blocks.
604  */
605 void
606 mono_unlink_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
607 {
608         int i, pos;
609         gboolean found;
610
611         found = FALSE;
612         for (i = 0; i < from->out_count; ++i) {
613                 if (to == from->out_bb [i]) {
614                         found = TRUE;
615                         break;
616                 }
617         }
618         if (found) {
619                 pos = 0;
620                 for (i = 0; i < from->out_count; ++i) {
621                         if (from->out_bb [i] != to)
622                                 from->out_bb [pos ++] = from->out_bb [i];
623                 }
624                 g_assert (pos == from->out_count - 1);
625                 from->out_count--;
626         }
627
628         found = FALSE;
629         for (i = 0; i < to->in_count; ++i) {
630                 if (from == to->in_bb [i]) {
631                         found = TRUE;
632                         break;
633                 }
634         }
635         if (found) {
636                 pos = 0;
637                 for (i = 0; i < to->in_count; ++i) {
638                         if (to->in_bb [i] != from)
639                                 to->in_bb [pos ++] = to->in_bb [i];
640                 }
641                 g_assert (pos == to->in_count - 1);
642                 to->in_count--;
643         }
644 }
645
646 /*
647  * mono_bblocks_linked:
648  *
649  *   Return whenever BB1 and BB2 are linked in the CFG.
650  */
651 gboolean
652 mono_bblocks_linked (MonoBasicBlock *bb1, MonoBasicBlock *bb2)
653 {
654         int i;
655
656         for (i = 0; i < bb1->out_count; ++i) {
657                 if (bb1->out_bb [i] == bb2)
658                         return TRUE;
659         }
660
661         return FALSE;
662 }
663
664 static int
665 mono_find_block_region_notry (MonoCompile *cfg, int offset)
666 {
667         MonoMethodHeader *header = cfg->header;
668         MonoExceptionClause *clause;
669         int i;
670
671         for (i = 0; i < header->num_clauses; ++i) {
672                 clause = &header->clauses [i];
673                 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
674                     (offset < (clause->handler_offset)))
675                         return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
676                            
677                 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
678                         if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
679                                 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
680                         else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
681                                 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
682                         else
683                                 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
684                 }
685         }
686
687         return -1;
688 }
689
690 /*
691  * mono_get_block_region_notry:
692  *
693  *   Return the region corresponding to REGION, ignoring try clauses nested inside
694  * finally clauses.
695  */
696 int
697 mono_get_block_region_notry (MonoCompile *cfg, int region)
698 {
699         if ((region & (0xf << 4)) == MONO_REGION_TRY) {
700                 MonoMethodHeader *header = cfg->header;
701                 
702                 /*
703                  * This can happen if a try clause is nested inside a finally clause.
704                  */
705                 int clause_index = (region >> 8) - 1;
706                 g_assert (clause_index >= 0 && clause_index < header->num_clauses);
707                 
708                 region = mono_find_block_region_notry (cfg, header->clauses [clause_index].try_offset);
709         }
710
711         return region;
712 }
713
714 MonoInst *
715 mono_find_spvar_for_region (MonoCompile *cfg, int region)
716 {
717         region = mono_get_block_region_notry (cfg, region);
718
719         return g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
720 }
721
722 static void
723 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
724 {
725         int i;
726
727         array [*dfn] = start;
728         /* g_print ("visit %d at %p (BB%ld)\n", *dfn, start->cil_code, start->block_num); */
729         for (i = 0; i < start->out_count; ++i) {
730                 if (start->out_bb [i]->dfn)
731                         continue;
732                 (*dfn)++;
733                 start->out_bb [i]->dfn = *dfn;
734                 start->out_bb [i]->df_parent = start;
735                 array [*dfn] = start->out_bb [i];
736                 df_visit (start->out_bb [i], dfn, array);
737         }
738 }
739
740 guint32
741 mono_reverse_branch_op (guint32 opcode)
742 {
743         static const int reverse_map [] = {
744                 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
745                 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
746         };
747         static const int reverse_fmap [] = {
748                 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
749                 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
750         };
751         static const int reverse_lmap [] = {
752                 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
753                 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
754         };
755         static const int reverse_imap [] = {
756                 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
757                 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
758         };
759                                 
760         if (opcode >= CEE_BEQ && opcode <= CEE_BLT_UN) {
761                 opcode = reverse_map [opcode - CEE_BEQ];
762         } else if (opcode >= OP_FBEQ && opcode <= OP_FBLT_UN) {
763                 opcode = reverse_fmap [opcode - OP_FBEQ];
764         } else if (opcode >= OP_LBEQ && opcode <= OP_LBLT_UN) {
765                 opcode = reverse_lmap [opcode - OP_LBEQ];
766         } else if (opcode >= OP_IBEQ && opcode <= OP_IBLT_UN) {
767                 opcode = reverse_imap [opcode - OP_IBEQ];
768         } else
769                 g_assert_not_reached ();
770
771         return opcode;
772 }
773
774 guint
775 mono_type_to_store_membase (MonoCompile *cfg, MonoType *type)
776 {
777         if (type->byref)
778                 return OP_STORE_MEMBASE_REG;
779
780 handle_enum:
781         switch (type->type) {
782         case MONO_TYPE_I1:
783         case MONO_TYPE_U1:
784         case MONO_TYPE_BOOLEAN:
785                 return OP_STOREI1_MEMBASE_REG;
786         case MONO_TYPE_I2:
787         case MONO_TYPE_U2:
788         case MONO_TYPE_CHAR:
789                 return OP_STOREI2_MEMBASE_REG;
790         case MONO_TYPE_I4:
791         case MONO_TYPE_U4:
792                 return OP_STOREI4_MEMBASE_REG;
793         case MONO_TYPE_I:
794         case MONO_TYPE_U:
795         case MONO_TYPE_PTR:
796         case MONO_TYPE_FNPTR:
797                 return OP_STORE_MEMBASE_REG;
798         case MONO_TYPE_CLASS:
799         case MONO_TYPE_STRING:
800         case MONO_TYPE_OBJECT:
801         case MONO_TYPE_SZARRAY:
802         case MONO_TYPE_ARRAY:    
803                 return OP_STORE_MEMBASE_REG;
804         case MONO_TYPE_I8:
805         case MONO_TYPE_U8:
806                 return OP_STOREI8_MEMBASE_REG;
807         case MONO_TYPE_R4:
808                 return OP_STORER4_MEMBASE_REG;
809         case MONO_TYPE_R8:
810                 return OP_STORER8_MEMBASE_REG;
811         case MONO_TYPE_VALUETYPE:
812                 if (type->data.klass->enumtype) {
813                         type = mono_class_enum_basetype (type->data.klass);
814                         goto handle_enum;
815                 }
816                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
817                         return OP_STOREX_MEMBASE;
818                 return OP_STOREV_MEMBASE;
819         case MONO_TYPE_TYPEDBYREF:
820                 return OP_STOREV_MEMBASE;
821         case MONO_TYPE_GENERICINST:
822                 type = &type->data.generic_class->container_class->byval_arg;
823                 goto handle_enum;
824         case MONO_TYPE_VAR:
825         case MONO_TYPE_MVAR:
826                 /* FIXME: all the arguments must be references for now,
827                  * later look inside cfg and see if the arg num is
828                  * really a reference
829                  */
830                 g_assert (cfg->generic_sharing_context);
831                 return OP_STORE_MEMBASE_REG;
832         default:
833                 g_error ("unknown type 0x%02x in type_to_store_membase", type->type);
834         }
835         return -1;
836 }
837
838 guint
839 mono_type_to_load_membase (MonoCompile *cfg, MonoType *type)
840 {
841         if (type->byref)
842                 return OP_LOAD_MEMBASE;
843
844         type = mono_type_get_underlying_type (type);
845
846         switch (type->type) {
847         case MONO_TYPE_I1:
848                 return OP_LOADI1_MEMBASE;
849         case MONO_TYPE_U1:
850         case MONO_TYPE_BOOLEAN:
851                 return OP_LOADU1_MEMBASE;
852         case MONO_TYPE_I2:
853                 return OP_LOADI2_MEMBASE;
854         case MONO_TYPE_U2:
855         case MONO_TYPE_CHAR:
856                 return OP_LOADU2_MEMBASE;
857         case MONO_TYPE_I4:
858                 return OP_LOADI4_MEMBASE;
859         case MONO_TYPE_U4:
860                 return OP_LOADU4_MEMBASE;
861         case MONO_TYPE_I:
862         case MONO_TYPE_U:
863         case MONO_TYPE_PTR:
864         case MONO_TYPE_FNPTR:
865                 return OP_LOAD_MEMBASE;
866         case MONO_TYPE_CLASS:
867         case MONO_TYPE_STRING:
868         case MONO_TYPE_OBJECT:
869         case MONO_TYPE_SZARRAY:
870         case MONO_TYPE_ARRAY:    
871                 return OP_LOAD_MEMBASE;
872         case MONO_TYPE_I8:
873         case MONO_TYPE_U8:
874                 return OP_LOADI8_MEMBASE;
875         case MONO_TYPE_R4:
876                 return OP_LOADR4_MEMBASE;
877         case MONO_TYPE_R8:
878                 return OP_LOADR8_MEMBASE;
879         case MONO_TYPE_VALUETYPE:
880                 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
881                         return OP_LOADX_MEMBASE;
882         case MONO_TYPE_TYPEDBYREF:
883                 return OP_LOADV_MEMBASE;
884         case MONO_TYPE_GENERICINST:
885                 if (mono_type_generic_inst_is_valuetype (type))
886                         return OP_LOADV_MEMBASE;
887                 else
888                         return OP_LOAD_MEMBASE;
889                 break;
890         case MONO_TYPE_VAR:
891         case MONO_TYPE_MVAR:
892                 /* FIXME: all the arguments must be references for now,
893                  * later look inside cfg and see if the arg num is
894                  * really a reference
895                  */
896                 g_assert (cfg->generic_sharing_context);
897                 return OP_LOAD_MEMBASE;
898         default:
899                 g_error ("unknown type 0x%02x in type_to_load_membase", type->type);
900         }
901         return -1;
902 }
903
904 static guint
905 mini_type_to_ldind (MonoCompile* cfg, MonoType *type)
906 {
907         if (cfg->generic_sharing_context && !type->byref) {
908                 /* FIXME: all the arguments must be references for now,
909                  * later look inside cfg and see if the arg num is
910                  * really a reference
911                  */
912                 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
913                         return CEE_LDIND_REF;
914         }
915         return mono_type_to_ldind (type);
916 }
917
918 guint
919 mini_type_to_stind (MonoCompile* cfg, MonoType *type)
920 {
921         if (cfg->generic_sharing_context && !type->byref) {
922                 /* FIXME: all the arguments must be references for now,
923                  * later look inside cfg and see if the arg num is
924                  * really a reference
925                  */
926                 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
927                         return CEE_STIND_REF;
928         }
929         return mono_type_to_stind (type);
930 }
931
932 int
933 mono_op_imm_to_op (int opcode)
934 {
935         switch (opcode) {
936         case OP_ADD_IMM:
937 #if SIZEOF_REGISTER == 4
938                 return OP_IADD;
939 #else
940                 return OP_LADD;
941 #endif
942         case OP_IADD_IMM:
943                 return OP_IADD;
944         case OP_LADD_IMM:
945                 return OP_LADD;
946         case OP_ISUB_IMM:
947                 return OP_ISUB;
948         case OP_LSUB_IMM:
949                 return OP_LSUB;
950         case OP_IMUL_IMM:
951                 return OP_IMUL;
952         case OP_AND_IMM:
953 #if SIZEOF_REGISTER == 4
954                 return OP_IAND;
955 #else
956                 return OP_LAND;
957 #endif
958         case OP_OR_IMM:
959 #if SIZEOF_REGISTER == 4
960                 return OP_IOR;
961 #else
962                 return OP_LOR;
963 #endif
964         case OP_XOR_IMM:
965 #if SIZEOF_REGISTER == 4
966                 return OP_IXOR;
967 #else
968                 return OP_LXOR;
969 #endif
970         case OP_IAND_IMM:
971                 return OP_IAND;
972         case OP_LAND_IMM:
973                 return OP_LAND;
974         case OP_IOR_IMM:
975                 return OP_IOR;
976         case OP_LOR_IMM:
977                 return OP_LOR;
978         case OP_IXOR_IMM:
979                 return OP_IXOR;
980         case OP_LXOR_IMM:
981                 return OP_LXOR;
982         case OP_ISHL_IMM:
983                 return OP_ISHL;
984         case OP_LSHL_IMM:
985                 return OP_LSHL;
986         case OP_ISHR_IMM:
987                 return OP_ISHR;
988         case OP_LSHR_IMM:
989                 return OP_LSHR;
990         case OP_ISHR_UN_IMM:
991                 return OP_ISHR_UN;
992         case OP_LSHR_UN_IMM:
993                 return OP_LSHR_UN;
994         case OP_IDIV_IMM:
995                 return OP_IDIV;
996         case OP_IDIV_UN_IMM:
997                 return OP_IDIV_UN;
998         case OP_IREM_UN_IMM:
999                 return OP_IREM_UN;
1000         case OP_IREM_IMM:
1001                 return OP_IREM;
1002         case OP_DIV_IMM:
1003 #if SIZEOF_REGISTER == 4
1004                 return OP_IDIV;
1005 #else
1006                 return OP_LDIV;
1007 #endif
1008         case OP_REM_IMM:
1009 #if SIZEOF_REGISTER == 4
1010                 return OP_IREM;
1011 #else
1012                 return OP_LREM;
1013 #endif
1014         case OP_ADDCC_IMM:
1015                 return OP_ADDCC;
1016         case OP_ADC_IMM:
1017                 return OP_ADC;
1018         case OP_SUBCC_IMM:
1019                 return OP_SUBCC;
1020         case OP_SBB_IMM:
1021                 return OP_SBB;
1022         case OP_IADC_IMM:
1023                 return OP_IADC;
1024         case OP_ISBB_IMM:
1025                 return OP_ISBB;
1026         case OP_COMPARE_IMM:
1027                 return OP_COMPARE;
1028         case OP_ICOMPARE_IMM:
1029                 return OP_ICOMPARE;
1030         case OP_LOCALLOC_IMM:
1031                 return OP_LOCALLOC;
1032         default:
1033                 printf ("%s\n", mono_inst_name (opcode));
1034                 g_assert_not_reached ();
1035                 return -1;
1036         }
1037 }
1038
1039 /*
1040  * mono_decompose_op_imm:
1041  *
1042  *   Replace the OP_.._IMM INS with its non IMM variant.
1043  */
1044 void
1045 mono_decompose_op_imm (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins)
1046 {
1047         MonoInst *temp;
1048
1049         MONO_INST_NEW (cfg, temp, OP_ICONST);
1050         temp->inst_c0 = ins->inst_imm;
1051         temp->dreg = mono_alloc_ireg (cfg);
1052         mono_bblock_insert_before_ins (bb, ins, temp);
1053         ins->opcode = mono_op_imm_to_op (ins->opcode);
1054         if (ins->opcode == OP_LOCALLOC)
1055                 ins->sreg1 = temp->dreg;
1056         else
1057                 ins->sreg2 = temp->dreg;
1058
1059         bb->max_vreg = MAX (bb->max_vreg, cfg->next_vreg);
1060 }
1061
1062 static void
1063 set_vreg_to_inst (MonoCompile *cfg, int vreg, MonoInst *inst)
1064 {
1065         if (vreg >= cfg->vreg_to_inst_len) {
1066                 MonoInst **tmp = cfg->vreg_to_inst;
1067                 int size = cfg->vreg_to_inst_len;
1068
1069                 while (vreg >= cfg->vreg_to_inst_len)
1070                         cfg->vreg_to_inst_len = cfg->vreg_to_inst_len ? cfg->vreg_to_inst_len * 2 : 32;
1071                 cfg->vreg_to_inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * cfg->vreg_to_inst_len);
1072                 if (size)
1073                         memcpy (cfg->vreg_to_inst, tmp, size * sizeof (MonoInst*));
1074         }
1075         cfg->vreg_to_inst [vreg] = inst;
1076 }
1077
1078 #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)))
1079 #define mono_type_is_float(type) (!(type)->byref && (((type)->type == MONO_TYPE_R8) || ((type)->type == MONO_TYPE_R4)))
1080
1081 #ifdef DISABLE_JIT
1082
1083 MonoInst*
1084 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1085 {
1086         return NULL;
1087 }
1088
1089 #else
1090
1091 MonoInst*
1092 mono_compile_create_var_for_vreg (MonoCompile *cfg, MonoType *type, int opcode, int vreg)
1093 {
1094         MonoInst *inst;
1095         int num = cfg->num_varinfo;
1096         gboolean regpair;
1097
1098         if ((num + 1) >= cfg->varinfo_count) {
1099                 int orig_count = cfg->varinfo_count;
1100                 cfg->varinfo_count = cfg->varinfo_count ? (cfg->varinfo_count * 2) : 64;
1101                 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
1102                 cfg->vars = (MonoMethodVar *)g_realloc (cfg->vars, sizeof (MonoMethodVar) * cfg->varinfo_count);
1103                 memset (&cfg->vars [orig_count], 0, (cfg->varinfo_count - orig_count) * sizeof (MonoMethodVar));
1104         }
1105
1106         mono_jit_stats.allocate_var++;
1107
1108         MONO_INST_NEW (cfg, inst, opcode);
1109         inst->inst_c0 = num;
1110         inst->inst_vtype = type;
1111         inst->klass = mono_class_from_mono_type (type);
1112         type_to_eval_stack_type (cfg, type, inst);
1113         /* if set to 1 the variable is native */
1114         inst->backend.is_pinvoke = 0;
1115         inst->dreg = vreg;
1116
1117         cfg->varinfo [num] = inst;
1118
1119         MONO_INIT_VARINFO (&cfg->vars [num], num);
1120         MONO_VARINFO (cfg, num)->vreg = vreg;
1121
1122         if (vreg != -1)
1123                 set_vreg_to_inst (cfg, vreg, inst);
1124
1125 #if SIZEOF_REGISTER == 4
1126 #ifdef MONO_ARCH_SOFT_FLOAT
1127         regpair = mono_type_is_long (type) || mono_type_is_float (type);
1128 #else
1129         regpair = mono_type_is_long (type);
1130 #endif
1131 #else
1132         regpair = FALSE;
1133 #endif
1134
1135         if (regpair) {
1136                 MonoInst *tree;
1137
1138                 /* 
1139                  * These two cannot be allocated using create_var_for_vreg since that would
1140                  * put it into the cfg->varinfo array, confusing many parts of the JIT.
1141                  */
1142
1143                 /* 
1144                  * Set flags to VOLATILE so SSA skips it.
1145                  */
1146
1147                 if (cfg->verbose_level >= 4) {
1148                         printf ("  Create LVAR R%d (R%d, R%d)\n", inst->dreg, inst->dreg + 1, inst->dreg + 2);
1149                 }
1150
1151 #ifdef MONO_ARCH_SOFT_FLOAT
1152                 if (cfg->opt & MONO_OPT_SSA) {
1153                         if (mono_type_is_float (type))
1154                                 inst->flags = MONO_INST_VOLATILE;
1155                 }
1156 #endif
1157
1158                 /* Allocate a dummy MonoInst for the first vreg */
1159                 MONO_INST_NEW (cfg, tree, OP_LOCAL);
1160                 tree->dreg = inst->dreg + 1;
1161                 if (cfg->opt & MONO_OPT_SSA)
1162                         tree->flags = MONO_INST_VOLATILE;
1163                 tree->inst_c0 = num;
1164                 tree->type = STACK_I4;
1165                 tree->inst_vtype = &mono_defaults.int32_class->byval_arg;
1166                 tree->klass = mono_class_from_mono_type (tree->inst_vtype);
1167
1168                 set_vreg_to_inst (cfg, inst->dreg + 1, tree);
1169
1170                 /* Allocate a dummy MonoInst for the second vreg */
1171                 MONO_INST_NEW (cfg, tree, OP_LOCAL);
1172                 tree->dreg = inst->dreg + 2;
1173                 if (cfg->opt & MONO_OPT_SSA)
1174                         tree->flags = MONO_INST_VOLATILE;
1175                 tree->inst_c0 = num;
1176                 tree->type = STACK_I4;
1177                 tree->inst_vtype = &mono_defaults.int32_class->byval_arg;
1178                 tree->klass = mono_class_from_mono_type (tree->inst_vtype);
1179
1180                 set_vreg_to_inst (cfg, inst->dreg + 2, tree);
1181         }
1182
1183         cfg->num_varinfo++;
1184         if (cfg->verbose_level > 2)
1185                 g_print ("created temp %d (R%d) of type %s\n", num, vreg, mono_type_get_name (type));
1186         return inst;
1187 }
1188
1189 MonoInst*
1190 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1191 {
1192         int dreg;
1193
1194         if (mono_type_is_long (type))
1195                 dreg = mono_alloc_dreg (cfg, STACK_I8);
1196 #ifdef MONO_ARCH_SOFT_FLOAT
1197         else if (mono_type_is_float (type))
1198                 dreg = mono_alloc_dreg (cfg, STACK_R8);
1199 #endif
1200         else
1201                 /* All the others are unified */
1202                 dreg = mono_alloc_preg (cfg);
1203
1204         return mono_compile_create_var_for_vreg (cfg, type, opcode, dreg);
1205 }
1206
1207 /*
1208  * Transform a MonoInst into a load from the variable of index var_index.
1209  */
1210 void
1211 mono_compile_make_var_load (MonoCompile *cfg, MonoInst *dest, gssize var_index) {
1212         memset (dest, 0, sizeof (MonoInst));
1213         dest->inst_i0 = cfg->varinfo [var_index];
1214         dest->opcode = mini_type_to_ldind (cfg, dest->inst_i0->inst_vtype);
1215         type_to_eval_stack_type (cfg, dest->inst_i0->inst_vtype, dest);
1216         dest->klass = dest->inst_i0->klass;
1217 }
1218
1219 #endif
1220
1221 static MonoType*
1222 type_from_stack_type (MonoInst *ins) {
1223         switch (ins->type) {
1224         case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1225         case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1226         case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1227         case STACK_R8: return &mono_defaults.double_class->byval_arg;
1228         case STACK_MP:
1229                 /* 
1230                  * this if used to be commented without any specific reason, but
1231                  * it breaks #80235 when commented
1232                  */
1233                 if (ins->klass)
1234                         return &ins->klass->this_arg;
1235                 else
1236                         return &mono_defaults.object_class->this_arg;
1237         case STACK_OBJ:
1238                 /* ins->klass may not be set for ldnull.
1239                  * Also, if we have a boxed valuetype, we want an object lass,
1240                  * not the valuetype class
1241                  */
1242                 if (ins->klass && !ins->klass->valuetype)
1243                         return &ins->klass->byval_arg;
1244                 return &mono_defaults.object_class->byval_arg;
1245         case STACK_VTYPE: return &ins->klass->byval_arg;
1246         default:
1247                 g_error ("stack type %d to montype not handled\n", ins->type);
1248         }
1249         return NULL;
1250 }
1251
1252 MonoType*
1253 mono_type_from_stack_type (MonoInst *ins) {
1254         return type_from_stack_type (ins);
1255 }
1256
1257 /*
1258  * mono_add_ins_to_end:
1259  *
1260  *   Same as MONO_ADD_INS, but add INST before any branches at the end of BB.
1261  */
1262 void
1263 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
1264 {
1265         int opcode;
1266
1267         if (!bb->code) {
1268                 MONO_ADD_INS (bb, inst);
1269                 return;
1270         }
1271
1272         switch (bb->last_ins->opcode) {
1273         case OP_BR:
1274         case OP_BR_REG:
1275         case CEE_BEQ:
1276         case CEE_BGE:
1277         case CEE_BGT:
1278         case CEE_BLE:
1279         case CEE_BLT:
1280         case CEE_BNE_UN:
1281         case CEE_BGE_UN:
1282         case CEE_BGT_UN:
1283         case CEE_BLE_UN:
1284         case CEE_BLT_UN:
1285         case OP_SWITCH:
1286                 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
1287                 break;
1288         default:
1289                 if (MONO_IS_COND_BRANCH_OP (bb->last_ins)) {
1290                         /* Need to insert the ins before the compare */
1291                         if (bb->code == bb->last_ins) {
1292                                 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
1293                                 return;
1294                         }
1295
1296                         if (bb->code->next == bb->last_ins) {
1297                                 /* Only two instructions */
1298                                 opcode = bb->code->opcode;
1299
1300                                 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)) {
1301                                         /* NEW IR */
1302                                         mono_bblock_insert_before_ins (bb, bb->code, inst);
1303                                 } else {
1304                                         mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
1305                                 }
1306                         } else {
1307                                 opcode = bb->last_ins->prev->opcode;
1308
1309                                 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)) {
1310                                         /* NEW IR */
1311                                         mono_bblock_insert_before_ins (bb, bb->last_ins->prev, inst);
1312                                 } else {
1313                                         mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
1314                                 }                                       
1315                         }
1316                 }
1317                 else
1318                         MONO_ADD_INS (bb, inst);
1319                 break;
1320         }
1321 }
1322
1323 void
1324 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
1325 {
1326         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
1327         MonoJumpInfoBBTable *table;
1328
1329         table = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
1330         table->table = bbs;
1331         table->table_size = num_blocks;
1332         
1333         ji->ip.label = label;
1334         ji->type = MONO_PATCH_INFO_SWITCH;
1335         ji->data.table = table;
1336         ji->next = cfg->patch_info;
1337         cfg->patch_info = ji;
1338 }
1339
1340 static MonoMethodSignature *
1341 mono_get_array_new_va_signature (int arity)
1342 {
1343         static GHashTable *sighash = NULL;
1344         MonoMethodSignature *res;
1345         int i;
1346
1347         mono_jit_lock ();
1348         if (!sighash) {
1349                 sighash = g_hash_table_new (NULL, NULL);
1350         }
1351         else if ((res = g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
1352                 mono_jit_unlock ();
1353                 return res;
1354         }
1355
1356         res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
1357
1358         res->pinvoke = 1;
1359 #ifdef MONO_ARCH_VARARG_ICALLS
1360         /* Only set this only some archs since not all backends can handle varargs+pinvoke */
1361         res->call_convention = MONO_CALL_VARARG;
1362 #endif
1363
1364 #ifdef TARGET_WIN32
1365         res->call_convention = MONO_CALL_C;
1366 #endif
1367
1368         res->params [0] = &mono_defaults.int_class->byval_arg;  
1369         for (i = 0; i < arity; i++)
1370                 res->params [i + 1] = &mono_defaults.int_class->byval_arg;
1371
1372         res->ret = &mono_defaults.object_class->byval_arg;
1373
1374         g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
1375         mono_jit_unlock ();
1376
1377         return res;
1378 }
1379
1380 MonoJitICallInfo *
1381 mono_get_array_new_va_icall (int rank)
1382 {
1383         MonoMethodSignature *esig;
1384         char icall_name [256];
1385         char *name;
1386         MonoJitICallInfo *info;
1387
1388         /* Need to register the icall so it gets an icall wrapper */
1389         sprintf (icall_name, "ves_array_new_va_%d", rank);
1390
1391         mono_jit_lock ();
1392         info = mono_find_jit_icall_by_name (icall_name);
1393         if (info == NULL) {
1394                 esig = mono_get_array_new_va_signature (rank);
1395                 name = g_strdup (icall_name);
1396                 info = mono_register_jit_icall (mono_array_new_va, name, esig, FALSE);
1397
1398                 g_hash_table_insert (jit_icall_name_hash, name, name);
1399         }
1400         mono_jit_unlock ();
1401
1402         return info;
1403 }
1404
1405 gboolean
1406 mini_class_is_system_array (MonoClass *klass)
1407 {
1408         if (klass->parent == mono_defaults.array_class)
1409                 return TRUE;
1410         else
1411                 return FALSE;
1412 }
1413
1414 gboolean
1415 mini_assembly_can_skip_verification (MonoDomain *domain, MonoMethod *method)
1416 {
1417         MonoAssembly *assembly = method->klass->image->assembly;
1418         if (method->wrapper_type != MONO_WRAPPER_NONE && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
1419                 return FALSE;
1420         if (assembly->in_gac || assembly->image == mono_defaults.corlib)
1421                 return FALSE;
1422         if (mono_security_get_mode () != MONO_SECURITY_MODE_NONE)
1423                 return FALSE;
1424         return mono_assembly_has_skip_verification (assembly);
1425 }
1426
1427 /*
1428  * mini_method_verify:
1429  * 
1430  * Verify the method using the new verfier.
1431  * 
1432  * Returns true if the method is invalid. 
1433  */
1434 static gboolean
1435 mini_method_verify (MonoCompile *cfg, MonoMethod *method, gboolean fail_compile)
1436 {
1437         GSList *tmp, *res;
1438         gboolean is_fulltrust;
1439         MonoLoaderError *error;
1440
1441         if (method->verification_success)
1442                 return FALSE;
1443
1444         is_fulltrust = mono_verifier_is_method_full_trust (method);
1445
1446         if (!mono_verifier_is_enabled_for_method (method))
1447                 return FALSE;
1448
1449         res = mono_method_verify_with_current_settings (method, cfg->skip_visibility);
1450
1451         if ((error = mono_loader_get_last_error ())) {
1452                 if (fail_compile)
1453                         cfg->exception_type = error->exception_type;
1454                 else
1455                         mono_loader_clear_error ();
1456                 if (res)
1457                         mono_free_verify_list (res);
1458                 return TRUE;
1459         }
1460
1461         if (res) { 
1462                 for (tmp = res; tmp; tmp = tmp->next) {
1463                         MonoVerifyInfoExtended *info = (MonoVerifyInfoExtended *)tmp->data;
1464                         if (info->info.status == MONO_VERIFY_ERROR) {
1465                                 if (fail_compile) {
1466                                 char *method_name = mono_method_full_name (method, TRUE);
1467                                         cfg->exception_type = info->exception_type;
1468                                         cfg->exception_message = g_strdup_printf ("Error verifying %s: %s", method_name, info->info.message);
1469                                         g_free (method_name);
1470                                 }
1471                                 mono_free_verify_list (res);
1472                                 return TRUE;
1473                         }
1474                         if (info->info.status == MONO_VERIFY_NOT_VERIFIABLE && (!is_fulltrust || info->exception_type == MONO_EXCEPTION_METHOD_ACCESS || info->exception_type == MONO_EXCEPTION_FIELD_ACCESS)) {
1475                                 if (fail_compile) {
1476                                         char *method_name = mono_method_full_name (method, TRUE);
1477                                         cfg->exception_type = info->exception_type;
1478                                         cfg->exception_message = g_strdup_printf ("Error verifying %s: %s", method_name, info->info.message);
1479                                         g_free (method_name);
1480                                 }
1481                                 mono_free_verify_list (res);
1482                                 return TRUE;
1483                         }
1484                 }
1485                 mono_free_verify_list (res);
1486         }
1487         method->verification_success = 1;
1488         return FALSE;
1489 }
1490
1491 /*Returns true if something went wrong*/
1492 gboolean
1493 mono_compile_is_broken (MonoCompile *cfg, MonoMethod *method, gboolean fail_compile)
1494 {
1495         MonoMethod *method_definition = method;
1496         gboolean dont_verify = mini_assembly_can_skip_verification (cfg->domain, method);
1497         dont_verify |= method->klass->image->assembly->corlib_internal;
1498
1499         while (method_definition->is_inflated) {
1500                 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
1501                 method_definition = imethod->declaring;
1502         }
1503
1504         return !dont_verify && mini_method_verify (cfg, method_definition, fail_compile);
1505 }
1506
1507 static gconstpointer
1508 mono_icall_get_wrapper_full (MonoJitICallInfo* callinfo, gboolean do_compile)
1509 {
1510         char *name;
1511         MonoMethod *wrapper;
1512         gconstpointer trampoline;
1513         MonoDomain *domain = mono_get_root_domain ();
1514         
1515         if (callinfo->wrapper) {
1516                 return callinfo->wrapper;
1517         }
1518
1519         if (callinfo->trampoline)
1520                 return callinfo->trampoline;
1521
1522         /* 
1523          * We use the lock on the root domain instead of the JIT lock to protect 
1524          * callinfo->trampoline, since we do a lot of stuff inside the critical section.
1525          */
1526         mono_loader_lock (); /*FIXME mono_compile_method requires the loader lock, by large.*/
1527         mono_domain_lock (domain);
1528
1529         if (callinfo->trampoline) {
1530                 mono_domain_unlock (domain);
1531                 mono_loader_unlock ();
1532                 return callinfo->trampoline;
1533         }
1534
1535         name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1536         wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1537         g_free (name);
1538
1539         if (do_compile)
1540                 trampoline = mono_compile_method (wrapper);
1541         else
1542                 trampoline = mono_create_ftnptr (domain, mono_create_jit_trampoline_in_domain (domain, wrapper));
1543         mono_register_jit_icall_wrapper (callinfo, trampoline);
1544
1545         callinfo->trampoline = trampoline;
1546
1547         mono_domain_unlock (domain);
1548         mono_loader_unlock ();
1549         
1550         return callinfo->trampoline;
1551 }
1552
1553 gconstpointer
1554 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
1555 {
1556         return mono_icall_get_wrapper_full (callinfo, FALSE);
1557 }
1558
1559 static void
1560 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
1561 {
1562         if (!domain_jit_info (domain)->dynamic_code_hash)
1563                 domain_jit_info (domain)->dynamic_code_hash = g_hash_table_new (NULL, NULL);
1564         g_hash_table_insert (domain_jit_info (domain)->dynamic_code_hash, method, ji);
1565 }
1566
1567 static MonoJitDynamicMethodInfo*
1568 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
1569 {
1570         MonoJitDynamicMethodInfo *res;
1571
1572         if (domain_jit_info (domain)->dynamic_code_hash)
1573                 res = g_hash_table_lookup (domain_jit_info (domain)->dynamic_code_hash, method);
1574         else
1575                 res = NULL;
1576         return res;
1577 }
1578
1579 typedef struct {
1580         MonoClass *vtype;
1581         GList *active, *inactive;
1582         GSList *slots;
1583 } StackSlotInfo;
1584
1585 static gint 
1586 compare_by_interval_start_pos_func (gconstpointer a, gconstpointer b)
1587 {
1588         MonoMethodVar *v1 = (MonoMethodVar*)a;
1589         MonoMethodVar *v2 = (MonoMethodVar*)b;
1590
1591         if (v1 == v2)
1592                 return 0;
1593         else if (v1->interval->range && v2->interval->range)
1594                 return v1->interval->range->from - v2->interval->range->from;
1595         else if (v1->interval->range)
1596                 return -1;
1597         else
1598                 return 1;
1599 }
1600
1601 #ifndef DISABLE_JIT
1602
1603 #if 0
1604 #define LSCAN_DEBUG(a) do { a; } while (0)
1605 #else
1606 #define LSCAN_DEBUG(a)
1607 #endif
1608
1609 static gint32*
1610 mono_allocate_stack_slots_full2 (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
1611 {
1612         int i, slot, offset, size;
1613         guint32 align;
1614         MonoMethodVar *vmv;
1615         MonoInst *inst;
1616         gint32 *offsets;
1617         GList *vars = NULL, *l, *unhandled;
1618         StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
1619         MonoType *t;
1620         int nvtypes;
1621         gboolean reuse_slot;
1622
1623         LSCAN_DEBUG (printf ("Allocate Stack Slots 2 for %s:\n", mono_method_full_name (cfg->method, TRUE)));
1624
1625         scalar_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
1626         vtype_stack_slots = NULL;
1627         nvtypes = 0;
1628
1629         offsets = mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
1630         for (i = 0; i < cfg->num_varinfo; ++i)
1631                 offsets [i] = -1;
1632
1633         for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1634                 inst = cfg->varinfo [i];
1635                 vmv = MONO_VARINFO (cfg, i);
1636
1637                 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
1638                         continue;
1639
1640                 vars = g_list_prepend (vars, vmv);
1641         }
1642
1643         vars = g_list_sort (g_list_copy (vars), compare_by_interval_start_pos_func);
1644
1645         /* Sanity check */
1646         /*
1647         i = 0;
1648         for (unhandled = vars; unhandled; unhandled = unhandled->next) {
1649                 MonoMethodVar *current = unhandled->data;
1650
1651                 if (current->interval->range) {
1652                         g_assert (current->interval->range->from >= i);
1653                         i = current->interval->range->from;
1654                 }
1655         }
1656         */
1657
1658         offset = 0;
1659         *stack_align = 0;
1660         for (unhandled = vars; unhandled; unhandled = unhandled->next) {
1661                 MonoMethodVar *current = unhandled->data;
1662
1663                 vmv = current;
1664                 inst = cfg->varinfo [vmv->idx];
1665
1666                 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
1667                 * pinvoke wrappers when they call functions returning structures */
1668                 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF) {
1669                         size = mono_class_native_size (mono_class_from_mono_type (inst->inst_vtype), &align);
1670                 }
1671                 else {
1672                         int ialign;
1673
1674                         size = mono_type_size (inst->inst_vtype, &ialign);
1675                         align = ialign;
1676
1677                         if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (inst->inst_vtype)))
1678                                 align = 16;
1679                 }
1680
1681                 reuse_slot = TRUE;
1682                 if (cfg->disable_reuse_stack_slots)
1683                         reuse_slot = FALSE;
1684
1685                 t = mono_type_get_underlying_type (inst->inst_vtype);
1686                 switch (t->type) {
1687                 case MONO_TYPE_GENERICINST:
1688                         if (!mono_type_generic_inst_is_valuetype (t)) {
1689                                 slot_info = &scalar_stack_slots [t->type];
1690                                 break;
1691                         }
1692                         /* Fall through */
1693                 case MONO_TYPE_VALUETYPE:
1694                         if (!vtype_stack_slots)
1695                                 vtype_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * 256);
1696                         for (i = 0; i < nvtypes; ++i)
1697                                 if (t->data.klass == vtype_stack_slots [i].vtype)
1698                                         break;
1699                         if (i < nvtypes)
1700                                 slot_info = &vtype_stack_slots [i];
1701                         else {
1702                                 g_assert (nvtypes < 256);
1703                                 vtype_stack_slots [nvtypes].vtype = t->data.klass;
1704                                 slot_info = &vtype_stack_slots [nvtypes];
1705                                 nvtypes ++;
1706                         }
1707                         if (cfg->disable_reuse_ref_stack_slots)
1708                                 reuse_slot = FALSE;
1709                         break;
1710
1711                 case MONO_TYPE_PTR:
1712                 case MONO_TYPE_I:
1713                 case MONO_TYPE_U:
1714 #if SIZEOF_VOID_P == 4
1715                 case MONO_TYPE_I4:
1716 #else
1717                 case MONO_TYPE_I8:
1718 #endif
1719                         if (cfg->disable_ref_noref_stack_slot_share) {
1720                                 slot_info = &scalar_stack_slots [MONO_TYPE_I];
1721                                 break;
1722                         }
1723                         /* Fall through */
1724
1725                 case MONO_TYPE_CLASS:
1726                 case MONO_TYPE_OBJECT:
1727                 case MONO_TYPE_ARRAY:
1728                 case MONO_TYPE_SZARRAY:
1729                 case MONO_TYPE_STRING:
1730                         /* Share non-float stack slots of the same size */
1731                         slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
1732                         if (cfg->disable_reuse_ref_stack_slots)
1733                                 reuse_slot = FALSE;
1734                         break;
1735
1736                 default:
1737                         slot_info = &scalar_stack_slots [t->type];
1738                 }
1739
1740                 slot = 0xffffff;
1741                 if (cfg->comp_done & MONO_COMP_LIVENESS) {
1742                         int pos;
1743                         gboolean changed;
1744
1745                         //printf ("START  %2d %08x %08x\n",  vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
1746
1747                         if (!current->interval->range) {
1748                                 if (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))
1749                                         pos = ~0;
1750                                 else {
1751                                         /* Dead */
1752                                         inst->flags |= MONO_INST_IS_DEAD;
1753                                         continue;
1754                                 }
1755                         }
1756                         else
1757                                 pos = current->interval->range->from;
1758
1759                         LSCAN_DEBUG (printf ("process R%d ", inst->dreg));
1760                         if (current->interval->range)
1761                                 LSCAN_DEBUG (mono_linterval_print (current->interval));
1762                         LSCAN_DEBUG (printf ("\n"));
1763
1764                         /* Check for intervals in active which expired or inactive */
1765                         changed = TRUE;
1766                         /* FIXME: Optimize this */
1767                         while (changed) {
1768                                 changed = FALSE;
1769                                 for (l = slot_info->active; l != NULL; l = l->next) {
1770                                         MonoMethodVar *v = (MonoMethodVar*)l->data;
1771
1772                                         if (v->interval->last_range->to < pos) {
1773                                                 slot_info->active = g_list_delete_link (slot_info->active, l);
1774                                                 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [v->idx]));
1775                                                 LSCAN_DEBUG (printf ("Interval R%d has expired, adding 0x%x to slots\n", cfg->varinfo [v->idx]->dreg, offsets [v->idx]));
1776                                                 changed = TRUE;
1777                                                 break;
1778                                         }
1779                                         else if (!mono_linterval_covers (v->interval, pos)) {
1780                                                 slot_info->inactive = g_list_append (slot_info->inactive, v);
1781                                                 slot_info->active = g_list_delete_link (slot_info->active, l);
1782                                                 LSCAN_DEBUG (printf ("Interval R%d became inactive\n", cfg->varinfo [v->idx]->dreg));
1783                                                 changed = TRUE;
1784                                                 break;
1785                                         }
1786                                 }
1787                         }
1788
1789                         /* Check for intervals in inactive which expired or active */
1790                         changed = TRUE;
1791                         /* FIXME: Optimize this */
1792                         while (changed) {
1793                                 changed = FALSE;
1794                                 for (l = slot_info->inactive; l != NULL; l = l->next) {
1795                                         MonoMethodVar *v = (MonoMethodVar*)l->data;
1796
1797                                         if (v->interval->last_range->to < pos) {
1798                                                 slot_info->inactive = g_list_delete_link (slot_info->inactive, l);
1799                                                 // FIXME: Enabling this seems to cause impossible to debug crashes
1800                                                 //slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [v->idx]));
1801                                                 LSCAN_DEBUG (printf ("Interval R%d has expired, adding 0x%x to slots\n", cfg->varinfo [v->idx]->dreg, offsets [v->idx]));
1802                                                 changed = TRUE;
1803                                                 break;
1804                                         }
1805                                         else if (mono_linterval_covers (v->interval, pos)) {
1806                                                 slot_info->active = g_list_append (slot_info->active, v);
1807                                                 slot_info->inactive = g_list_delete_link (slot_info->inactive, l);
1808                                                 LSCAN_DEBUG (printf ("\tInterval R%d became active\n", cfg->varinfo [v->idx]->dreg));
1809                                                 changed = TRUE;
1810                                                 break;
1811                                         }
1812                                 }
1813                         }
1814
1815                         /* 
1816                          * This also handles the case when the variable is used in an
1817                          * exception region, as liveness info is not computed there.
1818                          */
1819                         /* 
1820                          * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
1821                          * opcodes.
1822                          */
1823                         if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
1824                                 if (slot_info->slots) {
1825                                         slot = GPOINTER_TO_INT (slot_info->slots->data);
1826
1827                                         slot_info->slots = slot_info->slots->next;
1828                                 }
1829
1830                                 /* FIXME: We might want to consider the inactive intervals as well if slot_info->slots is empty */
1831
1832                                 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
1833                         }
1834                 }
1835
1836 #if 0
1837                 {
1838                         static int count = 0;
1839                         count ++;
1840
1841                         if (count == atoi (getenv ("COUNT3")))
1842                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
1843                         if (count > atoi (getenv ("COUNT3")))
1844                                 slot = 0xffffff;
1845                         else {
1846                                 mono_print_ins (inst);
1847                                 }
1848                 }
1849 #endif
1850
1851                 LSCAN_DEBUG (printf ("R%d %s -> 0x%x\n", inst->dreg, mono_type_full_name (t), slot));
1852
1853                 if (!reuse_slot)
1854                         slot = 0xffffff;
1855
1856                 if (slot == 0xffffff) {
1857                         /*
1858                          * Allways allocate valuetypes to sizeof (gpointer) to allow more
1859                          * efficient copying (and to work around the fact that OP_MEMCPY
1860                          * and OP_MEMSET ignores alignment).
1861                          */
1862                         if (MONO_TYPE_ISSTRUCT (t)) {
1863                                 align = MAX (align, sizeof (gpointer));
1864                                 align = MAX (align, mono_class_min_align (mono_class_from_mono_type (t)));
1865                         }
1866
1867                         if (backward) {
1868                                 offset += size;
1869                                 offset += align - 1;
1870                                 offset &= ~(align - 1);
1871                                 slot = offset;
1872                         }
1873                         else {
1874                                 offset += align - 1;
1875                                 offset &= ~(align - 1);
1876                                 slot = offset;
1877                                 offset += size;
1878                         }
1879
1880                         if (*stack_align == 0)
1881                                 *stack_align = align;
1882                 }
1883
1884                 offsets [vmv->idx] = slot;
1885         }
1886         g_list_free (vars);
1887         for (i = 0; i < MONO_TYPE_PINNED; ++i) {
1888                 if (scalar_stack_slots [i].active)
1889                         g_list_free (scalar_stack_slots [i].active);
1890         }
1891         for (i = 0; i < nvtypes; ++i) {
1892                 if (vtype_stack_slots [i].active)
1893                         g_list_free (vtype_stack_slots [i].active);
1894         }
1895
1896         mono_jit_stats.locals_stack_size += offset;
1897
1898         *stack_size = offset;
1899         return offsets;
1900 }
1901
1902 /*
1903  *  mono_allocate_stack_slots_full:
1904  *
1905  *  Allocate stack slots for all non register allocated variables using a
1906  * linear scan algorithm.
1907  * Returns: an array of stack offsets.
1908  * STACK_SIZE is set to the amount of stack space needed.
1909  * STACK_ALIGN is set to the alignment needed by the locals area.
1910  */
1911 gint32*
1912 mono_allocate_stack_slots_full (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
1913 {
1914         int i, slot, offset, size;
1915         guint32 align;
1916         MonoMethodVar *vmv;
1917         MonoInst *inst;
1918         gint32 *offsets;
1919         GList *vars = NULL, *l;
1920         StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
1921         MonoType *t;
1922         int nvtypes;
1923         gboolean reuse_slot;
1924
1925         if ((cfg->num_varinfo > 0) && MONO_VARINFO (cfg, 0)->interval)
1926                 return mono_allocate_stack_slots_full2 (cfg, backward, stack_size, stack_align);
1927
1928         scalar_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
1929         vtype_stack_slots = NULL;
1930         nvtypes = 0;
1931
1932         offsets = mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
1933         for (i = 0; i < cfg->num_varinfo; ++i)
1934                 offsets [i] = -1;
1935
1936         for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1937                 inst = cfg->varinfo [i];
1938                 vmv = MONO_VARINFO (cfg, i);
1939
1940                 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
1941                         continue;
1942
1943                 vars = g_list_prepend (vars, vmv);
1944         }
1945
1946         vars = mono_varlist_sort (cfg, vars, 0);
1947         offset = 0;
1948         *stack_align = SIZEOF_REGISTER;
1949         for (l = vars; l; l = l->next) {
1950                 vmv = l->data;
1951                 inst = cfg->varinfo [vmv->idx];
1952
1953                 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
1954                 * pinvoke wrappers when they call functions returning structures */
1955                 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF) {
1956                         size = mono_class_native_size (mono_class_from_mono_type (inst->inst_vtype), &align);
1957                 } else {
1958                         int ialign;
1959
1960                         size = mono_type_size (inst->inst_vtype, &ialign);
1961                         align = ialign;
1962
1963                         if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (inst->inst_vtype)))
1964                                 align = 16;
1965                 }
1966
1967                 reuse_slot = TRUE;
1968                 if (cfg->disable_reuse_stack_slots)
1969                         reuse_slot = FALSE;
1970
1971                 t = mono_type_get_underlying_type (inst->inst_vtype);
1972                 if (t->byref) {
1973                         slot_info = &scalar_stack_slots [MONO_TYPE_I];
1974                 } else {
1975                         switch (t->type) {
1976                         case MONO_TYPE_GENERICINST:
1977                                 if (!mono_type_generic_inst_is_valuetype (t)) {
1978                                         slot_info = &scalar_stack_slots [t->type];
1979                                         break;
1980                                 }
1981                                 /* Fall through */
1982                         case MONO_TYPE_VALUETYPE:
1983                                 if (!vtype_stack_slots)
1984                                         vtype_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * 256);
1985                                 for (i = 0; i < nvtypes; ++i)
1986                                         if (t->data.klass == vtype_stack_slots [i].vtype)
1987                                                 break;
1988                                 if (i < nvtypes)
1989                                         slot_info = &vtype_stack_slots [i];
1990                                 else {
1991                                         g_assert (nvtypes < 256);
1992                                         vtype_stack_slots [nvtypes].vtype = t->data.klass;
1993                                         slot_info = &vtype_stack_slots [nvtypes];
1994                                         nvtypes ++;
1995                                 }
1996                                 if (cfg->disable_reuse_ref_stack_slots)
1997                                         reuse_slot = FALSE;
1998                                 break;
1999
2000                         case MONO_TYPE_PTR:
2001                         case MONO_TYPE_I:
2002                         case MONO_TYPE_U:
2003 #if SIZEOF_VOID_P == 4
2004                         case MONO_TYPE_I4:
2005 #else
2006                         case MONO_TYPE_I8:
2007 #endif
2008                                 if (cfg->disable_ref_noref_stack_slot_share) {
2009                                         slot_info = &scalar_stack_slots [MONO_TYPE_I];
2010                                         break;
2011                                 }
2012                                 /* Fall through */
2013
2014                         case MONO_TYPE_CLASS:
2015                         case MONO_TYPE_OBJECT:
2016                         case MONO_TYPE_ARRAY:
2017                         case MONO_TYPE_SZARRAY:
2018                         case MONO_TYPE_STRING:
2019                                 /* Share non-float stack slots of the same size */
2020                                 slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
2021                                 if (cfg->disable_reuse_ref_stack_slots)
2022                                         reuse_slot = FALSE;
2023                                 break;
2024
2025                         default:
2026                                 slot_info = &scalar_stack_slots [t->type];
2027                         }
2028                 }
2029
2030                 slot = 0xffffff;
2031                 if (cfg->comp_done & MONO_COMP_LIVENESS) {
2032                         //printf ("START  %2d %08x %08x\n",  vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
2033                         
2034                         /* expire old intervals in active */
2035                         while (slot_info->active) {
2036                                 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
2037
2038                                 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
2039                                         break;
2040
2041                                 //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);
2042
2043                                 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
2044                                 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
2045                         }
2046
2047                         /* 
2048                          * This also handles the case when the variable is used in an
2049                          * exception region, as liveness info is not computed there.
2050                          */
2051                         /* 
2052                          * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
2053                          * opcodes.
2054                          */
2055                         if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
2056                                 if (slot_info->slots) {
2057                                         slot = GPOINTER_TO_INT (slot_info->slots->data);
2058
2059                                         slot_info->slots = slot_info->slots->next;
2060                                 }
2061
2062                                 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
2063                         }
2064                 }
2065
2066                 {
2067                         static int count = 0;
2068                         count ++;
2069
2070                         /*
2071                         if (count == atoi (getenv ("COUNT")))
2072                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
2073                         if (count > atoi (getenv ("COUNT")))
2074                                 slot = 0xffffff;
2075                         else {
2076                                 mono_print_ins (inst);
2077                                 }
2078                         */
2079                 }
2080
2081                 if (!reuse_slot)
2082                         slot = 0xffffff;
2083
2084                 if (slot == 0xffffff) {
2085                         /*
2086                          * Allways allocate valuetypes to sizeof (gpointer) to allow more
2087                          * efficient copying (and to work around the fact that OP_MEMCPY
2088                          * and OP_MEMSET ignores alignment).
2089                          */
2090                         if (MONO_TYPE_ISSTRUCT (t)) {
2091                                 align = MAX (align, sizeof (gpointer));
2092                                 align = MAX (align, mono_class_min_align (mono_class_from_mono_type (t)));
2093                                 /* 
2094                                  * Align the size too so the code generated for passing vtypes in
2095                                  * registers doesn't overwrite random locals.
2096                                  */
2097                                 size = (size + (align - 1)) & ~(align -1);
2098                         }
2099
2100                         if (backward) {
2101                                 offset += size;
2102                                 offset += align - 1;
2103                                 offset &= ~(align - 1);
2104                                 slot = offset;
2105                         }
2106                         else {
2107                                 offset += align - 1;
2108                                 offset &= ~(align - 1);
2109                                 slot = offset;
2110                                 offset += size;
2111                         }
2112
2113                         *stack_align = MAX (*stack_align, align);
2114                 }
2115
2116                 offsets [vmv->idx] = slot;
2117         }
2118         g_list_free (vars);
2119         for (i = 0; i < MONO_TYPE_PINNED; ++i) {
2120                 if (scalar_stack_slots [i].active)
2121                         g_list_free (scalar_stack_slots [i].active);
2122         }
2123         for (i = 0; i < nvtypes; ++i) {
2124                 if (vtype_stack_slots [i].active)
2125                         g_list_free (vtype_stack_slots [i].active);
2126         }
2127
2128         mono_jit_stats.locals_stack_size += offset;
2129
2130         *stack_size = offset;
2131         return offsets;
2132 }
2133
2134 #else
2135
2136 gint32*
2137 mono_allocate_stack_slots_full (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
2138 {
2139         g_assert_not_reached ();
2140         return NULL;
2141 }
2142
2143 #endif /* DISABLE_JIT */
2144
2145 gint32*
2146 mono_allocate_stack_slots (MonoCompile *m, guint32 *stack_size, guint32 *stack_align)
2147 {
2148         return mono_allocate_stack_slots_full (m, TRUE, stack_size, stack_align);
2149 }
2150
2151 #define EMUL_HIT_SHIFT 3
2152 #define EMUL_HIT_MASK ((1 << EMUL_HIT_SHIFT) - 1)
2153 /* small hit bitmap cache */
2154 static mono_byte emul_opcode_hit_cache [(OP_LAST>>EMUL_HIT_SHIFT) + 1] = {0};
2155 static short emul_opcode_num = 0;
2156 static short emul_opcode_alloced = 0;
2157 static short *emul_opcode_opcodes = NULL;
2158 static MonoJitICallInfo **emul_opcode_map = NULL;
2159
2160 MonoJitICallInfo *
2161 mono_find_jit_opcode_emulation (int opcode)
2162 {
2163         g_assert (opcode >= 0 && opcode <= OP_LAST);
2164         if (emul_opcode_hit_cache [opcode >> (EMUL_HIT_SHIFT + 3)] & (1 << (opcode & EMUL_HIT_MASK))) {
2165                 int i;
2166                 for (i = 0; i < emul_opcode_num; ++i) {
2167                         if (emul_opcode_opcodes [i] == opcode)
2168                                 return emul_opcode_map [i];
2169                 }
2170         }
2171         return NULL;
2172 }
2173
2174 void
2175 mono_register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, gboolean no_throw)
2176 {
2177         MonoJitICallInfo *info;
2178         MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
2179
2180         g_assert (!sig->hasthis);
2181         g_assert (sig->param_count < 3);
2182
2183         info = mono_register_jit_icall (func, name, sig, no_throw);
2184
2185         if (emul_opcode_num >= emul_opcode_alloced) {
2186                 int incr = emul_opcode_alloced? emul_opcode_alloced/2: 16;
2187                 emul_opcode_alloced += incr;
2188                 emul_opcode_map = g_realloc (emul_opcode_map, sizeof (emul_opcode_map [0]) * emul_opcode_alloced);
2189                 emul_opcode_opcodes = g_realloc (emul_opcode_opcodes, sizeof (emul_opcode_opcodes [0]) * emul_opcode_alloced);
2190         }
2191         emul_opcode_map [emul_opcode_num] = info;
2192         emul_opcode_opcodes [emul_opcode_num] = opcode;
2193         emul_opcode_num++;
2194         emul_opcode_hit_cache [opcode >> (EMUL_HIT_SHIFT + 3)] |= (1 << (opcode & EMUL_HIT_MASK));
2195 }
2196
2197 static void
2198 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
2199 {
2200         MonoMethodSignature *sig;
2201
2202         if (sigstr)
2203                 sig = mono_create_icall_signature (sigstr);
2204         else
2205                 sig = NULL;
2206
2207         mono_register_jit_icall (func, name, sig, save);
2208 }
2209
2210 static void
2211 print_dfn (MonoCompile *cfg) {
2212         int i, j;
2213         char *code;
2214         MonoBasicBlock *bb;
2215         MonoInst *c;
2216
2217         {
2218                 char *method_name = mono_method_full_name (cfg->method, TRUE);
2219                 g_print ("IR code for method %s\n", method_name);
2220                 g_free (method_name);
2221         }
2222
2223         for (i = 0; i < cfg->num_bblocks; ++i) {
2224                 bb = cfg->bblocks [i];
2225                 /*if (bb->cil_code) {
2226                         char* code1, *code2;
2227                         code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
2228                         if (bb->last_ins->cil_code)
2229                                 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
2230                         else
2231                                 code2 = g_strdup ("");
2232
2233                         code1 [strlen (code1) - 1] = 0;
2234                         code = g_strdup_printf ("%s -> %s", code1, code2);
2235                         g_free (code1);
2236                         g_free (code2);
2237                 } else*/
2238                         code = g_strdup ("\n");
2239                 g_print ("\nBB%d (%d) (len: %d): %s", bb->block_num, i, bb->cil_length, code);
2240                 MONO_BB_FOR_EACH_INS (bb, c) {
2241                         mono_print_ins_index (-1, c);
2242                 }
2243
2244                 g_print ("\tprev:");
2245                 for (j = 0; j < bb->in_count; ++j) {
2246                         g_print (" BB%d", bb->in_bb [j]->block_num);
2247                 }
2248                 g_print ("\t\tsucc:");
2249                 for (j = 0; j < bb->out_count; ++j) {
2250                         g_print (" BB%d", bb->out_bb [j]->block_num);
2251                 }
2252                 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
2253
2254                 if (bb->idom)
2255                         g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
2256
2257                 if (bb->dominators)
2258                         mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
2259                 if (bb->dfrontier)
2260                         mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
2261                 g_free (code);
2262         }
2263
2264         g_print ("\n");
2265 }
2266
2267 void
2268 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
2269 {
2270         MONO_ADD_INS (bb, inst);
2271 }
2272
2273 void
2274 mono_bblock_insert_after_ins (MonoBasicBlock *bb, MonoInst *ins, MonoInst *ins_to_insert)
2275 {
2276         if (ins == NULL) {
2277                 ins = bb->code;
2278                 bb->code = ins_to_insert;
2279
2280                 /* Link with next */
2281                 ins_to_insert->next = ins;
2282                 if (ins)
2283                         ins->prev = ins_to_insert;
2284
2285                 if (bb->last_ins == NULL)
2286                         bb->last_ins = ins_to_insert;
2287         } else {
2288                 /* Link with next */
2289                 ins_to_insert->next = ins->next;
2290                 if (ins->next)
2291                         ins->next->prev = ins_to_insert;
2292
2293                 /* Link with previous */
2294                 ins->next = ins_to_insert;
2295                 ins_to_insert->prev = ins;
2296
2297                 if (bb->last_ins == ins)
2298                         bb->last_ins = ins_to_insert;
2299         }
2300 }
2301
2302 void
2303 mono_bblock_insert_before_ins (MonoBasicBlock *bb, MonoInst *ins, MonoInst *ins_to_insert)
2304 {
2305         if (ins == NULL) {
2306                 ins = bb->code;
2307                 if (ins)
2308                         ins->prev = ins_to_insert;
2309                 bb->code = ins_to_insert;
2310                 ins_to_insert->next = ins;
2311                 if (bb->last_ins == NULL)
2312                         bb->last_ins = ins_to_insert;
2313         } else {
2314                 /* Link with previous */
2315                 if (ins->prev)
2316                         ins->prev->next = ins_to_insert;
2317                 ins_to_insert->prev = ins->prev;
2318
2319                 /* Link with next */
2320                 ins->prev = ins_to_insert;
2321                 ins_to_insert->next = ins;
2322
2323                 if (bb->code == ins)
2324                         bb->code = ins_to_insert;
2325         }
2326 }
2327
2328 /*
2329  * mono_verify_bblock:
2330  *
2331  *   Verify that the next and prev pointers are consistent inside the instructions in BB.
2332  */
2333 void
2334 mono_verify_bblock (MonoBasicBlock *bb)
2335 {
2336         MonoInst *ins, *prev;
2337
2338         prev = NULL;
2339         for (ins = bb->code; ins; ins = ins->next) {
2340                 g_assert (ins->prev == prev);
2341                 prev = ins;
2342         }
2343         if (bb->last_ins)
2344                 g_assert (!bb->last_ins->next);
2345 }
2346
2347 /*
2348  * mono_verify_cfg:
2349  *
2350  *   Perform consistency checks on the JIT data structures and the IR
2351  */
2352 void
2353 mono_verify_cfg (MonoCompile *cfg)
2354 {
2355         MonoBasicBlock *bb;
2356
2357         for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2358                 mono_verify_bblock (bb);
2359 }
2360
2361 void
2362 mono_destroy_compile (MonoCompile *cfg)
2363 {
2364         GSList *l;
2365
2366         if (cfg->header)
2367                 mono_metadata_free_mh (cfg->header);
2368         //mono_mempool_stats (cfg->mempool);
2369         mono_free_loop_info (cfg);
2370         if (cfg->rs)
2371                 mono_regstate_free (cfg->rs);
2372         if (cfg->spvars)
2373                 g_hash_table_destroy (cfg->spvars);
2374         if (cfg->exvars)
2375                 g_hash_table_destroy (cfg->exvars);
2376         for (l = cfg->headers_to_free; l; l = l->next)
2377                 mono_metadata_free_mh (l->data);
2378         g_list_free (cfg->ldstr_list);
2379         g_hash_table_destroy (cfg->token_info_hash);
2380         if (cfg->abs_patches)
2381                 g_hash_table_destroy (cfg->abs_patches);
2382         mono_mempool_destroy (cfg->mempool);
2383
2384         mono_debug_free_method (cfg);
2385
2386         g_free (cfg->varinfo);
2387         g_free (cfg->vars);
2388         g_free (cfg->exception_message);
2389         g_free (cfg);
2390 }
2391
2392 #ifdef MINI_HAVE_FAST_TLS
2393 MINI_FAST_TLS_DECLARE(mono_lmf_addr);
2394 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
2395 /* 
2396  * When this is defined, the current lmf is stored in this tls variable instead of in 
2397  * jit_tls->lmf.
2398  */
2399 MINI_FAST_TLS_DECLARE(mono_lmf);
2400 #endif
2401 #endif
2402
2403 guint32
2404 mono_get_jit_tls_key (void)
2405 {
2406         return mono_jit_tls_id;
2407 }
2408
2409 gint32
2410 mono_get_jit_tls_offset (void)
2411 {
2412 #ifdef MINI_HAVE_FAST_TLS
2413         int offset;
2414         MINI_THREAD_VAR_OFFSET (mono_jit_tls, offset);
2415         return offset;
2416 #else
2417         return -1;
2418 #endif
2419 }
2420
2421 gint32
2422 mono_get_lmf_tls_offset (void)
2423 {
2424 #if defined(MINI_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
2425         int offset;
2426         MINI_THREAD_VAR_OFFSET(mono_lmf,offset);
2427         return offset;
2428 #else
2429         return -1;
2430 #endif
2431 }
2432
2433 gint32
2434 mono_get_lmf_addr_tls_offset (void)
2435 {
2436         int offset;
2437         MINI_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
2438         return offset;
2439 }
2440
2441 MonoLMF *
2442 mono_get_lmf (void)
2443 {
2444 #if defined(MINI_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
2445         return MINI_FAST_TLS_GET (mono_lmf);
2446 #else
2447         MonoJitTlsData *jit_tls;
2448
2449         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
2450                 return jit_tls->lmf;
2451
2452         g_assert_not_reached ();
2453         return NULL;
2454 #endif
2455 }
2456
2457 MonoLMF **
2458 mono_get_lmf_addr (void)
2459 {
2460 #ifdef MINI_HAVE_FAST_TLS
2461         return MINI_FAST_TLS_GET (mono_lmf_addr);
2462 #else
2463         MonoJitTlsData *jit_tls;
2464
2465         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
2466                 return &jit_tls->lmf;
2467
2468         /*
2469          * When resolving the call to mono_jit_thread_attach full-aot will look
2470          * in the plt, which causes a call into the generic trampoline, which in turn
2471          * tries to resolve the lmf_addr creating a cyclic dependency.  We cannot
2472          * call mono_jit_thread_attach from the native-to-managed wrapper, without
2473          * mono_get_lmf_addr, and mono_get_lmf_addr requires the thread to be attached.
2474          */
2475
2476         mono_jit_thread_attach (NULL);
2477         
2478         if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
2479                 return &jit_tls->lmf;
2480
2481         g_assert_not_reached ();
2482         return NULL;
2483 #endif
2484 }
2485
2486 void
2487 mono_set_lmf (MonoLMF *lmf)
2488 {
2489 #if defined(MINI_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
2490         MINI_FAST_TLS_SET (mono_lmf, lmf);
2491 #endif
2492
2493         (*mono_get_lmf_addr ()) = lmf;
2494 }
2495
2496 static void
2497 mono_set_jit_tls (MonoJitTlsData *jit_tls)
2498 {
2499         TlsSetValue (mono_jit_tls_id, jit_tls);
2500
2501 #ifdef MINI_HAVE_FAST_TLS
2502         MINI_FAST_TLS_SET (mono_jit_tls, jit_tls);
2503 #endif
2504 }
2505
2506 static void
2507 mono_set_lmf_addr (gpointer lmf_addr)
2508 {
2509 #ifdef MINI_HAVE_FAST_TLS
2510         MINI_FAST_TLS_SET (mono_lmf_addr, lmf_addr);
2511 #endif
2512 }
2513
2514 /* Called by native->managed wrappers */
2515 void
2516 mono_jit_thread_attach (MonoDomain *domain)
2517 {
2518         if (!domain)
2519                 /* 
2520                  * Happens when called from AOTed code which is only used in the root
2521                  * domain.
2522                  */
2523                 domain = mono_get_root_domain ();
2524
2525 #ifdef MINI_HAVE_FAST_TLS
2526         if (!MINI_FAST_TLS_GET (mono_lmf_addr)) {
2527                 mono_thread_attach (domain);
2528         }
2529 #else
2530         if (!TlsGetValue (mono_jit_tls_id))
2531                 mono_thread_attach (domain);
2532 #endif
2533         if (mono_domain_get () != domain)
2534                 mono_domain_set (domain, TRUE);
2535 }       
2536
2537 /**
2538  * mono_thread_abort:
2539  * @obj: exception object
2540  *
2541  * abort the thread, print exception information and stack trace
2542  */
2543 static void
2544 mono_thread_abort (MonoObject *obj)
2545 {
2546         /* MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id); */
2547         
2548         /* handle_remove should be eventually called for this thread, too
2549         g_free (jit_tls);*/
2550
2551         if ((mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_LEGACY) ||
2552                         (obj->vtable->klass == mono_defaults.threadabortexception_class)) {
2553                 mono_thread_exit ();
2554         } else {
2555                 exit (mono_environment_exitcode_get ());
2556         }
2557 }
2558
2559 static void*
2560 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
2561 {
2562         MonoJitTlsData *jit_tls;
2563         MonoLMF *lmf;
2564
2565         jit_tls = TlsGetValue (mono_jit_tls_id);
2566         if (jit_tls)
2567                 return jit_tls;
2568
2569         jit_tls = g_new0 (MonoJitTlsData, 1);
2570
2571         jit_tls->abort_func = abort_func;
2572         jit_tls->end_of_stack = stack_start;
2573
2574         mono_set_jit_tls (jit_tls);
2575
2576         lmf = g_new0 (MonoLMF, 1);
2577         MONO_ARCH_INIT_TOP_LMF_ENTRY (lmf);
2578
2579         jit_tls->first_lmf = lmf;
2580
2581 #if defined(MINI_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
2582         /* jit_tls->lmf is unused */
2583         MINI_FAST_TLS_SET (mono_lmf, lmf);
2584         mono_set_lmf_addr (&mono_lmf);
2585 #else
2586         mono_set_lmf_addr (&jit_tls->lmf);
2587
2588         jit_tls->lmf = lmf;
2589 #endif
2590
2591         mono_arch_setup_jit_tls_data (jit_tls);
2592         mono_setup_altstack (jit_tls);
2593
2594         return jit_tls;
2595 }
2596
2597 static void
2598 free_jit_tls_data (MonoJitTlsData *jit_tls)
2599 {
2600         mono_arch_free_jit_tls_data (jit_tls);
2601         mono_free_altstack (jit_tls);
2602
2603         g_free (jit_tls->first_lmf);
2604         g_free (jit_tls);
2605 }
2606
2607 static void
2608 mono_thread_start_cb (intptr_t tid, gpointer stack_start, gpointer func)
2609 {
2610         MonoInternalThread *thread;
2611         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
2612         thread = mono_thread_internal_current ();
2613         mono_debugger_thread_created (tid, thread->root_domain_thread, jit_tls, func);
2614         if (thread)
2615                 thread->jit_data = jit_tls;
2616
2617         mono_arch_cpu_init ();
2618 }
2619
2620 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
2621
2622 static void
2623 mono_thread_abort_dummy (MonoObject *obj)
2624 {
2625   if (mono_thread_attach_aborted_cb)
2626     mono_thread_attach_aborted_cb (obj);
2627   else
2628     mono_thread_abort (obj);
2629 }
2630
2631 static void
2632 mono_thread_attach_cb (intptr_t tid, gpointer stack_start)
2633 {
2634         MonoInternalThread *thread;
2635         void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
2636         thread = mono_thread_internal_current ();
2637         mono_debugger_thread_created (tid, thread->root_domain_thread, (MonoJitTlsData *) jit_tls, NULL);
2638         if (thread)
2639                 thread->jit_data = jit_tls;
2640         if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
2641                 mono_runtime_setup_stat_profiler ();
2642
2643         mono_arch_cpu_init ();
2644 }
2645
2646 static void
2647 mini_thread_cleanup (MonoInternalThread *thread)
2648 {
2649         MonoJitTlsData *jit_tls = thread->jit_data;
2650
2651         if (jit_tls) {
2652                 mono_debugger_thread_cleanup (jit_tls);
2653
2654                 /* We can't clean up tls information if we are on another thread, it will clean up the wrong stuff
2655                  * It would be nice to issue a warning when this happens outside of the shutdown sequence. but it's
2656                  * not a trivial thing.
2657                  *
2658                  * The current offender is mono_thread_manage which cleanup threads from the outside.
2659                  */
2660                 if (thread == mono_thread_internal_current ()) {
2661                         mono_set_lmf (NULL);
2662                         mono_set_jit_tls (NULL);
2663                         mono_set_lmf_addr (NULL);
2664                 }
2665
2666                 free_jit_tls_data (jit_tls);
2667
2668                 thread->jit_data = NULL;
2669         }
2670 }
2671
2672 static MonoInst*
2673 mono_create_tls_get (MonoCompile *cfg, int offset)
2674 {
2675 #ifdef MONO_ARCH_HAVE_TLS_GET
2676         if (MONO_ARCH_HAVE_TLS_GET) {
2677                 MonoInst* ins;
2678
2679                 if (offset == -1)
2680                         return NULL;
2681
2682                 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
2683                 ins->dreg = mono_alloc_preg (cfg);
2684                 ins->inst_offset = offset;
2685                 return ins;
2686         }
2687 #endif
2688         return NULL;
2689 }
2690
2691 MonoInst*
2692 mono_get_jit_tls_intrinsic (MonoCompile *cfg)
2693 {
2694         return mono_create_tls_get (cfg, mono_get_jit_tls_offset ());
2695 }
2696
2697 MonoInst*
2698 mono_get_domain_intrinsic (MonoCompile* cfg)
2699 {
2700         return mono_create_tls_get (cfg, mono_domain_get_tls_offset ());
2701 }
2702
2703 MonoInst*
2704 mono_get_thread_intrinsic (MonoCompile* cfg)
2705 {
2706         return mono_create_tls_get (cfg, mono_thread_get_tls_offset ());
2707 }
2708
2709 void
2710 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
2711 {
2712         MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
2713
2714         ji->ip.i = ip;
2715         ji->type = type;
2716         ji->data.target = target;
2717         ji->next = cfg->patch_info;
2718
2719         cfg->patch_info = ji;
2720 }
2721
2722 MonoJumpInfo *
2723 mono_patch_info_list_prepend (MonoJumpInfo *list, int ip, MonoJumpInfoType type, gconstpointer target)
2724 {
2725         MonoJumpInfo *ji = g_new0 (MonoJumpInfo, 1);
2726
2727         ji->ip.i = ip;
2728         ji->type = type;
2729         ji->data.target = target;
2730         ji->next = list;
2731
2732         return ji;
2733 }
2734
2735 void
2736 mono_remove_patch_info (MonoCompile *cfg, int ip)
2737 {
2738         MonoJumpInfo **ji = &cfg->patch_info;
2739
2740         while (*ji) {
2741                 if ((*ji)->ip.i == ip)
2742                         *ji = (*ji)->next;
2743                 else
2744                         ji = &((*ji)->next);
2745         }
2746 }
2747
2748 /**
2749  * mono_patch_info_dup_mp:
2750  *
2751  * Make a copy of PATCH_INFO, allocating memory from the mempool MP.
2752  */
2753 MonoJumpInfo*
2754 mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info)
2755 {
2756         MonoJumpInfo *res = mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
2757         memcpy (res, patch_info, sizeof (MonoJumpInfo));
2758
2759         switch (patch_info->type) {
2760         case MONO_PATCH_INFO_RVA:
2761         case MONO_PATCH_INFO_LDSTR:
2762         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2763         case MONO_PATCH_INFO_LDTOKEN:
2764         case MONO_PATCH_INFO_DECLSEC:
2765                 res->data.token = mono_mempool_alloc (mp, sizeof (MonoJumpInfoToken));
2766                 memcpy (res->data.token, patch_info->data.token, sizeof (MonoJumpInfoToken));
2767                 break;
2768         case MONO_PATCH_INFO_SWITCH:
2769                 res->data.table = mono_mempool_alloc (mp, sizeof (MonoJumpInfoBBTable));
2770                 memcpy (res->data.table, patch_info->data.table, sizeof (MonoJumpInfoBBTable));
2771                 res->data.table->table = mono_mempool_alloc (mp, sizeof (MonoBasicBlock*) * patch_info->data.table->table_size);
2772                 memcpy (res->data.table->table, patch_info->data.table->table, sizeof (MonoBasicBlock*) * patch_info->data.table->table_size);
2773                 break;
2774         case MONO_PATCH_INFO_RGCTX_FETCH:
2775                 res->data.rgctx_entry = mono_mempool_alloc (mp, sizeof (MonoJumpInfoRgctxEntry));
2776                 memcpy (res->data.rgctx_entry, patch_info->data.rgctx_entry, sizeof (MonoJumpInfoRgctxEntry));
2777                 res->data.rgctx_entry->data = mono_patch_info_dup_mp (mp, res->data.rgctx_entry->data);
2778                 break;
2779         default:
2780                 break;
2781         }
2782
2783         return res;
2784 }
2785
2786 guint
2787 mono_patch_info_hash (gconstpointer data)
2788 {
2789         const MonoJumpInfo *ji = (MonoJumpInfo*)data;
2790
2791         switch (ji->type) {
2792         case MONO_PATCH_INFO_RVA:
2793         case MONO_PATCH_INFO_LDSTR:
2794         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2795         case MONO_PATCH_INFO_LDTOKEN:
2796         case MONO_PATCH_INFO_DECLSEC:
2797                 return (ji->type << 8) | ji->data.token->token;
2798         case MONO_PATCH_INFO_INTERNAL_METHOD:
2799                 return (ji->type << 8) | g_str_hash (ji->data.name);
2800         case MONO_PATCH_INFO_VTABLE:
2801         case MONO_PATCH_INFO_CLASS:
2802         case MONO_PATCH_INFO_IID:
2803         case MONO_PATCH_INFO_ADJUSTED_IID:
2804         case MONO_PATCH_INFO_CLASS_INIT:
2805         case MONO_PATCH_INFO_METHODCONST:
2806         case MONO_PATCH_INFO_METHOD:
2807         case MONO_PATCH_INFO_METHOD_JUMP:
2808         case MONO_PATCH_INFO_IMAGE:
2809         case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2810         case MONO_PATCH_INFO_FIELD:
2811         case MONO_PATCH_INFO_SFLDA:
2812         case MONO_PATCH_INFO_SEQ_POINT_INFO:
2813                 return (ji->type << 8) | (gssize)ji->data.target;
2814         default:
2815                 return (ji->type << 8);
2816         }
2817 }
2818
2819 /* 
2820  * mono_patch_info_equal:
2821  * 
2822  * This might fail to recognize equivalent patches, i.e. floats, so its only
2823  * usable in those cases where this is not a problem, i.e. sharing GOT slots
2824  * in AOT.
2825  */
2826 gint
2827 mono_patch_info_equal (gconstpointer ka, gconstpointer kb)
2828 {
2829         const MonoJumpInfo *ji1 = (MonoJumpInfo*)ka;
2830         const MonoJumpInfo *ji2 = (MonoJumpInfo*)kb;
2831
2832         if (ji1->type != ji2->type)
2833                 return 0;
2834
2835         switch (ji1->type) {
2836         case MONO_PATCH_INFO_RVA:
2837         case MONO_PATCH_INFO_LDSTR:
2838         case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2839         case MONO_PATCH_INFO_LDTOKEN:
2840         case MONO_PATCH_INFO_DECLSEC:
2841                 if ((ji1->data.token->image != ji2->data.token->image) ||
2842                         (ji1->data.token->token != ji2->data.token->token) || 
2843                         (ji1->data.token->has_context != ji2->data.token->has_context) ||
2844                         (ji1->data.token->context.class_inst != ji2->data.token->context.class_inst) ||
2845                         (ji1->data.token->context.method_inst != ji2->data.token->context.method_inst))
2846                         return 0;
2847                 break;
2848         case MONO_PATCH_INFO_INTERNAL_METHOD:
2849                 return g_str_equal (ji1->data.name, ji2->data.name);
2850
2851         case MONO_PATCH_INFO_RGCTX_FETCH: {
2852                 MonoJumpInfoRgctxEntry *e1 = ji1->data.rgctx_entry;
2853                 MonoJumpInfoRgctxEntry *e2 = ji2->data.rgctx_entry;
2854
2855                 return e1->method == e2->method && e1->in_mrgctx == e2->in_mrgctx && e1->info_type == e2->info_type && mono_patch_info_equal (e1->data, e2->data);
2856         }
2857         default:
2858                 if (ji1->data.target != ji2->data.target)
2859                         return 0;
2860                 break;
2861         }
2862
2863         return 1;
2864 }
2865
2866 gpointer
2867 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
2868 {
2869         unsigned char *ip = patch_info->ip.i + code;
2870         gconstpointer target = NULL;
2871
2872         switch (patch_info->type) {
2873         case MONO_PATCH_INFO_BB:
2874                 /* 
2875                  * FIXME: This could be hit for methods without a prolog. Should use -1
2876                  * but too much code depends on a 0 initial value.
2877                  */
2878                 //g_assert (patch_info->data.bb->native_offset);
2879                 target = patch_info->data.bb->native_offset + code;
2880                 break;
2881         case MONO_PATCH_INFO_ABS:
2882                 target = patch_info->data.target;
2883                 break;
2884         case MONO_PATCH_INFO_LABEL:
2885                 target = patch_info->data.inst->inst_c0 + code;
2886                 break;
2887         case MONO_PATCH_INFO_IP:
2888 #if defined(__native_client__) && defined(__native_client_codegen__)
2889                 /* Need to transform to the destination address, it's */
2890                 /* emitted as an immediate in the code. */
2891                 target = nacl_inverse_modify_patch_target(ip);
2892 #else
2893                 target = ip;
2894 #endif
2895                 break;
2896         case MONO_PATCH_INFO_METHOD_REL:
2897                 target = code + patch_info->data.offset;
2898                 break;
2899         case MONO_PATCH_INFO_INTERNAL_METHOD: {
2900                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
2901                 if (!mi) {
2902                         g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
2903                         g_assert_not_reached ();
2904                 }
2905                 target = mono_icall_get_wrapper (mi);
2906                 break;
2907         }
2908         case MONO_PATCH_INFO_METHOD_JUMP:
2909                 target = mono_create_jump_trampoline (domain, patch_info->data.method, FALSE);
2910 #if defined(__native_client__) && defined(__native_client_codegen__)
2911 #if defined(TARGET_AMD64)
2912                 /* This target is an absolute address, not relative to the */
2913                 /* current code being emitted on AMD64. */
2914                 target = nacl_inverse_modify_patch_target(target);
2915 #endif
2916 #endif
2917                 break;
2918         case MONO_PATCH_INFO_METHOD:
2919                 if (patch_info->data.method == method) {
2920                         target = code;
2921                 } else {
2922                         /* get the trampoline to the method from the domain */
2923                         target = mono_create_jit_trampoline (patch_info->data.method);
2924                 }
2925                 break;
2926         case MONO_PATCH_INFO_SWITCH: {
2927                 gpointer *jump_table;
2928                 int i;
2929
2930 #if defined(__native_client__) && defined(__native_client_codegen__)
2931                 /* This memory will leak, but we don't care if we're */
2932                 /* not deleting JIT'd methods anyway                 */
2933                 jump_table = g_malloc0 (sizeof(gpointer) * patch_info->data.table->table_size);
2934 #else
2935                 if (method && method->dynamic) {
2936                         jump_table = mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
2937                 } else {
2938                         if (mono_aot_only) {
2939                                 jump_table = mono_domain_alloc (domain, sizeof (gpointer) * patch_info->data.table->table_size);
2940                         } else {
2941                                 jump_table = mono_domain_code_reserve (domain, sizeof (gpointer) * patch_info->data.table->table_size);
2942                         }
2943                 }
2944 #endif
2945
2946                 for (i = 0; i < patch_info->data.table->table_size; i++) {
2947 #if defined(__native_client__) && defined(__native_client_codegen__)
2948                         /* 'code' is relative to the current code blob, we */
2949                         /* need to do this transform on it to make the     */
2950                         /* pointers in this table absolute                 */
2951                         jump_table [i] = nacl_inverse_modify_patch_target (code) + GPOINTER_TO_INT (patch_info->data.table->table [i]);
2952 #else
2953                         jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
2954 #endif
2955                 }
2956
2957 #if defined(__native_client__) && defined(__native_client_codegen__)
2958                 /* jump_table is in the data section, we need to transform */
2959                 /* it here so when it gets modified in amd64_patch it will */
2960                 /* then point back to the absolute data address            */
2961                 target = nacl_inverse_modify_patch_target (jump_table);
2962 #else
2963                 target = jump_table;
2964 #endif
2965                 break;
2966         }
2967         case MONO_PATCH_INFO_METHODCONST:
2968         case MONO_PATCH_INFO_CLASS:
2969         case MONO_PATCH_INFO_IMAGE:
2970         case MONO_PATCH_INFO_FIELD:
2971                 target = patch_info->data.target;
2972                 break;
2973         case MONO_PATCH_INFO_IID:
2974                 mono_class_init (patch_info->data.klass);
2975                 target = GINT_TO_POINTER ((int)patch_info->data.klass->interface_id);
2976                 break;
2977         case MONO_PATCH_INFO_ADJUSTED_IID:
2978                 mono_class_init (patch_info->data.klass);
2979                 target = GINT_TO_POINTER ((int)(-((patch_info->data.klass->interface_id + 1) * SIZEOF_VOID_P)));
2980                 break;
2981         case MONO_PATCH_INFO_VTABLE:
2982                 target = mono_class_vtable (domain, patch_info->data.klass);
2983                 g_assert (target);
2984                 break;
2985         case MONO_PATCH_INFO_CLASS_INIT: {
2986                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.klass);
2987
2988                 g_assert (vtable);
2989                 target = mono_create_class_init_trampoline (vtable);
2990                 break;
2991         }
2992         case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2993                 target = mono_create_delegate_trampoline (patch_info->data.klass);
2994                 break;
2995         case MONO_PATCH_INFO_SFLDA: {
2996                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
2997
2998                 if (mono_class_field_is_special_static (patch_info->data.field)) {
2999                         gpointer addr = NULL;
3000
3001                         mono_domain_lock (domain);
3002                         if (domain->special_static_fields)
3003                                 addr = g_hash_table_lookup (domain->special_static_fields, patch_info->data.field);
3004                         mono_domain_unlock (domain);
3005                         g_assert (addr);
3006                         return addr;
3007                 }
3008
3009                 g_assert (vtable);
3010                 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && (method && mono_class_needs_cctor_run (vtable->klass, method)))
3011                         /* Done by the generated code */
3012                         ;
3013                 else {
3014                         if (run_cctors)
3015                                 mono_runtime_class_init (vtable);
3016                 }
3017                 target = (char*)vtable->data + patch_info->data.field->offset;
3018                 break;
3019         }
3020         case MONO_PATCH_INFO_RVA: {
3021                 guint32 field_index = mono_metadata_token_index (patch_info->data.token->token);
3022                 guint32 rva;
3023
3024                 mono_metadata_field_info (patch_info->data.token->image, field_index - 1, NULL, &rva, NULL);
3025                 target = mono_image_rva_map (patch_info->data.token->image, rva);
3026                 break;
3027         }
3028         case MONO_PATCH_INFO_R4:
3029         case MONO_PATCH_INFO_R8:
3030                 target = patch_info->data.target;
3031                 break;
3032         case MONO_PATCH_INFO_EXC_NAME:
3033                 target = patch_info->data.name;
3034                 break;
3035         case MONO_PATCH_INFO_LDSTR:
3036                 target =
3037                         mono_ldstr (domain, patch_info->data.token->image, 
3038                                                 mono_metadata_token_index (patch_info->data.token->token));
3039                 break;
3040         case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
3041                 gpointer handle;
3042                 MonoClass *handle_class;
3043
3044                 handle = mono_ldtoken (patch_info->data.token->image, 
3045                                                            patch_info->data.token->token, &handle_class, patch_info->data.token->has_context ? &patch_info->data.token->context : NULL);
3046                 mono_class_init (handle_class);
3047                 mono_class_init (mono_class_from_mono_type (handle));
3048
3049                 target =
3050                         mono_type_get_object (domain, handle);
3051                 break;
3052         }
3053         case MONO_PATCH_INFO_LDTOKEN: {
3054                 gpointer handle;
3055                 MonoClass *handle_class;
3056                 
3057                 handle = mono_ldtoken (patch_info->data.token->image,
3058                                        patch_info->data.token->token, &handle_class, NULL);
3059                 mono_class_init (handle_class);
3060                 
3061                 target = handle;
3062                 break;
3063         }
3064         case MONO_PATCH_INFO_DECLSEC:
3065                 target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
3066                 break;
3067         case MONO_PATCH_INFO_ICALL_ADDR:
3068                 /* run_cctors == 0 -> AOT */
3069                 if (patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
3070                         if (run_cctors) {
3071                                 target = mono_lookup_pinvoke_call (patch_info->data.method, NULL, NULL);
3072                                 if (!target)
3073                                         g_error ("Unable to resolve pinvoke method '%s' Re-run with MONO_LOG_LEVEL=debug for more information.\n", mono_method_full_name (patch_info->data.method, TRUE));
3074                         } else {
3075                                 target = NULL;
3076                         }
3077                 } else {
3078                         target = mono_lookup_internal_call (patch_info->data.method);
3079
3080                         if (!target && run_cctors)
3081                                 g_error ("Unregistered icall '%s'\n", mono_method_full_name (patch_info->data.method, TRUE));
3082                 }
3083                 break;
3084         case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3085                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
3086                 if (!mi) {
3087                         g_warning ("unknown MONO_PATCH_INFO_JIT_ICALL_ADDR %s", patch_info->data.name);
3088                         g_assert_not_reached ();
3089                 }
3090                 target = mi->func;
3091                 break;
3092         }
3093         case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3094                 target = mono_thread_interruption_request_flag ();
3095                 break;
3096         case MONO_PATCH_INFO_METHOD_RGCTX: {
3097                 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.method->klass);
3098                 g_assert (vtable);
3099
3100                 target = mono_method_lookup_rgctx (vtable, mini_method_get_context (patch_info->data.method)->method_inst);
3101                 break;
3102         }
3103         case MONO_PATCH_INFO_BB_OVF:
3104         case MONO_PATCH_INFO_EXC_OVF:
3105         case MONO_PATCH_INFO_GOT_OFFSET:
3106         case MONO_PATCH_INFO_NONE:
3107                 break;
3108         case MONO_PATCH_INFO_RGCTX_FETCH: {
3109                 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3110                 guint32 slot = -1;
3111
3112                 switch (entry->data->type) {
3113                 case MONO_PATCH_INFO_CLASS:
3114                         slot = mono_method_lookup_or_register_other_info (entry->method, entry->in_mrgctx, &entry->data->data.klass->byval_arg, entry->info_type, mono_method_get_context (entry->method));
3115                         break;
3116                 case MONO_PATCH_INFO_METHOD:
3117                 case MONO_PATCH_INFO_METHODCONST:
3118                         slot = mono_method_lookup_or_register_other_info (entry->method, entry->in_mrgctx, entry->data->data.method, entry->info_type, mono_method_get_context (entry->method));
3119                         break;
3120                 case MONO_PATCH_INFO_FIELD:
3121                         slot = mono_method_lookup_or_register_other_info (entry->method, entry->in_mrgctx, entry->data->data.field, entry->info_type, mono_method_get_context (entry->method));
3122                         break;
3123                 default:
3124                         g_assert_not_reached ();
3125                         break;
3126                 }
3127
3128                 target = mono_create_rgctx_lazy_fetch_trampoline (slot);
3129                 break;
3130         }
3131         case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3132                 target = mono_create_generic_class_init_trampoline ();
3133                 break;
3134         case MONO_PATCH_INFO_MONITOR_ENTER:
3135                 target = mono_create_monitor_enter_trampoline ();
3136                 break;
3137         case MONO_PATCH_INFO_MONITOR_EXIT:
3138                 target = mono_create_monitor_exit_trampoline ();
3139                 break;
3140 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3141         case MONO_PATCH_INFO_SEQ_POINT_INFO:
3142                 if (!run_cctors)
3143                         /* AOT, not needed */
3144                         target = NULL;
3145                 else
3146                         target = mono_arch_get_seq_point_info (domain, code);
3147                 break;
3148 #endif
3149         case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3150 #ifdef MONO_ARCH_LLVM_SUPPORTED
3151                 g_assert (mono_use_llvm);
3152                 target = mono_create_llvm_imt_trampoline (domain, patch_info->data.imt_tramp->method, patch_info->data.imt_tramp->vt_offset);
3153 #else
3154                 g_assert_not_reached ();
3155 #endif
3156                 break;
3157         case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR: {
3158                 int card_table_shift_bits;
3159                 gpointer card_table_mask;
3160
3161                 target = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
3162                 break;
3163         }
3164         default:
3165                 g_assert_not_reached ();
3166         }
3167
3168         return (gpointer)target;
3169 }
3170
3171 void
3172 mono_add_seq_point (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, int native_offset)
3173 {
3174         ins->inst_offset = native_offset;
3175         g_ptr_array_add (cfg->seq_points, ins);
3176         bb->seq_points = g_slist_prepend_mempool (cfg->mempool, bb->seq_points, ins);
3177         bb->last_seq_point = ins;
3178 }
3179
3180 #ifndef DISABLE_JIT
3181
3182 static void
3183 mono_compile_create_vars (MonoCompile *cfg)
3184 {
3185         MonoMethodSignature *sig;
3186         MonoMethodHeader *header;
3187         int i;
3188
3189         header = cfg->header;
3190
3191         sig = mono_method_signature (cfg->method);
3192         
3193         if (!MONO_TYPE_IS_VOID (sig->ret)) {
3194                 cfg->ret = mono_compile_create_var (cfg, sig->ret, OP_ARG);
3195                 /* Inhibit optimizations */
3196                 cfg->ret->flags |= MONO_INST_VOLATILE;
3197         }
3198         if (cfg->verbose_level > 2)
3199                 g_print ("creating vars\n");
3200
3201         cfg->args = mono_mempool_alloc0 (cfg->mempool, (sig->param_count + sig->hasthis) * sizeof (MonoInst*));
3202
3203         if (sig->hasthis)
3204                 cfg->args [0] = mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
3205
3206         for (i = 0; i < sig->param_count; ++i) {
3207                 cfg->args [i + sig->hasthis] = mono_compile_create_var (cfg, sig->params [i], OP_ARG);
3208         }
3209
3210         if (cfg->verbose_level > 2) {
3211                 if (cfg->ret) {
3212                         printf ("\treturn : ");
3213                         mono_print_ins (cfg->ret);
3214                 }
3215
3216                 if (sig->hasthis) {
3217                         printf ("\tthis: ");
3218                         mono_print_ins (cfg->args [0]);
3219                 }
3220
3221                 for (i = 0; i < sig->param_count; ++i) {
3222                         printf ("\targ [%d]: ", i);
3223                         mono_print_ins (cfg->args [i + sig->hasthis]);
3224                 }
3225         }
3226
3227         cfg->locals_start = cfg->num_varinfo;
3228         cfg->locals = mono_mempool_alloc0 (cfg->mempool, header->num_locals * sizeof (MonoInst*));
3229
3230         if (cfg->verbose_level > 2)
3231                 g_print ("creating locals\n");
3232
3233         for (i = 0; i < header->num_locals; ++i)
3234                 cfg->locals [i] = mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
3235
3236         if (cfg->verbose_level > 2)
3237                 g_print ("locals done\n");
3238
3239         mono_arch_create_vars (cfg);
3240 }
3241
3242 #endif /* #ifndef DISABLE_JIT */
3243
3244 void
3245 mono_print_code (MonoCompile *cfg, const char* msg)
3246 {
3247         MonoBasicBlock *bb;
3248         
3249         for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
3250                 mono_print_bb (bb, msg);
3251 }
3252
3253 #ifndef DISABLE_JIT
3254
3255 static void
3256 mono_postprocess_patches (MonoCompile *cfg)
3257 {
3258         MonoJumpInfo *patch_info;
3259         int i;
3260
3261         for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3262                 switch (patch_info->type) {
3263                 case MONO_PATCH_INFO_ABS: {
3264                         MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
3265
3266                         /*
3267                          * Change patches of type MONO_PATCH_INFO_ABS into patches describing the 
3268                          * absolute address.
3269                          */
3270                         if (info) {
3271                                 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
3272                                 // FIXME: CLEAN UP THIS MESS.
3273                                 if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && 
3274                                         strstr (cfg->method->name, info->name)) {
3275                                         /*
3276                                          * This is an icall wrapper, and this is a call to the
3277                                          * wrapped function.
3278                                          */
3279                                         if (cfg->compile_aot) {
3280                                                 patch_info->type = MONO_PATCH_INFO_JIT_ICALL_ADDR;
3281                                                 patch_info->data.name = info->name;
3282                                         }
3283                                 } else {
3284                                         /* for these array methods we currently register the same function pointer
3285                                          * since it's a vararg function. But this means that mono_find_jit_icall_by_addr ()
3286                                          * will return the incorrect one depending on the order they are registered.
3287                                          * See tests/test-arr.cs
3288                                          */
3289                                         if (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL) {
3290                                                 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
3291                                                 patch_info->data.name = info->name;
3292                                         }
3293                                 }
3294                         }
3295
3296                         if (patch_info->type == MONO_PATCH_INFO_ABS) {
3297                                 if (cfg->abs_patches) {
3298                                         MonoJumpInfo *abs_ji = g_hash_table_lookup (cfg->abs_patches, patch_info->data.target);
3299                                         if (abs_ji) {
3300                                                 patch_info->type = abs_ji->type;
3301                                                 patch_info->data.target = abs_ji->data.target;
3302                                         }
3303                                 }
3304                         }
3305
3306                         break;
3307                 }
3308                 case MONO_PATCH_INFO_SWITCH: {
3309                         gpointer *table;
3310 #if defined(__native_client__) && defined(__native_client_codegen__)
3311                         /* This memory will leak.  */
3312                         /* TODO: can we free this when  */
3313                         /* making the final jump table? */
3314                         table = g_malloc0 (sizeof(gpointer) * patch_info->data.table->table_size);
3315 #else
3316                         if (cfg->method->dynamic) {
3317                                 table = mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
3318                         } else {
3319                                 table = mono_domain_code_reserve (cfg->domain, sizeof (gpointer) * patch_info->data.table->table_size);
3320                         }
3321 #endif
3322
3323                         for (i = 0; i < patch_info->data.table->table_size; i++) {
3324                                 /* Might be NULL if the switch is eliminated */
3325                                 if (patch_info->data.table->table [i]) {
3326                                         g_assert (patch_info->data.table->table [i]->native_offset);
3327                                         table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
3328                                 } else {
3329                                         table [i] = NULL;
3330                                 }
3331                         }
3332                         patch_info->data.table->table = (MonoBasicBlock**)table;
3333                         break;
3334                 }
3335                 case MONO_PATCH_INFO_METHOD_JUMP: {
3336                         GSList *list;
3337                         MonoDomain *domain = cfg->domain;
3338                         unsigned char *ip = cfg->native_code + patch_info->ip.i;
3339 #if defined(__native_client__) && defined(__native_client_codegen__)
3340                         /* When this jump target gets evaluated, the method */
3341                         /* will be installed in the dynamic code section,   */
3342                         /* not at the location of cfg->native_code.         */
3343                         ip = nacl_inverse_modify_patch_target (cfg->native_code) + patch_info->ip.i;
3344 #endif
3345
3346                         mono_domain_lock (domain);
3347                         if (!domain_jit_info (domain)->jump_target_hash)
3348                                 domain_jit_info (domain)->jump_target_hash = g_hash_table_new (NULL, NULL);
3349                         list = g_hash_table_lookup (domain_jit_info (domain)->jump_target_hash, patch_info->data.method);
3350                         list = g_slist_prepend (list, ip);
3351                         g_hash_table_insert (domain_jit_info (domain)->jump_target_hash, patch_info->data.method, list);
3352                         mono_domain_unlock (domain);
3353                         break;
3354                 }
3355                 default:
3356                         /* do nothing */
3357                         break;
3358                 }
3359         }
3360 }
3361
3362 static void
3363 collect_pred_seq_points (MonoBasicBlock *bb, MonoInst *ins, GSList **next, int depth)
3364 {
3365         int i;
3366         MonoBasicBlock *in_bb;
3367
3368         for (i = 0; i < bb->in_count; ++i) {
3369                 in_bb = bb->in_bb [i];
3370
3371                 if (in_bb->last_seq_point) {
3372                         next [in_bb->last_seq_point->backend.size] = g_slist_append (next [in_bb->last_seq_point->backend.size], GUINT_TO_POINTER (ins->backend.size));
3373                 } else {
3374                         /* Have to look at its predecessors */
3375                         if (depth < 5)
3376                                 collect_pred_seq_points (in_bb, ins, next, depth + 1);
3377                 }
3378         }
3379 }
3380
3381 static void
3382 mono_save_seq_point_info (MonoCompile *cfg)
3383 {
3384         MonoBasicBlock *bb;
3385         GSList *bb_seq_points, *l;
3386         MonoInst *last;
3387         MonoDomain *domain = cfg->domain;
3388         int i;
3389         MonoSeqPointInfo *info;
3390         GSList **next;
3391
3392         if (!cfg->seq_points)
3393                 return;
3394
3395         info = g_malloc0 (sizeof (MonoSeqPointInfo) + (cfg->seq_points->len - MONO_ZERO_LEN_ARRAY) * sizeof (SeqPoint));
3396         info->len = cfg->seq_points->len;
3397         for (i = 0; i < cfg->seq_points->len; ++i) {
3398                 SeqPoint *sp = &info->seq_points [i];
3399                 MonoInst *ins = g_ptr_array_index (cfg->seq_points, i);
3400
3401                 sp->il_offset = ins->inst_imm;
3402                 sp->native_offset = ins->inst_offset;
3403
3404                 /* Used below */
3405                 ins->backend.size = i;
3406         }
3407
3408         /*
3409          * For each sequence point, compute the list of sequence points immediately
3410          * following it, this is needed to implement 'step over' in the debugger agent.
3411          */ 
3412         next = g_new0 (GSList*, cfg->seq_points->len);
3413         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3414                 bb_seq_points = g_slist_reverse (bb->seq_points);
3415                 last = NULL;
3416                 for (l = bb_seq_points; l; l = l->next) {
3417                         MonoInst *ins = l->data;
3418
3419                         if (!(ins->flags & MONO_INST_SINGLE_STEP_LOC))
3420                                 continue;
3421
3422                         if (last != NULL) {
3423                                 /* Link with the previous seq point in the same bb */
3424                                 next [last->backend.size] = g_slist_append (next [last->backend.size], GUINT_TO_POINTER (ins->backend.size));
3425                         } else {
3426                                 /* Link with the last bb in the previous bblocks */
3427                                 collect_pred_seq_points (bb, ins, next, 0);
3428                         }
3429
3430                         last = ins;
3431                 }
3432         }
3433
3434         if (cfg->verbose_level > 2) {
3435                 printf ("\nSEQ POINT MAP: \n");
3436         }
3437
3438         for (i = 0; i < cfg->seq_points->len; ++i) {
3439                 SeqPoint *sp = &info->seq_points [i];
3440                 GSList *l;
3441                 int j, next_index;
3442
3443                 sp->next_len = g_slist_length (next [i]);
3444                 sp->next = g_new (int, sp->next_len);
3445                 j = 0;
3446                 if (cfg->verbose_level > 2 && next [i]) {
3447                         printf ("\t0x%x ->", sp->il_offset);
3448                         for (l = next [i]; l; l = l->next) {
3449                                 next_index = GPOINTER_TO_UINT (l->data);
3450                                 printf (" 0x%x", info->seq_points [next_index].il_offset);
3451                         }
3452                         printf ("\n");
3453                 }
3454                 for (l = next [i]; l; l = l->next) {
3455                         next_index = GPOINTER_TO_UINT (l->data);
3456                         sp->next [j ++] = next_index;
3457                 }
3458                 g_slist_free (next [i]);
3459         }
3460         g_free (next);
3461
3462         cfg->seq_point_info = info;
3463
3464         // FIXME: dynamic methods
3465         if (!cfg->compile_aot) {
3466                 mono_domain_lock (domain);
3467                 // FIXME: How can the lookup succeed ?
3468                 if (!g_hash_table_lookup (domain_jit_info (domain)->seq_points, cfg->method_to_register))
3469                         g_hash_table_insert (domain_jit_info (domain)->seq_points, cfg->method_to_register, info);
3470                 mono_domain_unlock (domain);
3471         }
3472
3473         g_ptr_array_free (cfg->seq_points, TRUE);
3474         cfg->seq_points = NULL;
3475 }
3476
3477 void
3478 mono_codegen (MonoCompile *cfg)
3479 {
3480         MonoBasicBlock *bb;
3481         int max_epilog_size;
3482         guint8 *code;
3483
3484 #if defined(__native_client_codegen__) && defined(__native_client__)
3485         void *code_dest;
3486
3487         /* This keeps patch targets from being transformed during
3488          * ordinary method compilation, for local branches and jumps.
3489          */
3490         nacl_allow_target_modification (FALSE);
3491 #endif
3492
3493         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3494                 cfg->spill_count = 0;
3495                 /* we reuse dfn here */
3496                 /* bb->dfn = bb_count++; */
3497
3498                 mono_arch_lowering_pass (cfg, bb);
3499
3500                 if (cfg->opt & MONO_OPT_PEEPHOLE)
3501                         mono_arch_peephole_pass_1 (cfg, bb);
3502
3503                 if (!cfg->globalra)
3504                         mono_local_regalloc (cfg, bb);
3505
3506                 if (cfg->opt & MONO_OPT_PEEPHOLE)
3507                         mono_arch_peephole_pass_2 (cfg, bb);
3508         }
3509
3510         if (cfg->prof_options & MONO_PROFILE_COVERAGE)
3511                 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
3512
3513         code = mono_arch_emit_prolog (cfg);
3514
3515         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
3516                 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
3517
3518         cfg->code_len = code - cfg->native_code;
3519         cfg->prolog_end = cfg->code_len;
3520
3521         mono_debug_open_method (cfg);
3522
3523         /* emit code all basic blocks */
3524         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3525                 bb->native_offset = cfg->code_len;
3526                 //if ((bb == cfg->bb_entry) || !(bb->region == -1 && !bb->dfn))
3527                         mono_arch_output_basic_block (cfg, bb);
3528                 bb->native_length = cfg->code_len - bb->native_offset;
3529
3530                 if (bb == cfg->bb_exit) {
3531                         cfg->epilog_begin = cfg->code_len;
3532
3533                         if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
3534                                 code = cfg->native_code + cfg->code_len;
3535                                 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
3536                                 cfg->code_len = code - cfg->native_code;
3537                                 g_assert (cfg->code_len < cfg->code_size);
3538                         }
3539
3540                         mono_arch_emit_epilog (cfg);
3541                 }
3542         }
3543
3544 #ifdef __native_client_codegen__
3545         mono_nacl_fix_patches (cfg->native_code, cfg->patch_info);
3546 #endif
3547         mono_arch_emit_exceptions (cfg);
3548
3549         max_epilog_size = 0;
3550
3551         code = cfg->native_code + cfg->code_len;
3552
3553         /* we always allocate code in cfg->domain->code_mp to increase locality */
3554         cfg->code_size = cfg->code_len + max_epilog_size;
3555         /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
3556
3557         if (cfg->method->dynamic) {
3558                 guint unwindlen = 0;
3559 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
3560                 unwindlen = mono_arch_unwindinfo_get_size (cfg->arch.unwindinfo);
3561 #endif
3562                 /* Allocate the code into a separate memory pool so it can be freed */
3563                 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
3564                 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
3565                 mono_domain_lock (cfg->domain);
3566                 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
3567                 mono_domain_unlock (cfg->domain);
3568
3569                 code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size + unwindlen);
3570         } else {
3571                 guint unwindlen = 0;
3572 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
3573                 unwindlen = mono_arch_unwindinfo_get_size (cfg->arch.unwindinfo);
3574 #endif
3575                 code = mono_domain_code_reserve (cfg->domain, cfg->code_size + unwindlen);
3576         }
3577 #if defined(__native_client_codegen__) && defined(__native_client__)
3578         nacl_allow_target_modification (TRUE);
3579 #endif
3580
3581         memcpy (code, cfg->native_code, cfg->code_len);
3582 #if defined(__default_codegen__)
3583         g_free (cfg->native_code);
3584 #elif defined(__native_client_codegen__)
3585         if (cfg->native_code_alloc) {
3586                 g_free (cfg->native_code_alloc);
3587                 cfg->native_code_alloc = 0;
3588         }
3589         else if (cfg->native_code) {
3590                 g_free (cfg->native_code);
3591         }
3592 #endif /* __native_client_codegen__ */
3593         cfg->native_code = code;
3594         code = cfg->native_code + cfg->code_len;
3595   
3596         /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
3597         mono_postprocess_patches (cfg);
3598
3599 #ifdef VALGRIND_JIT_REGISTER_MAP
3600 if (valgrind_register){
3601                 char* nm = mono_method_full_name (cfg->method, TRUE);
3602                 VALGRIND_JIT_REGISTER_MAP (nm, cfg->native_code, cfg->native_code + cfg->code_len);
3603                 g_free (nm);
3604         }
3605 #endif
3606  
3607         if (cfg->verbose_level > 0) {
3608                 char* nm = mono_method_full_name (cfg->method, TRUE);
3609                 g_print ("Method %s emitted at %p to %p (code length %d) [%s]\n", 
3610                                  nm, 
3611                                  cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
3612                 g_free (nm);
3613         }
3614
3615         {
3616                 gboolean is_generic = FALSE;
3617
3618                 if (cfg->method->is_inflated || mono_method_get_generic_container (cfg->method) ||
3619                                 cfg->method->klass->generic_container || cfg->method->klass->generic_class) {
3620                         is_generic = TRUE;
3621                 }
3622
3623                 if (cfg->generic_sharing_context)
3624                         g_assert (is_generic);
3625         }
3626
3627 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
3628         mono_arch_save_unwind_info (cfg);
3629 #endif
3630
3631 #if defined(__native_client_codegen__) && defined(__native_client__)
3632         if (!cfg->compile_aot) {
3633                 if (cfg->method->dynamic) {
3634                         code_dest = nacl_code_manager_get_code_dest(cfg->dynamic_info->code_mp, cfg->native_code);
3635                 } else {
3636                         code_dest = nacl_domain_get_code_dest(cfg->domain, cfg->native_code);
3637                 }
3638         }
3639 #endif
3640
3641 #if defined(__native_client_codegen__)
3642         mono_nacl_fix_patches (cfg->native_code, cfg->patch_info);
3643 #endif
3644
3645         mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
3646
3647         if (cfg->method->dynamic) {
3648                 mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
3649         } else {
3650                 mono_domain_code_commit (cfg->domain, cfg->native_code, cfg->code_size, cfg->code_len);
3651         }
3652 #if defined(__native_client_codegen__) && defined(__native_client__)
3653         cfg->native_code = code_dest;
3654 #endif
3655         mono_profiler_code_buffer_new (cfg->native_code, cfg->code_len, MONO_PROFILER_CODE_BUFFER_METHOD, cfg->method);
3656         
3657         mono_arch_flush_icache (cfg->native_code, cfg->code_len);
3658
3659         mono_debug_close_method (cfg);
3660
3661 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
3662         mono_arch_unwindinfo_install_unwind_info (&cfg->arch.unwindinfo, cfg->native_code, cfg->code_len);
3663 #endif
3664 }
3665
3666 static void
3667 compute_reachable (MonoBasicBlock *bb)
3668 {
3669         int i;
3670
3671         if (!(bb->flags & BB_VISITED)) {
3672                 bb->flags |= BB_VISITED;
3673                 for (i = 0; i < bb->out_count; ++i)
3674                         compute_reachable (bb->out_bb [i]);
3675         }
3676 }
3677
3678 static void
3679 mono_handle_out_of_line_bblock (MonoCompile *cfg)
3680 {
3681         MonoBasicBlock *bb;
3682         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3683                 if (bb->next_bb && bb->next_bb->out_of_line && bb->last_ins && !MONO_IS_BRANCH_OP (bb->last_ins)) {
3684                         MonoInst *ins;
3685                         MONO_INST_NEW (cfg, ins, OP_BR);
3686                         MONO_ADD_INS (bb, ins);
3687                         ins->inst_target_bb = bb->next_bb;
3688                 }
3689         }
3690 }
3691
3692 static MonoJitInfo*
3693 create_jit_info (MonoCompile *cfg, MonoMethod *method_to_compile)
3694 {
3695         GSList *tmp;
3696         MonoMethodHeader *header;
3697         MonoJitInfo *jinfo;
3698         int num_clauses;
3699         int generic_info_size;
3700         int holes_size = 0, num_holes = 0;
3701
3702         g_assert (method_to_compile == cfg->method);
3703         header = cfg->header;
3704
3705         if (cfg->generic_sharing_context)
3706                 generic_info_size = sizeof (MonoGenericJitInfo);
3707         else
3708                 generic_info_size = 0;
3709
3710         if (cfg->try_block_holes) {
3711                 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
3712                         TryBlockHole *hole = tmp->data;
3713                         MonoExceptionClause *ec = hole->clause;
3714                         int hole_end = hole->basic_block->native_offset + hole->basic_block->native_length;
3715                         MonoBasicBlock *clause_last_bb = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
3716                         g_assert (clause_last_bb);
3717
3718                         /* Holes at the end of a try region can be represented by simply reducing the size of the block itself.*/
3719                         if (clause_last_bb->native_offset != hole_end)
3720                                 ++num_holes;
3721                 }
3722                 if (num_holes)
3723                         holes_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
3724                 if (G_UNLIKELY (cfg->verbose_level >= 4))
3725                         printf ("Number of try block holes %d\n", num_holes);
3726         }
3727
3728         if (COMPILE_LLVM (cfg))
3729                 num_clauses = cfg->llvm_ex_info_len;
3730         else
3731                 num_clauses = header->num_clauses;
3732
3733         if (cfg->method->dynamic) {
3734                 jinfo = g_malloc0 (MONO_SIZEOF_JIT_INFO + (num_clauses * sizeof (MonoJitExceptionInfo)) +
3735                                 generic_info_size + holes_size);
3736         } else {
3737                 jinfo = mono_domain_alloc0 (cfg->domain, MONO_SIZEOF_JIT_INFO +
3738                                 (num_clauses * sizeof (MonoJitExceptionInfo)) +
3739                                 generic_info_size + holes_size);
3740         }
3741
3742         jinfo->method = cfg->method_to_register;
3743         jinfo->code_start = cfg->native_code;
3744         jinfo->code_size = cfg->code_len;
3745         jinfo->used_regs = cfg->used_int_regs;
3746         jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
3747         jinfo->cas_inited = FALSE; /* initialization delayed at the first stalk walk using this method */
3748         jinfo->num_clauses = num_clauses;
3749         if (COMPILE_LLVM (cfg))
3750                 jinfo->from_llvm = TRUE;
3751
3752         if (cfg->generic_sharing_context) {
3753                 MonoInst *inst;
3754                 MonoGenericJitInfo *gi;
3755
3756                 jinfo->has_generic_jit_info = 1;
3757
3758                 gi = mono_jit_info_get_generic_jit_info (jinfo);
3759                 g_assert (gi);
3760
3761                 gi->generic_sharing_context = cfg->generic_sharing_context;
3762
3763                 if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
3764                                 mini_method_get_context (method_to_compile)->method_inst ||
3765                                 method_to_compile->klass->valuetype) {
3766                         g_assert (cfg->rgctx_var);
3767                 }
3768
3769                 gi->has_this = 1;
3770
3771                 if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
3772                                 mini_method_get_context (method_to_compile)->method_inst ||
3773                                 method_to_compile->klass->valuetype) {
3774                         inst = cfg->rgctx_var;
3775                         if (!COMPILE_LLVM (cfg))
3776                                 g_assert (inst->opcode == OP_REGOFFSET);
3777                 } else {
3778                         inst = cfg->args [0];
3779                 }
3780
3781                 if (COMPILE_LLVM (cfg)) {
3782                         g_assert (cfg->llvm_this_reg != -1);
3783                         gi->this_in_reg = 0;
3784                         gi->this_reg = cfg->llvm_this_reg;
3785                         gi->this_offset = cfg->llvm_this_offset;
3786                 } else if (inst->opcode == OP_REGVAR) {
3787                         gi->this_in_reg = 1;
3788                         gi->this_reg = inst->dreg;
3789                 } else {
3790                         g_assert (inst->opcode == OP_REGOFFSET);
3791 #ifdef TARGET_X86
3792                         g_assert (inst->inst_basereg == X86_EBP);
3793 #elif defined(TARGET_AMD64)
3794                         g_assert (inst->inst_basereg == X86_EBP || inst->inst_basereg == X86_ESP);
3795 #endif
3796                         g_assert (inst->inst_offset >= G_MININT32 && inst->inst_offset <= G_MAXINT32);
3797
3798                         gi->this_in_reg = 0;
3799                         gi->this_reg = inst->inst_basereg;
3800                         gi->this_offset = inst->inst_offset;
3801                 }
3802         }
3803
3804         if (num_holes) {
3805                 MonoTryBlockHoleTableJitInfo *table;
3806                 int i;
3807
3808                 jinfo->has_try_block_holes = 1;
3809                 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3810                 table->num_holes = (guint16)num_holes;
3811                 i = 0;
3812                 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
3813                         guint32 start_bb_offset;
3814                         MonoTryBlockHoleJitInfo *hole;
3815                         TryBlockHole *hole_data = tmp->data;
3816                         MonoExceptionClause *ec = hole_data->clause;
3817                         int hole_end = hole_data->basic_block->native_offset + hole_data->basic_block->native_length;
3818                         MonoBasicBlock *clause_last_bb = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
3819                         g_assert (clause_last_bb);
3820
3821                         /* Holes at the end of a try region can be represented by simply reducing the size of the block itself.*/
3822                         if (clause_last_bb->native_offset == hole_end)
3823                                 continue;
3824
3825                         start_bb_offset = hole_data->start_offset - hole_data->basic_block->native_offset;
3826                         hole = &table->holes [i++];
3827                         hole->clause = hole_data->clause - &header->clauses [0];
3828                         hole->offset = (guint32)hole_data->start_offset;
3829                         hole->length = (guint16)(hole_data->basic_block->native_length - start_bb_offset);
3830
3831                         if (G_UNLIKELY (cfg->verbose_level >= 4))
3832                                 printf ("\tTry block hole at eh clause %d offset %x length %x\n", hole->clause, hole->offset, hole->length);
3833                 }
3834                 g_assert (i == num_holes);
3835         }
3836
3837         if (COMPILE_LLVM (cfg)) {
3838                 if (num_clauses)
3839                         memcpy (&jinfo->clauses [0], &cfg->llvm_ex_info [0], num_clauses * sizeof (MonoJitExceptionInfo));
3840         } else if (header->num_clauses) {
3841                 int i;
3842
3843                 for (i = 0; i < header->num_clauses; i++) {
3844                         MonoExceptionClause *ec = &header->clauses [i];
3845                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
3846                         MonoBasicBlock *tblock;
3847                         MonoInst *exvar;
3848
3849                         ei->flags = ec->flags;
3850
3851                         exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
3852                         ei->exvar_offset = exvar ? exvar->inst_offset : 0;
3853
3854                         if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
3855                                 tblock = cfg->cil_offset_to_bb [ec->data.filter_offset];
3856                                 g_assert (tblock);
3857                                 ei->data.filter = cfg->native_code + tblock->native_offset;
3858                         } else {
3859                                 ei->data.catch_class = ec->data.catch_class;
3860                         }
3861
3862                         tblock = cfg->cil_offset_to_bb [ec->try_offset];
3863                         g_assert (tblock);
3864                         g_assert (tblock->native_offset);
3865                         ei->try_start = cfg->native_code + tblock->native_offset;
3866                         if (tblock->extend_try_block) {
3867                                 /*
3868                                  * Extend the try block backwards to include parts of the previous call
3869                                  * instruction.
3870                                  * FIXME: This is arch specific.
3871                                  */
3872                                 ei->try_start = (guint8*)ei->try_start - 1;
3873                         }
3874                         tblock = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
3875                         g_assert (tblock);
3876                         if (!tblock->native_offset) {
3877                                 int j, end;
3878                                 for (j = ec->try_offset + ec->try_len, end = ec->try_offset; j >= end; --j) {
3879                                         MonoBasicBlock *bb = cfg->cil_offset_to_bb [j];
3880                                         if (bb && bb->native_offset) {
3881                                                 tblock = bb;
3882                                                 break;
3883                                         }
3884                                 }
3885                         }
3886                         ei->try_end = cfg->native_code + tblock->native_offset;
3887                         g_assert (tblock->native_offset);
3888                         tblock = cfg->cil_offset_to_bb [ec->handler_offset];
3889                         g_assert (tblock);
3890                         ei->handler_start = cfg->native_code + tblock->native_offset;
3891
3892                         for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
3893                                 TryBlockHole *hole = tmp->data;
3894                                 gpointer hole_end = cfg->native_code + (hole->basic_block->native_offset + hole->basic_block->native_length);
3895                                 if (hole->clause == ec && hole_end == ei->try_end) {
3896                                         if (G_UNLIKELY (cfg->verbose_level >= 4))
3897                                                 printf ("\tShortening try block %d from %x to %x\n", i, (int)((guint8*)ei->try_end - cfg->native_code), hole->start_offset);
3898
3899                                         ei->try_end = cfg->native_code + hole->start_offset;
3900                                         break;
3901                                 }
3902                         }
3903
3904                         if (ec->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
3905                                 int end_offset;
3906                                 if (ec->handler_offset + ec->handler_len < header->code_size) {
3907                                         tblock = cfg->cil_offset_to_bb [ec->handler_offset + ec->handler_len];
3908                                         g_assert (tblock);
3909                                         end_offset = tblock->native_offset;
3910                                 } else {
3911                                         end_offset = cfg->epilog_begin;
3912                                 }
3913                                 ei->data.handler_end = cfg->native_code + end_offset;
3914                         }
3915                 }
3916         }
3917
3918         if (G_UNLIKELY (cfg->verbose_level >= 4)) {
3919                 int i;
3920                 for (i = 0; i < jinfo->num_clauses; i++) {
3921                         MonoJitExceptionInfo *ei = &jinfo->clauses [i];
3922                         int start = (guint8*)ei->try_start - cfg->native_code;
3923                         int end = (guint8*)ei->try_end - cfg->native_code;
3924                         int handler = (guint8*)ei->handler_start - cfg->native_code;
3925
3926                         printf ("JitInfo EH clause %d flags %x try %x-%x handler %x\n", i, ei->flags, start, end, handler);
3927                 }
3928         }
3929
3930         /* 
3931          * Its possible to generate dwarf unwind info for xdebug etc, but not actually
3932          * using it during runtime, hence the define.
3933          */
3934 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3935         if (cfg->encoded_unwind_ops) {
3936                 jinfo->used_regs = mono_cache_unwind_info (cfg->encoded_unwind_ops, cfg->encoded_unwind_ops_len);
3937                 g_free (cfg->encoded_unwind_ops);
3938         } else if (cfg->unwind_ops) {
3939                 guint32 info_len;
3940                 guint8 *unwind_info = mono_unwind_ops_encode (cfg->unwind_ops, &info_len);
3941
3942                 jinfo->used_regs = mono_cache_unwind_info (unwind_info, info_len);
3943                 g_free (unwind_info);
3944         }
3945 #endif
3946
3947         return jinfo;
3948 }
3949 #endif
3950
3951 /*
3952  * mini_get_shared_method:
3953  *
3954  *   Return the method which is actually compiled/registered when doing generic sharing.
3955  */
3956 MonoMethod*
3957 mini_get_shared_method (MonoMethod *method)
3958 {
3959         MonoGenericContext shared_context;
3960         MonoMethod *declaring_method, *res;
3961         int i;
3962         gboolean partial = FALSE;
3963
3964         if (method->is_generic || method->klass->generic_container)
3965                 declaring_method = method;
3966         else
3967                 declaring_method = mono_method_get_declaring_generic_method (method);
3968
3969         if (declaring_method->is_generic)
3970                 shared_context = mono_method_get_generic_container (declaring_method)->context;
3971         else
3972                 shared_context = declaring_method->klass->generic_container->context;
3973
3974         /* Handle partial sharing */
3975         if (method != declaring_method && method->is_inflated && !mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE)) {
3976                 MonoGenericContext *context = mono_method_get_context (method);
3977                 MonoGenericInst *inst;
3978                 MonoType **type_argv;
3979
3980                 /* 
3981                  * Create the shared context by replacing the ref type arguments with
3982                  * type parameters, and keeping the rest.
3983                  */
3984                 partial = TRUE;
3985                 inst = context->class_inst;
3986                 if (inst) {
3987                         type_argv = g_new0 (MonoType*, inst->type_argc);
3988                         for (i = 0; i < inst->type_argc; ++i) {
3989                                 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
3990                                         type_argv [i] = shared_context.class_inst->type_argv [i];
3991                                 else
3992                                         type_argv [i] = inst->type_argv [i];
3993                         }
3994
3995                         shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3996                         g_free (type_argv);
3997                 }
3998
3999                 inst = context->method_inst;
4000                 if (inst) {
4001                         type_argv = g_new0 (MonoType*, inst->type_argc);
4002                         for (i = 0; i < inst->type_argc; ++i) {
4003                                 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
4004                                         type_argv [i] = shared_context.method_inst->type_argv [i];
4005                                 else
4006                                         type_argv [i] = inst->type_argv [i];
4007                         }
4008
4009                         shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4010                         g_free (type_argv);
4011                 }
4012         }
4013
4014     res = mono_class_inflate_generic_method (declaring_method, &shared_context);
4015         if (!partial) {
4016                 /* The result should be an inflated method whose parent is not inflated */
4017                 g_assert (!res->klass->is_inflated);
4018         }
4019         return res;
4020 }
4021
4022 #ifndef DISABLE_JIT
4023 /*
4024  * mini_method_compile:
4025  * @method: the method to compile
4026  * @opts: the optimization flags to use
4027  * @domain: the domain where the method will be compiled in
4028  * @run_cctors: whether we should run type ctors if possible
4029  * @compile_aot: whether this is an AOT compilation
4030  * @parts: debug flag
4031  *
4032  * Returns: a MonoCompile* pointer. Caller must check the exception_type
4033  * field in the returned struct to see if compilation succeded.
4034  */
4035 MonoCompile*
4036 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
4037 {
4038         MonoMethodHeader *header;
4039         MonoMethodSignature *sig;
4040         MonoError err;
4041         guint8 *ip;
4042         MonoCompile *cfg;
4043         int dfn, i, code_size_ratio;
4044         gboolean deadce_has_run = FALSE;
4045         gboolean try_generic_shared, try_llvm = FALSE;
4046         MonoMethod *method_to_compile, *method_to_register;
4047
4048         mono_jit_stats.methods_compiled++;
4049         if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
4050                 mono_profiler_method_jit (method);
4051         if (MONO_PROBE_METHOD_COMPILE_BEGIN_ENABLED ())
4052                 MONO_PROBE_METHOD_COMPILE_BEGIN (method);
4053
4054         if (compile_aot)
4055                 /* 
4056                  * We might get passed the original generic method definition or
4057                  * instances with type parameters.
4058                  * FIXME: Remove the method->klass->generic_class limitation.
4059                  */
4060                 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
4061                         (opts & MONO_OPT_GSHARED) && ((method->is_generic || method->klass->generic_container) || (!method->klass->generic_class && mono_method_is_generic_sharable_impl (method, TRUE)));
4062         else
4063                 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
4064                         (opts & MONO_OPT_GSHARED) && mono_method_is_generic_sharable_impl (method, FALSE);
4065
4066         if (opts & MONO_OPT_GSHARED) {
4067                 if (try_generic_shared)
4068                         mono_stats.generics_sharable_methods++;
4069                 else if (mono_method_is_generic_impl (method))
4070                         mono_stats.generics_unsharable_methods++;
4071         }
4072
4073 #ifdef ENABLE_LLVM
4074         try_llvm = mono_use_llvm;
4075 #endif
4076
4077  restart_compile:
4078         if (try_generic_shared) {
4079                 method_to_compile = mini_get_shared_method (method);
4080                 g_assert (method_to_compile);
4081         } else {
4082                 method_to_compile = method;
4083         }
4084
4085         cfg = g_new0 (MonoCompile, 1);
4086         cfg->method = method_to_compile;
4087         cfg->header = mono_method_get_header (cfg->method);
4088         cfg->mempool = mono_mempool_new ();
4089         cfg->opt = opts;
4090         cfg->prof_options = mono_profiler_get_events ();
4091         cfg->run_cctors = run_cctors;
4092         cfg->domain = domain;
4093         cfg->verbose_level = mini_verbose;
4094         cfg->compile_aot = compile_aot;
4095         cfg->skip_visibility = method->skip_visibility;
4096         cfg->orig_method = method;
4097         cfg->gen_seq_points = debug_options.gen_seq_points;
4098         cfg->explicit_null_checks = debug_options.explicit_null_checks;
4099         if (try_generic_shared)
4100                 cfg->generic_sharing_context = (MonoGenericSharingContext*)&cfg->generic_sharing_context;
4101         cfg->compile_llvm = try_llvm;
4102         cfg->token_info_hash = g_hash_table_new (NULL, NULL);
4103
4104         if (cfg->gen_seq_points)
4105                 cfg->seq_points = g_ptr_array_new ();
4106
4107         if (cfg->compile_aot && !try_generic_shared && (method->is_generic || method->klass->generic_container)) {
4108                 cfg->exception_type = MONO_EXCEPTION_GENERIC_SHARING_FAILED;
4109                 return cfg;
4110         }
4111
4112         if (cfg->generic_sharing_context) {
4113                 method_to_register = method_to_compile;
4114         } else {
4115                 g_assert (method == method_to_compile);
4116                 method_to_register = method;
4117         }
4118         cfg->method_to_register = method_to_register;
4119
4120         mono_error_init (&err);
4121         sig = mono_method_signature_checked (cfg->method, &err);        
4122         if (!sig) {
4123                 cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
4124                 cfg->exception_message = g_strdup (mono_error_get_message (&err));
4125                 mono_error_cleanup (&err);
4126                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4127                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
4128                 return cfg;
4129         }
4130
4131         header = cfg->header;
4132         if (!header) {
4133                 MonoLoaderError *error;
4134
4135                 if ((error = mono_loader_get_last_error ())) {
4136                         cfg->exception_type = error->exception_type;
4137                 } else {
4138                         cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
4139                         cfg->exception_message = g_strdup_printf ("Missing or incorrect header for method %s", cfg->method->name);
4140                 }
4141                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4142                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
4143                 return cfg;
4144         }
4145
4146 #ifdef ENABLE_LLVM
4147         {
4148                 static gboolean inited;
4149
4150                 if (!inited) {
4151                         inited = TRUE;
4152                 }
4153
4154                 /* 
4155                  * Check for methods which cannot be compiled by LLVM early, to avoid
4156                  * the extra compilation pass.
4157                  */
4158                 if (COMPILE_LLVM (cfg)) {
4159                         mono_llvm_check_method_supported (cfg);
4160                         if (cfg->disable_llvm) {
4161                                 if (cfg->verbose_level >= 1) {
4162                                         //nm = mono_method_full_name (cfg->method, TRUE);
4163                                         printf ("LLVM failed for '%s': %s\n", method->name, cfg->exception_message);
4164                                         //g_free (nm);
4165                                 }
4166                                 mono_destroy_compile (cfg);
4167                                 try_llvm = FALSE;
4168                                 goto restart_compile;
4169                         }
4170                 }
4171         }
4172 #endif
4173
4174         /* The debugger has no liveness information, so avoid sharing registers/stack slots */
4175         if (mono_debug_using_mono_debugger () || debug_options.mdb_optimizations) {
4176                 cfg->disable_reuse_registers = TRUE;
4177                 cfg->disable_reuse_stack_slots = TRUE;
4178                 /* 
4179                  * This decreases the change the debugger will read registers/stack slots which are
4180                  * not yet initialized.
4181                  */
4182                 cfg->disable_initlocals_opt = TRUE;
4183
4184                 cfg->extend_live_ranges = TRUE;
4185
4186                 /* Temporarily disable this when running in the debugger until we have support
4187                  * for this in the debugger. */
4188                 cfg->disable_omit_fp = TRUE;
4189
4190                 /* The debugger needs all locals to be on the stack or in a global register */
4191                 cfg->disable_vreg_to_lvreg = TRUE;
4192
4193                 /* Don't remove unused variables when running inside the debugger since the user
4194                  * may still want to view them. */
4195                 cfg->disable_deadce_vars = TRUE;
4196
4197                 // cfg->opt |= MONO_OPT_SHARED;
4198                 cfg->opt &= ~MONO_OPT_DEADCE;
4199                 cfg->opt &= ~MONO_OPT_INLINE;
4200                 cfg->opt &= ~MONO_OPT_COPYPROP;
4201                 cfg->opt &= ~MONO_OPT_CONSPROP;
4202                 cfg->opt &= ~MONO_OPT_GSHARED;
4203
4204                 /* This is needed for the soft debugger, which doesn't like code after the epilog */
4205                 cfg->disable_out_of_line_bblocks = TRUE;
4206         }
4207
4208         if (mono_using_xdebug) {
4209                 /* 
4210                  * Make each variable use its own register/stack slot and extend 
4211                  * their liveness to cover the whole method, making them displayable
4212                  * in gdb even after they are dead.
4213                  */
4214                 cfg->disable_reuse_registers = TRUE;
4215                 cfg->disable_reuse_stack_slots = TRUE;
4216                 cfg->extend_live_ranges = TRUE;
4217                 cfg->compute_precise_live_ranges = TRUE;
4218         }
4219
4220         mini_gc_init_cfg (cfg);
4221
4222         if (COMPILE_LLVM (cfg)) {
4223                 cfg->opt |= MONO_OPT_ABCREM;
4224         }
4225
4226         if (getenv ("MONO_VERBOSE_METHOD")) {
4227                 char *name = getenv ("MONO_VERBOSE_METHOD");
4228
4229                 if ((strchr (name, '.') > name) || strchr (name, ':')) {
4230                         MonoMethodDesc *desc;
4231                         
4232                         desc = mono_method_desc_new (name, TRUE);
4233                         if (mono_method_desc_full_match (desc, cfg->method)) {
4234                                 cfg->verbose_level = 4;
4235                         }
4236                         mono_method_desc_free (desc);
4237                 } else {
4238                         if (strcmp (cfg->method->name, getenv ("MONO_VERBOSE_METHOD")) == 0)
4239                                 cfg->verbose_level = 4;
4240                 }
4241         }
4242
4243         ip = (guint8 *)header->code;
4244
4245         cfg->intvars = mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * header->max_stack);
4246
4247         if (cfg->verbose_level > 0) {
4248                 char *method_name;
4249                 if (COMPILE_LLVM (cfg))
4250                         g_print ("converting llvm method %s\n", method_name = mono_method_full_name (method, TRUE));
4251                 else if (cfg->generic_sharing_context)
4252                         g_print ("converting shared method %s\n", method_name = mono_method_full_name (method_to_compile, TRUE));
4253                 else
4254                         g_print ("converting method %s\n", method_name = mono_method_full_name (method, TRUE));
4255                 g_free (method_name);
4256         }
4257
4258         if (cfg->opt & (MONO_OPT_ABCREM | MONO_OPT_SSAPRE))
4259                 cfg->opt |= MONO_OPT_SSA;
4260
4261         /* 
4262         if ((cfg->method->klass->image != mono_defaults.corlib) || (strstr (cfg->method->klass->name, "StackOverflowException") && strstr (cfg->method->name, ".ctor")) || (strstr (cfg->method->klass->name, "OutOfMemoryException") && strstr (cfg->method->name, ".ctor")))
4263                 cfg->globalra = TRUE;
4264         */
4265
4266         //cfg->globalra = TRUE;
4267
4268         //if (!strcmp (cfg->method->klass->name, "Tests") && !cfg->method->wrapper_type)
4269         //      cfg->globalra = TRUE;
4270
4271         {
4272                 static int count = 0;
4273                 count ++;
4274
4275                 /*
4276                 if (getenv ("COUNT2")) {
4277                         cfg->globalra = TRUE;
4278                         if (count == atoi (getenv ("COUNT2")))
4279                                 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
4280                         if (count > atoi (getenv ("COUNT2")))
4281                                 cfg->globalra = FALSE;
4282                 }
4283                 */
4284         }
4285
4286         if (header->clauses)
4287                 cfg->globalra = FALSE;
4288
4289         if (cfg->method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)
4290                 /* The code in the prolog clobbers caller saved registers */
4291                 cfg->globalra = FALSE;
4292
4293         // FIXME: Disable globalra in case of tracing/profiling
4294
4295         if (cfg->method->save_lmf)
4296                 /* The LMF saving code might clobber caller saved registers */
4297                 cfg->globalra = FALSE;
4298
4299         if (header->code_size > 5000)
4300                 // FIXME:
4301                 /* Too large bblocks could overflow the ins positions */
4302                 cfg->globalra = FALSE;
4303
4304         cfg->rs = mono_regstate_new ();
4305         if (cfg->globalra)
4306                 cfg->rs->next_vreg = MONO_MAX_IREGS + MONO_MAX_FREGS;
4307         cfg->next_vreg = cfg->rs->next_vreg;
4308
4309         /* FIXME: Fix SSA to handle branches inside bblocks */
4310         if (cfg->opt & MONO_OPT_SSA)
4311                 cfg->enable_extended_bblocks = FALSE;
4312
4313         /*
4314          * FIXME: This confuses liveness analysis because variables which are assigned after
4315          * a branch inside a bblock become part of the kill set, even though the assignment
4316          * might not get executed. This causes the optimize_initlocals pass to delete some
4317          * assignments which are needed.
4318          * Also, the mono_if_conversion pass needs to be modified to recognize the code
4319          * created by this.
4320          */
4321         //cfg->enable_extended_bblocks = TRUE;
4322
4323         /*We must verify the method before doing any IR generation as mono_compile_create_vars can assert.*/
4324         if (mono_compile_is_broken (cfg, cfg->method, TRUE)) {
4325                 if (mini_get_debug_options ()->break_on_unverified)
4326                         G_BREAKPOINT ();
4327                 return cfg;
4328         }
4329
4330         /*
4331          * create MonoInst* which represents arguments and local variables
4332          */
4333         mono_compile_create_vars (cfg);
4334
4335         /* SSAPRE is not supported on linear IR */
4336         cfg->opt &= ~MONO_OPT_SSAPRE;
4337
4338         i = mono_method_to_ir (cfg, method_to_compile, NULL, NULL, NULL, NULL, NULL, 0, FALSE);
4339
4340         if (i < 0) {
4341                 if (try_generic_shared && cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4342                         if (compile_aot) {
4343                                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4344                                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
4345                                 return cfg;
4346                         }
4347                         mono_destroy_compile (cfg);
4348                         try_generic_shared = FALSE;
4349                         goto restart_compile;
4350                 }
4351                 g_assert (cfg->exception_type != MONO_EXCEPTION_GENERIC_SHARING_FAILED);
4352
4353                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4354                         MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
4355                 /* cfg contains the details of the failure, so let the caller cleanup */
4356                 return cfg;
4357         }
4358
4359         mono_jit_stats.basic_blocks += cfg->num_bblocks;
4360         mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
4361
4362         if (COMPILE_LLVM (cfg)) {
4363                 MonoInst *ins;
4364
4365                 /* The IR has to be in SSA form for LLVM */
4366                 cfg->opt |= MONO_OPT_SSA;
4367
4368                 // FIXME:
4369                 if (cfg->ret) {
4370                         // Allow SSA on the result value
4371                         cfg->ret->flags &= ~MONO_INST_VOLATILE;
4372
4373                         // Add an explicit return instruction referencing the return value
4374                         MONO_INST_NEW (cfg, ins, OP_SETRET);
4375                         ins->sreg1 = cfg->ret->dreg;
4376
4377                         MONO_ADD_INS (cfg->bb_exit, ins);
4378                 }
4379
4380                 cfg->opt &= ~MONO_OPT_LINEARS;
4381
4382                 /* FIXME: */
4383                 cfg->opt &= ~MONO_OPT_BRANCH;
4384         }
4385
4386         /* todo: remove code when we have verified that the liveness for try/catch blocks
4387          * works perfectly 
4388          */
4389         /* 
4390          * Currently, this can't be commented out since exception blocks are not
4391          * processed during liveness analysis.
4392          * It is also needed, because otherwise the local optimization passes would
4393          * delete assignments in cases like this:
4394          * r1 <- 1
4395          * <something which throws>
4396          * r1 <- 2
4397          * This also allows SSA to be run on methods containing exception clauses, since
4398          * SSA will ignore variables marked VOLATILE.
4399          */
4400         mono_liveness_handle_exception_clauses (cfg);
4401
4402         mono_handle_out_of_line_bblock (cfg);
4403
4404         /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
4405
4406         if (!COMPILE_LLVM (cfg))
4407                 mono_decompose_long_opts (cfg);
4408
4409         /* Should be done before branch opts */
4410         if (cfg->opt & (MONO_OPT_CONSPROP | MONO_OPT_COPYPROP))
4411                 mono_local_cprop (cfg);
4412
4413         if (cfg->opt & MONO_OPT_BRANCH)
4414                 mono_optimize_branches (cfg);
4415
4416         /* This must be done _before_ global reg alloc and _after_ decompose */
4417         mono_handle_global_vregs (cfg);
4418         if (cfg->opt & MONO_OPT_DEADCE)
4419                 mono_local_deadce (cfg);
4420         /* Disable this for LLVM to make the IR easier to handle */
4421         if (!COMPILE_LLVM (cfg))
4422                 mono_if_conversion (cfg);
4423
4424         if ((cfg->opt & MONO_OPT_SSAPRE) || cfg->globalra)
4425                 mono_remove_critical_edges (cfg);
4426
4427         /* Depth-first ordering on basic blocks */
4428         cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
4429
4430         cfg->max_block_num = cfg->num_bblocks;
4431
4432         dfn = 0;
4433         df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
4434         if (cfg->num_bblocks != dfn + 1) {
4435                 MonoBasicBlock *bb;
4436
4437                 cfg->num_bblocks = dfn + 1;
4438
4439                 /* remove unreachable code, because the code in them may be 
4440                  * inconsistent  (access to dead variables for example) */
4441                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4442                         bb->flags &= ~BB_VISITED;
4443                 compute_reachable (cfg->bb_entry);
4444                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4445                         if (bb->flags & BB_EXCEPTION_HANDLER)
4446                                 compute_reachable (bb);
4447                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4448                         if (!(bb->flags & BB_VISITED)) {
4449                                 if (cfg->verbose_level > 1)
4450                                         g_print ("found unreachable code in BB%d\n", bb->block_num);
4451                                 bb->code = bb->last_ins = NULL;
4452                                 while (bb->out_count)
4453                                         mono_unlink_bblock (cfg, bb, bb->out_bb [0]);
4454                         }
4455                 }
4456                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4457                         bb->flags &= ~BB_VISITED;
4458         }
4459
4460         if (((cfg->num_varinfo > 2000) || (cfg->num_bblocks > 1000)) && !cfg->compile_aot) {
4461                 /* 
4462                  * we disable some optimizations if there are too many variables
4463                  * because JIT time may become too expensive. The actual number needs 
4464                  * to be tweaked and eventually the non-linear algorithms should be fixed.
4465                  */
4466                 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
4467                 cfg->disable_ssa = TRUE;
4468         }
4469
4470         if (cfg->opt & MONO_OPT_LOOP) {
4471                 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
4472                 mono_compute_natural_loops (cfg);
4473         }
4474
4475         /* after method_to_ir */
4476         if (parts == 1) {
4477                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4478                         MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
4479                 return cfg;
4480         }
4481
4482         /*
4483           if (header->num_clauses)
4484           cfg->disable_ssa = TRUE;
4485         */
4486
4487 //#define DEBUGSSA "logic_run"
4488 #define DEBUGSSA_CLASS "Tests"
4489 #ifdef DEBUGSSA
4490
4491         if (!cfg->disable_ssa) {
4492                 mono_local_cprop (cfg);
4493
4494 #ifndef DISABLE_SSA
4495                 mono_ssa_compute (cfg);
4496 #endif
4497         }
4498 #else 
4499         if (cfg->opt & MONO_OPT_SSA) {
4500                 if (!(cfg->comp_done & MONO_COMP_SSA) && !cfg->disable_ssa) {
4501 #ifndef DISABLE_SSA
4502                         mono_ssa_compute (cfg);
4503 #endif
4504
4505                         if (cfg->verbose_level >= 2) {
4506                                 print_dfn (cfg);
4507                         }
4508                 }
4509         }
4510 #endif
4511
4512         /* after SSA translation */
4513         if (parts == 2) {
4514                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4515                         MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
4516                 return cfg;
4517         }
4518
4519         if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
4520                 if (cfg->comp_done & MONO_COMP_SSA && !COMPILE_LLVM (cfg)) {
4521 #ifndef DISABLE_SSA
4522                         mono_ssa_cprop (cfg);
4523 #endif
4524                 }
4525         }
4526
4527 #ifndef DISABLE_SSA
4528         if (cfg->comp_done & MONO_COMP_SSA && !COMPILE_LLVM (cfg)) {
4529                 //mono_ssa_strength_reduction (cfg);
4530
4531                 if (cfg->opt & MONO_OPT_SSAPRE) {
4532                         mono_perform_ssapre (cfg);
4533                         //mono_local_cprop (cfg);
4534                 }
4535
4536                 if (cfg->opt & MONO_OPT_DEADCE) {
4537                         mono_ssa_deadce (cfg);
4538                         deadce_has_run = TRUE;
4539                 }
4540
4541                 if ((cfg->flags & (MONO_CFG_HAS_LDELEMA|MONO_CFG_HAS_CHECK_THIS)) && (cfg->opt & MONO_OPT_ABCREM))
4542                         mono_perform_abc_removal (cfg);
4543
4544                 mono_ssa_remove (cfg);
4545                 mono_local_cprop (cfg);
4546                 mono_handle_global_vregs (cfg);
4547                 if (cfg->opt & MONO_OPT_DEADCE)
4548                         mono_local_deadce (cfg);
4549
4550                 if (cfg->opt & MONO_OPT_BRANCH) {
4551                         MonoBasicBlock *bb;
4552
4553                         mono_optimize_branches (cfg);
4554
4555                         /* Have to recompute cfg->bblocks and bb->dfn */
4556                         if (cfg->globalra) {
4557                                 mono_remove_critical_edges (cfg);
4558
4559                                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4560                                         bb->dfn = 0;
4561
4562                                 /* Depth-first ordering on basic blocks */
4563                                 cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
4564
4565                                 dfn = 0;
4566                                 df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
4567                                 cfg->num_bblocks = dfn + 1;
4568                         }
4569                 }
4570         }
4571 #endif
4572
4573         if (cfg->comp_done & MONO_COMP_SSA && COMPILE_LLVM (cfg)) {
4574                 /* This removes MONO_INST_FAULT flags too so perform it unconditionally */
4575                 if (cfg->opt & MONO_OPT_ABCREM)
4576                         mono_perform_abc_removal (cfg);
4577         }
4578
4579         /* after SSA removal */
4580         if (parts == 3) {
4581                 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4582                         MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
4583                 return cfg;
4584         }
4585
4586 #ifdef MONO_ARCH_SOFT_FLOAT
4587         if (!COMPILE_LLVM (cfg))
4588                 mono_decompose_soft_float (cfg);
4589 #endif
4590         if (!COMPILE_LLVM (cfg))
4591                 mono_decompose_vtype_opts (cfg);
4592         if (cfg->flags & MONO_CFG_HAS_ARRAY_ACCESS)
4593                 mono_decompose_array_access_opts (cfg);
4594
4595         if (cfg->got_var) {
4596 #ifndef MONO_ARCH_GOT_REG
4597                 GList *regs;
4598 #endif
4599                 int got_reg;
4600
4601                 g_assert (cfg->got_var_allocated);
4602
4603                 /* 
4604                  * Allways allocate the GOT var to a register, because keeping it
4605                  * in memory will increase the number of live temporaries in some
4606                  * code created by inssel.brg, leading to the well known spills+
4607                  * branches problem. Testcase: mcs crash in 
4608                  * System.MonoCustomAttrs:GetCustomAttributes.
4609                  */
4610 #ifdef MONO_ARCH_GOT_REG
4611                 got_reg = MONO_ARCH_GOT_REG;
4612 #else
4613                 regs = mono_arch_get_global_int_regs (cfg);
4614                 g_assert (regs);
4615                 got_reg = GPOINTER_TO_INT (regs->data);
4616                 g_list_free (regs);
4617 #endif
4618                 cfg->got_var->opcode = OP_REGVAR;
4619                 cfg->got_var->dreg = got_reg;
4620                 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
4621         }
4622
4623         /*
4624          * Have to call this again to process variables added since the first call.
4625          */
4626         mono_liveness_handle_exception_clauses (cfg);
4627
4628         if (cfg->globalra) {
4629                 MonoBasicBlock *bb;
4630
4631                 /* Have to do this before regalloc since it can create vregs */
4632                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4633                         mono_arch_lowering_pass (cfg, bb);
4634
4635                 mono_global_regalloc (cfg);
4636         }
4637
4638         if ((cfg->opt & MONO_OPT_LINEARS) && !cfg->globalra) {
4639                 GList *vars, *regs, *l;
4640                 
4641                 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
4642                 cfg->comp_done &= ~MONO_COMP_LIVENESS;
4643                 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
4644                         mono_analyze_liveness (cfg);
4645
4646                 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
4647                         regs = mono_arch_get_global_int_regs (cfg);
4648                         /* Remove the reg reserved for holding the GOT address */
4649                         if (cfg->got_var) {
4650                                 for (l = regs; l; l = l->next) {
4651                                         if (GPOINTER_TO_UINT (l->data) == cfg->got_var->dreg) {
4652                                                 regs = g_list_delete_link (regs, l);
4653                                                 break;
4654                                         }
4655                                 }
4656                         }
4657                         mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
4658                 }
4659         }
4660
4661         //mono_print_code (cfg, "");
4662
4663     //print_dfn (cfg);
4664         
4665         /* variables are allocated after decompose, since decompose could create temps */
4666         if (!cfg->globalra && !COMPILE_LLVM (cfg)) {
4667                 mono_arch_allocate_vars (cfg);
4668                 if (cfg->exception_type)
4669                         return cfg;
4670         }
4671
4672         {
4673                 MonoBasicBlock *bb;
4674                 gboolean need_local_opts;
4675
4676                 if (!cfg->globalra && !COMPILE_LLVM (cfg)) {
4677                         mono_spill_global_vars (cfg, &need_local_opts);
4678
4679                         if (need_local_opts || cfg->compile_aot) {
4680                                 /* To optimize code created by spill_global_vars */
4681                                 mono_local_cprop (cfg);
4682                                 if (cfg->opt & MONO_OPT_DEADCE)
4683                                         mono_local_deadce (cfg);
4684                         }
4685                 }
4686
4687                 /* Add branches between non-consecutive bblocks */
4688                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4689                         if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
4690                                 bb->last_ins->inst_false_bb && bb->next_bb != bb->last_ins->inst_false_bb) {
4691                                 /* we are careful when inverting, since bugs like #59580
4692                                  * could show up when dealing with NaNs.
4693                                  */
4694                                 if (MONO_IS_COND_BRANCH_NOFP(bb->last_ins) && bb->next_bb == bb->last_ins->inst_true_bb) {
4695                                         MonoBasicBlock *tmp =  bb->last_ins->inst_true_bb;
4696                                         bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb;
4697                                         bb->last_ins->inst_false_bb = tmp;
4698
4699                                         bb->last_ins->opcode = mono_reverse_branch_op (bb->last_ins->opcode);
4700                                 } else {                        
4701                                         MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
4702                                         inst->opcode = OP_BR;
4703                                         inst->inst_target_bb = bb->last_ins->inst_false_bb;
4704                                         mono_bblock_add_inst (bb, inst);
4705                                 }
4706                         }
4707                 }
4708
4709                 if (cfg->verbose_level >= 4 && !cfg->globalra) {
4710                         for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4711                                 MonoInst *tree = bb->code;      
4712                                 g_print ("DUMP BLOCK %d:\n", bb->block_num);
4713                                 if (!tree)
4714                                         continue;
4715                                 for (; tree; tree = tree->next) {
4716                                         mono_print_ins_index (-1, tree);
4717                                 }
4718                         }
4719                 }
4720
4721                 /* FIXME: */
4722                 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4723                         bb->max_vreg = cfg->next_vreg;
4724                 }
4725         }
4726
4727         if (COMPILE_LLVM (cfg)) {
4728 #ifdef ENABLE_LLVM
4729                 char *nm;
4730
4731                 /* The IR has to be in SSA form for LLVM */
4732                 if (!(cfg->comp_done & MONO_COMP_SSA)) {
4733                         cfg->exception_message = g_strdup ("SSA disabled.");
4734                         cfg->disable_llvm = TRUE;
4735                 }
4736
4737                 if (cfg->flags & MONO_CFG_HAS_ARRAY_ACCESS)
4738                         mono_decompose_array_access_opts (cfg);
4739
4740                 if (!cfg->disable_llvm)
4741                         mono_llvm_emit_method (cfg);
4742                 if (cfg->disable_llvm) {
4743                         if (cfg->verbose_level >= 1) {
4744                                 //nm = mono_method_full_name (cfg->method, TRUE);
4745                                 printf ("LLVM failed for '%s': %s\n", method->name, cfg->exception_message);
4746                                 //g_free (nm);
4747                         }
4748                         mono_destroy_compile (cfg);
4749                         try_llvm = FALSE;
4750                         goto restart_compile;
4751                 }
4752
4753                 if (cfg->verbose_level > 0 && !cfg->compile_aot) {
4754                         nm = mono_method_full_name (cfg->method, TRUE);
4755                         g_print ("LLVM Method %s emitted at %p to %p (code length %d) [%s]\n", 
4756                                          nm, 
4757                                          cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
4758                         g_free (nm);
4759                 }
4760 #endif
4761         } else {
4762                 mono_codegen (cfg);
4763         }
4764
4765         if (COMPILE_LLVM (cfg))
4766                 InterlockedIncrement (&mono_jit_stats.methods_with_llvm);
4767         else
4768                 InterlockedIncrement (&mono_jit_stats.methods_without_llvm);
4769
4770         if (cfg->verbose_level >= 2) {
4771                 char *id =  mono_method_full_name (cfg->method, FALSE);
4772                 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
4773                 g_free (id);
4774         }
4775
4776         cfg->jit_info = create_jit_info (cfg, method_to_compile);
4777
4778 #ifdef MONO_ARCH_HAVE_LIVERANGE_OPS
4779         if (cfg->extend_live_ranges) {
4780                 /* Extend live ranges to cover the whole method */
4781                 for (i = 0; i < cfg->num_varinfo; ++i)
4782                         MONO_VARINFO (cfg, i)->live_range_end = cfg->code_len;
4783         }
4784 #endif
4785
4786         if (!cfg->compile_aot)
4787                 mono_save_xdebug_info (cfg);
4788
4789         mini_gc_create_gc_map (cfg);
4790  
4791         mono_save_seq_point_info (cfg);
4792
4793         if (!cfg->compile_aot) {
4794                 mono_domain_lock (cfg->domain);
4795                 mono_jit_info_table_add (cfg->domain, cfg->jit_info);
4796
4797                 if (cfg->method->dynamic)
4798                         mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = cfg->jit_info;
4799                 mono_domain_unlock (cfg->domain);
4800         }
4801
4802         /* collect statistics */
4803         mono_perfcounters->jit_methods++;
4804         mono_perfcounters->jit_bytes += header->code_size;
4805         mono_jit_stats.allocated_code_size += cfg->code_len;
4806         code_size_ratio = cfg->code_len;
4807         if (code_size_ratio > mono_jit_stats.biggest_method_size && mono_jit_stats.enabled) {
4808                 mono_jit_stats.biggest_method_size = code_size_ratio;
4809                 g_free (mono_jit_stats.biggest_method);
4810                 mono_jit_stats.biggest_method = g_strdup_printf ("%s::%s)", method->klass->name, method->name);
4811         }
4812         code_size_ratio = (code_size_ratio * 100) / header->code_size;
4813         if (code_size_ratio > mono_jit_stats.max_code_size_ratio && mono_jit_stats.enabled) {
4814                 mono_jit_stats.max_code_size_ratio = code_size_ratio;
4815                 g_free (mono_jit_stats.max_ratio_method);
4816                 mono_jit_stats.max_ratio_method = g_strdup_printf ("%s::%s)", method->klass->name, method->name);
4817         }
4818         mono_jit_stats.native_code_size += cfg->code_len;
4819
4820         if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4821                 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
4822
4823         return cfg;
4824 }
4825
4826 #else
4827
4828 MonoCompile*
4829 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
4830 {
4831         g_assert_not_reached ();
4832         return NULL;
4833 }
4834
4835 #endif /* DISABLE_JIT */
4836
4837 MonoJitInfo*
4838 mono_domain_lookup_shared_generic (MonoDomain *domain, MonoMethod *method)
4839 {
4840         static gboolean inited = FALSE;
4841         static int lookups = 0;
4842         static int failed_lookups = 0;
4843         MonoJitInfo *ji;
4844
4845         ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, mini_get_shared_method (method));
4846         if (ji && !ji->has_generic_jit_info)
4847                 ji = NULL;
4848
4849         if (!inited) {
4850                 mono_counters_register ("Shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &lookups);
4851                 mono_counters_register ("Failed shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &failed_lookups);
4852                 inited = TRUE;
4853         }
4854
4855         ++lookups;
4856         if (!ji)
4857                 ++failed_lookups;
4858
4859         return ji;
4860 }
4861
4862 /*
4863  * LOCKING: Assumes domain->jit_code_hash_lock is held.
4864  */
4865 static MonoJitInfo*
4866 lookup_method_inner (MonoDomain *domain, MonoMethod *method)
4867 {
4868         MonoJitInfo *ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, method);
4869
4870         if (ji)
4871                 return ji;
4872
4873         if (!mono_method_is_generic_sharable_impl (method, FALSE))
4874                 return NULL;
4875         return mono_domain_lookup_shared_generic (domain, method);
4876 }
4877
4878 static MonoJitInfo*
4879 lookup_method (MonoDomain *domain, MonoMethod *method)
4880 {
4881         MonoJitInfo *info;
4882
4883         mono_loader_lock (); /*FIXME lookup_method_inner acquired it*/
4884         mono_domain_jit_code_hash_lock (domain);
4885         info = lookup_method_inner (domain, method);
4886         mono_domain_jit_code_hash_unlock (domain);
4887         mono_loader_unlock ();
4888
4889         return info;
4890 }
4891
4892 #if ENABLE_JIT_MAP
4893 static FILE* perf_map_file = NULL;
4894
4895 void
4896 mono_enable_jit_map (void)
4897 {
4898         if (!perf_map_file) {
4899                 char name [64];
4900                 g_snprintf (name, sizeof (name), "/tmp/perf-%d.map", getpid ());
4901                 unlink (name);
4902                 perf_map_file = fopen (name, "w");
4903         }
4904 }
4905
4906 void
4907 mono_emit_jit_tramp (void *start, int size, const char *desc)
4908 {
4909         if (perf_map_file)
4910                 fprintf (perf_map_file, "%llx %x %s\n", (long long unsigned int)(gsize)start, size, desc);
4911 }
4912
4913 void
4914 mono_emit_jit_map (MonoJitInfo *jinfo)
4915 {
4916         if (perf_map_file) {
4917                 char *name = mono_method_full_name (jinfo->method, TRUE);
4918                 mono_emit_jit_tramp (jinfo->code_start, jinfo->code_size, name);
4919                 g_free (name);
4920         }
4921 }
4922
4923 gboolean
4924 mono_jit_map_is_enabled (void)
4925 {
4926         return perf_map_file != NULL;
4927 }
4928
4929 #endif
4930
4931 static gpointer
4932 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt, MonoException **jit_ex)
4933 {
4934         MonoCompile *cfg;
4935         gpointer code = NULL;
4936         MonoJitInfo *jinfo, *info;
4937         MonoVTable *vtable;
4938         MonoException *ex = NULL;
4939         guint32 prof_options;
4940         GTimer *jit_timer;
4941         MonoMethod *prof_method;
4942
4943 #ifdef MONO_USE_AOT_COMPILER
4944         if (opt & MONO_OPT_AOT) {
4945                 MonoDomain *domain = mono_domain_get ();
4946
4947                 mono_class_init (method->klass);
4948
4949                 if ((code = mono_aot_get_method (domain, method))) {
4950                         vtable = mono_class_vtable (domain, method->klass);
4951                         g_assert (vtable);
4952                         mono_runtime_class_init (vtable);
4953
4954                         return code;
4955                 }
4956         }
4957 #endif
4958
4959         if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
4960             (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4961                 MonoMethod *nm;
4962                 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
4963
4964                 if (!piinfo->addr) {
4965                         if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4966                                 piinfo->addr = mono_lookup_internal_call (method);
4967                         else if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
4968 #ifdef HOST_WIN32
4969                                 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);
4970 #else
4971                                 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);
4972 #endif
4973                         else
4974                                 mono_lookup_pinvoke_call (method, NULL, NULL);
4975                 }
4976                 nm = mono_marshal_get_native_wrapper (method, check_for_pending_exc, FALSE);
4977                 code = mono_get_addr_from_ftnptr (mono_compile_method (nm));
4978                 jinfo = mono_jit_info_table_find (target_domain, code);
4979                 if (!jinfo)
4980                         jinfo = mono_jit_info_table_find (mono_domain_get (), code);
4981                 if (jinfo)
4982                         mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
4983                 return code;
4984
4985                 //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE) 
4986                 //mono_debug_add_wrapper (method, nm);
4987         } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
4988                 const char *name = method->name;
4989                 char *full_name, *msg;
4990                 MonoMethod *nm;
4991
4992                 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
4993                         if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
4994                                 MonoJitICallInfo *mi = mono_find_jit_icall_by_name ("mono_delegate_ctor");
4995                                 g_assert (mi);
4996                                 /*
4997                                  * We need to make sure this wrapper
4998                                  * is compiled because it might end up
4999                                  * in an (M)RGCTX if generic sharing
5000                                  * is enabled, and would be called
5001                                  * indirectly.  If it were a
5002                                  * trampoline we'd try to patch that
5003                                  * indirect call, which is not
5004                                  * possible.
5005                                  */
5006                                 return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper_full (mi, TRUE));
5007                         } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
5008 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
5009                                 return mono_create_delegate_trampoline (method->klass);
5010 #else
5011                                 nm = mono_marshal_get_delegate_invoke (method, NULL);
5012                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
5013 #endif
5014                         } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
5015                                 nm = mono_marshal_get_delegate_begin_invoke (method);
5016                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
5017                         } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
5018                                 nm = mono_marshal_get_delegate_end_invoke (method);
5019                                 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
5020                         }
5021                 }
5022
5023                 full_name = mono_method_full_name (method, TRUE);
5024                 msg = g_strdup_printf ("Unrecognizable runtime implemented method '%s'", full_name);
5025                 *jit_ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", msg);
5026                 g_free (full_name);
5027                 g_free (msg);
5028                 return NULL;
5029         }
5030
5031         if (mono_aot_only) {
5032                 char *fullname = mono_method_full_name (method, TRUE);
5033                 char *msg = g_strdup_printf ("Attempting to JIT compile method '%s' while running with --aot-only.\n", fullname);
5034
5035                 *jit_ex = mono_get_exception_execution_engine (msg);
5036                 g_free (fullname);
5037                 g_free (msg);
5038                 
5039                 return NULL;
5040         }
5041
5042         jit_timer = g_timer_new ();
5043
5044         cfg = mini_method_compile (method, opt, target_domain, TRUE, FALSE, 0);
5045         prof_method = cfg->method;
5046
5047         g_timer_stop (jit_timer);
5048         mono_jit_stats.jit_time += g_timer_elapsed (jit_timer, NULL);
5049         g_timer_destroy (jit_timer);
5050
5051         switch (cfg->exception_type) {
5052         case MONO_EXCEPTION_NONE:
5053                 break;
5054         case MONO_EXCEPTION_TYPE_LOAD:
5055         case MONO_EXCEPTION_MISSING_FIELD:
5056         case MONO_EXCEPTION_MISSING_METHOD:
5057         case MONO_EXCEPTION_FILE_NOT_FOUND:
5058         case MONO_EXCEPTION_BAD_IMAGE: {
5059                 /* Throw a type load exception if needed */
5060                 MonoLoaderError *error = mono_loader_get_last_error ();
5061
5062                 if (error) {
5063                         ex = mono_loader_error_prepare_exception (error);
5064                 } else {
5065                         if (cfg->exception_ptr) {
5066                                 ex = mono_class_get_exception_for_failure (cfg->exception_ptr);
5067                         } else {
5068                                 if (cfg->exception_type == MONO_EXCEPTION_MISSING_FIELD)
5069                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingFieldException", cfg->exception_message);
5070                                 else if (cfg->exception_type == MONO_EXCEPTION_MISSING_METHOD)
5071                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingMethodException", cfg->exception_message);
5072                                 else if (cfg->exception_type == MONO_EXCEPTION_TYPE_LOAD)
5073                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "TypeLoadException", cfg->exception_message);
5074                                 else if (cfg->exception_type == MONO_EXCEPTION_FILE_NOT_FOUND)
5075                                         ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FileNotFoundException", cfg->exception_message);
5076                                 else if (cfg->exception_type == MONO_EXCEPTION_BAD_IMAGE)
5077                                         ex = mono_get_exception_bad_image_format (cfg->exception_message);
5078                                 else
5079                                         g_assert_not_reached ();
5080                         }
5081                 }
5082                 break;
5083         }
5084         case MONO_EXCEPTION_INVALID_PROGRAM:
5085                 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", cfg->exception_message);
5086                 break;
5087         case MONO_EXCEPTION_UNVERIFIABLE_IL:
5088                 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.Security", "VerificationException", cfg->exception_message);
5089                 break;
5090         case MONO_EXCEPTION_METHOD_ACCESS:
5091                 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MethodAccessException", cfg->exception_message);
5092                 break;
5093         case MONO_EXCEPTION_FIELD_ACCESS:
5094                 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FieldAccessException", cfg->exception_message);
5095                 break;
5096         /* this can only be set if the security manager is active */
5097         case MONO_EXCEPTION_SECURITY_LINKDEMAND: {
5098                 MonoSecurityManager* secman = mono_security_manager_get_methods ();
5099                 MonoObject *exc = NULL;
5100                 gpointer args [2];
5101
5102                 args [0] = &cfg->exception_data;
5103                 args [1] = &method;
5104                 mono_runtime_invoke (secman->linkdemandsecurityexception, NULL, args, &exc);
5105
5106                 ex = (MonoException*)exc;
5107                 break;
5108         }
5109         case MONO_EXCEPTION_OBJECT_SUPPLIED: {
5110                 MonoException *exp = cfg->exception_ptr;
5111                 MONO_GC_UNREGISTER_ROOT (cfg->exception_ptr);
5112
5113                 ex = exp;
5114                 break;
5115         }
5116         case MONO_EXCEPTION_OUT_OF_MEMORY:
5117                 ex = mono_domain_get ()->out_of_memory_ex;
5118                 break;
5119         default:
5120                 g_assert_not_reached ();
5121         }
5122
5123         if (ex) {
5124                 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
5125                         mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
5126
5127                 mono_destroy_compile (cfg);
5128                 *jit_ex = ex;
5129
5130                 return NULL;
5131         }
5132
5133         mono_loader_lock (); /*FIXME lookup_method_inner requires the loader lock*/
5134         mono_domain_lock (target_domain);
5135
5136         /* Check if some other thread already did the job. In this case, we can
5137        discard the code this thread generated. */
5138
5139         mono_domain_jit_code_hash_lock (target_domain);
5140
5141         info = lookup_method_inner (target_domain, method);
5142         if (info) {
5143                 /* We can't use a domain specific method in another domain */
5144                 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
5145                         code = info->code_start;
5146 //                      printf("Discarding code for method %s\n", method->name);
5147                 }
5148         }
5149         
5150         if (code == NULL) {
5151                 mono_internal_hash_table_insert (&target_domain->jit_code_hash, cfg->jit_info->method, cfg->jit_info);
5152                 mono_domain_jit_code_hash_unlock (target_domain);
5153                 code = cfg->native_code;
5154
5155                 if (cfg->generic_sharing_context && mono_method_is_generic_sharable_impl (method, FALSE))
5156                         mono_stats.generics_shared_methods++;
5157         } else {
5158                 mono_domain_jit_code_hash_unlock (target_domain);
5159         }
5160
5161         jinfo = cfg->jit_info;
5162
5163         prof_options = cfg->prof_options;
5164
5165         mono_destroy_compile (cfg);
5166
5167 #ifndef DISABLE_JIT
5168         if (domain_jit_info (target_domain)->jump_target_hash) {
5169                 MonoJumpInfo patch_info;
5170                 GSList *list, *tmp;
5171                 list = g_hash_table_lookup (domain_jit_info (target_domain)->jump_target_hash, method);
5172                 if (list) {
5173                         patch_info.next = NULL;
5174                         patch_info.ip.i = 0;
5175                         patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
5176                         patch_info.data.method = method;
5177                         g_hash_table_remove (domain_jit_info (target_domain)->jump_target_hash, method);
5178                 }
5179                 for (tmp = list; tmp; tmp = tmp->next)
5180                         mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info, TRUE);
5181                 g_slist_free (list);
5182         }
5183
5184         mono_emit_jit_map (jinfo);
5185 #endif
5186         mono_domain_unlock (target_domain);
5187         mono_loader_unlock ();
5188
5189         vtable = mono_class_vtable (target_domain, method->klass);
5190         if (!vtable) {
5191                 ex = mono_class_get_exception_for_failure (method->klass);
5192                 g_assert (ex);
5193                 *jit_ex = ex;
5194                 return NULL;
5195         }
5196
5197         if (prof_options & MONO_PROFILE_JIT_COMPILATION) {
5198                 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
5199                         if (mono_marshal_method_from_wrapper (method)) {
5200                                 /* Native func wrappers have no method */
5201                                 /* The profiler doesn't know about wrappers, so pass the original icall method */
5202                                 mono_profiler_method_end_jit (mono_marshal_method_from_wrapper (method), jinfo, MONO_PROFILE_OK);
5203                         }
5204                 }
5205                 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
5206                 if (prof_method != method) {
5207                         mono_profiler_method_end_jit (prof_method, jinfo, MONO_PROFILE_OK);
5208                 }
5209         }
5210
5211         ex = mono_runtime_class_init_full (vtable, FALSE);
5212         if (ex) {
5213                 *jit_ex = ex;
5214                 return NULL;
5215         }
5216         return code;
5217 }
5218
5219 static gpointer
5220 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt, MonoException **ex)
5221 {
5222         MonoDomain *target_domain, *domain = mono_domain_get ();
5223         MonoJitInfo *info;
5224         gpointer code, p;
5225         MonoJitICallInfo *callinfo = NULL;
5226
5227         /*
5228          * ICALL wrappers are handled specially, since there is only one copy of them
5229          * shared by all appdomains.
5230          */
5231         if ((method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (strstr (method->name, "__icall_wrapper_") == method->name)) {
5232                 const char *icall_name;
5233
5234                 icall_name = method->name + strlen ("__icall_wrapper_");
5235                 g_assert (icall_name);
5236                 callinfo = mono_find_jit_icall_by_name (icall_name);
5237                 g_assert (callinfo);
5238
5239                 /* Must be domain neutral since there is only one copy */
5240                 opt |= MONO_OPT_SHARED;
5241         }
5242
5243         if (opt & MONO_OPT_SHARED)
5244                 target_domain = mono_get_root_domain ();
5245         else 
5246                 target_domain = domain;
5247
5248         info = lookup_method (target_domain, method);
5249         if (info) {
5250                 /* We can't use a domain specific method in another domain */
5251                 if (! ((domain != target_domain) && !info->domain_neutral)) {
5252                         MonoVTable *vtable;
5253                         MonoException *tmpEx;
5254
5255                         mono_jit_stats.methods_lookups++;
5256                         vtable = mono_class_vtable (domain, method->klass);
5257                         g_assert (vtable);
5258                         tmpEx = mono_runtime_class_init_full (vtable, ex == NULL);
5259                         if (tmpEx) {
5260                                 *ex = tmpEx;
5261                                 return NULL;
5262                         }
5263                         return mono_create_ftnptr (target_domain, info->code_start);
5264                 }
5265         }
5266
5267         code = mono_jit_compile_method_inner (method, target_domain, opt, ex);
5268         if (!code)
5269                 return NULL;
5270
5271         p = mono_create_ftnptr (target_domain, code);
5272
5273         if (callinfo) {
5274                 mono_jit_lock ();
5275                 if (!callinfo->wrapper) {
5276                         callinfo->wrapper = p;
5277                         mono_register_jit_icall_wrapper (callinfo, p);
5278                         mono_debug_add_icall_wrapper (method, callinfo);
5279                 }
5280                 mono_jit_unlock ();
5281         }
5282
5283         return p;
5284 }
5285
5286 gpointer
5287 mono_jit_compile_method (MonoMethod *method)
5288 {
5289         MonoException *ex = NULL;
5290         gpointer code;
5291
5292         code = mono_jit_compile_method_with_opt (method, default_opt, &ex);
5293         if (!code) {
5294                 g_assert (ex);
5295                 mono_raise_exception (ex);
5296         }
5297
5298         return code;
5299 }
5300
5301 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
5302 static void
5303 invalidated_delegate_trampoline (char *desc)
5304 {
5305         g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
5306                  "See http://www.go-mono.com/delegate.html for an explanation and ways to fix this.",
5307                  desc);
5308 }
5309 #endif
5310
5311 /*
5312  * mono_jit_free_method:
5313  *
5314  *  Free all memory allocated by the JIT for METHOD.
5315  */
5316 static void
5317 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
5318 {
5319         MonoJitDynamicMethodInfo *ji;
5320         gboolean destroy = TRUE;
5321
5322         g_assert (method->dynamic);
5323
5324         mono_domain_lock (domain);
5325         ji = mono_dynamic_code_hash_lookup (domain, method);
5326         mono_domain_unlock (domain);
5327
5328         if (!ji)
5329                 return;
5330         mono_domain_lock (domain);
5331         g_hash_table_remove (domain_jit_info (domain)->dynamic_code_hash, method);
5332         mono_internal_hash_table_remove (&domain->jit_code_hash, method);
5333         g_hash_table_remove (domain_jit_info (domain)->jump_trampoline_hash, method);
5334         g_hash_table_remove (domain_jit_info (domain)->runtime_invoke_hash, method);
5335         mono_domain_unlock (domain);
5336
5337 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
5338         if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
5339                 /*
5340                  * Instead of freeing the code, change it to call an error routine
5341                  * so people can fix their code.
5342                  */
5343                 char *type = mono_type_full_name (&method->klass->byval_arg);
5344                 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
5345
5346                 g_free (type);
5347                 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
5348                 destroy = FALSE;
5349         }
5350 #endif
5351
5352         /* 
5353          * This needs to be done before freeing code_mp, since the code address is the
5354          * key in the table, so if we free the code_mp first, another thread can grab the
5355          * same code address and replace our entry in the table.
5356          */
5357         mono_jit_info_table_remove (domain, ji->ji);
5358
5359         if (destroy)
5360                 mono_code_manager_destroy (ji->code_mp);
5361         g_free (ji);
5362 }
5363
5364 gpointer
5365 mono_jit_find_compiled_method_with_jit_info (MonoDomain *domain, MonoMethod *method, MonoJitInfo **ji)
5366 {
5367         MonoDomain *target_domain;
5368         MonoJitInfo *info;
5369
5370         if (default_opt & MONO_OPT_SHARED)
5371                 target_domain = mono_get_root_domain ();
5372         else 
5373                 target_domain = domain;
5374
5375         info = lookup_method (target_domain, method);
5376         if (info) {
5377                 /* We can't use a domain specific method in another domain */
5378                 if (! ((domain != target_domain) && !info->domain_neutral)) {
5379                         mono_jit_stats.methods_lookups++;
5380                         if (ji)
5381                                 *ji = info;
5382                         return info->code_start;
5383                 }
5384         }
5385
5386         if (ji)
5387                 *ji = NULL;
5388         return NULL;
5389 }
5390
5391 gpointer
5392 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
5393 {
5394         return mono_jit_find_compiled_method_with_jit_info (domain, method, NULL);
5395 }
5396
5397 typedef struct {
5398         MonoMethod *method;
5399         gpointer compiled_method;
5400         gpointer runtime_invoke;
5401         MonoVTable *vtable;
5402         MonoDynCallInfo *dyn_call_info;
5403         MonoClass *ret_box_class;
5404 } RuntimeInvokeInfo;
5405
5406 /**
5407  * mono_jit_runtime_invoke:
5408  * @method: the method to invoke
5409  * @obj: this pointer
5410  * @params: array of parameter values.
5411  * @exc: used to catch exceptions objects
5412  */
5413 static MonoObject*
5414 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
5415 {
5416         MonoMethod *invoke;
5417         MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
5418         MonoDomain *domain = mono_domain_get ();
5419         MonoJitDomainInfo *domain_info;
5420         RuntimeInvokeInfo *info, *info2;
5421         
5422         if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
5423                 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
5424                 return NULL;
5425         }
5426
5427         domain_info = domain_jit_info (domain);
5428
5429         mono_domain_lock (domain);
5430         info = g_hash_table_lookup (domain_info->runtime_invoke_hash, method);
5431         mono_domain_unlock (domain);            
5432
5433         if (!info) {
5434                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
5435                         /* 
5436                          * This might be redundant since mono_class_vtable () already does this,
5437                          * but keep it just in case for moonlight.
5438                          */
5439                         mono_class_setup_vtable (method->klass);
5440                         if (method->klass->exception_type != MONO_EXCEPTION_NONE) {
5441                                 if (exc)
5442                                         *exc = (MonoObject*)mono_class_get_exception_for_failure (method->klass);
5443                                 else
5444                                         mono_raise_exception (mono_class_get_exception_for_failure (method->klass));
5445                                 return NULL;
5446                         }
5447                 }
5448
5449                 info = g_new0 (RuntimeInvokeInfo, 1);
5450
5451                 invoke = mono_marshal_get_runtime_invoke (method, FALSE);
5452                 info->vtable = mono_class_vtable_full (domain, method->klass, TRUE);
5453                 g_assert (info->vtable);
5454
5455                 if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
5456                         (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
5457                         /* 
5458                          * Array Get/Set/Address methods. The JIT implements them using inline code 
5459                          * inside the runtime invoke wrappers, so no need to compile them.
5460                          */
5461                         info->compiled_method = NULL;
5462                 } else {
5463                         MonoException *jit_ex = NULL;
5464
5465                         info->compiled_method = mono_jit_compile_method_with_opt (method, default_opt, &jit_ex);
5466                         if (!info->compiled_method) {
5467                                 g_free (info);
5468                                 g_assert (jit_ex);
5469                                 if (exc) {
5470                                         *exc = (MonoObject*)jit_ex;
5471                                         return NULL;
5472                                 } else {
5473                                         mono_raise_exception (jit_ex);
5474                                 }
5475                         }
5476
5477                         if (mono_method_needs_static_rgctx_invoke (method, FALSE))
5478                                 info->compiled_method = mono_create_static_rgctx_trampoline (method, info->compiled_method);
5479                 }
5480
5481                 /*
5482                  * We want to avoid AOTing 1000s of runtime-invoke wrappers when running
5483                  * in full-aot mode, so we use a slower, but more generic wrapper if
5484                  * possible, built on top of the OP_DYN_CALL opcode provided by the JIT.
5485                  */
5486 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
5487                 if (mono_aot_only || debug_options.dyn_runtime_invoke) {
5488                         MonoMethodSignature *sig = mono_method_signature (method);
5489                         gboolean supported = TRUE;
5490                         int i;
5491
5492                         if (method->string_ctor)
5493                                 sig = mono_marshal_get_string_ctor_signature (method);
5494
5495                         for (i = 0; i < sig->param_count; ++i) {
5496                                 MonoType *t = sig->params [i];
5497
5498                                 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t)))
5499                                         supported = FALSE;
5500                         }
5501
5502                         if (method->klass->contextbound || !info->compiled_method)
5503                                 supported = FALSE;
5504
5505                         if (supported)
5506                                 info->dyn_call_info = mono_arch_dyn_call_prepare (sig);
5507
5508                         if (info->dyn_call_info) {
5509                                 switch (sig->ret->type) {
5510                                 case MONO_TYPE_VOID:
5511                                         break;
5512                                 case MONO_TYPE_I1:
5513                                 case MONO_TYPE_U1:
5514                                 case MONO_TYPE_I2:
5515                                 case MONO_TYPE_U2:
5516                                 case MONO_TYPE_I4:
5517                                 case MONO_TYPE_U4:
5518                                 case MONO_TYPE_I:
5519                                 case MONO_TYPE_U:
5520                                 case MONO_TYPE_I8:
5521                                 case MONO_TYPE_U8:
5522                                 case MONO_TYPE_BOOLEAN:
5523                                 case MONO_TYPE_CHAR:
5524                                 case MONO_TYPE_R4:
5525                                 case MONO_TYPE_R8:
5526                                         info->ret_box_class = mono_class_from_mono_type (sig->ret);
5527                                         break;
5528                                 case MONO_TYPE_PTR:
5529                                         info->ret_box_class = mono_defaults.int_class;
5530                                         break;
5531                                 case MONO_TYPE_STRING:
5532                                 case MONO_TYPE_CLASS:  
5533                                 case MONO_TYPE_ARRAY:
5534                                 case MONO_TYPE_SZARRAY:
5535                                 case MONO_TYPE_OBJECT:
5536                                         break;
5537                                 case MONO_TYPE_GENERICINST:
5538                                         if (!MONO_TYPE_IS_REFERENCE (sig->ret))
5539                                                 info->ret_box_class = mono_class_from_mono_type (sig->ret);
5540                                         break;
5541                                 case MONO_TYPE_VALUETYPE:
5542                                         info->ret_box_class = mono_class_from_mono_type (sig->ret);
5543                                         break;
5544                                 default:
5545                                         g_assert_not_reached ();
5546                                         break;
5547                                 }
5548                         }
5549                 }
5550 #endif
5551
5552                 if (!info->dyn_call_info)
5553                         info->runtime_invoke = mono_jit_compile_method (invoke);
5554
5555                 mono_domain_lock (domain);
5556                 info2 = g_hash_table_lookup (domain_info->runtime_invoke_hash, method);
5557                 if (info2) {
5558                         g_free (info);
5559                         info = info2;
5560                 } else {
5561                         g_hash_table_insert (domain_info->runtime_invoke_hash, method, info);
5562                 }
5563                 mono_domain_unlock (domain);
5564         }
5565
5566         runtime_invoke = info->runtime_invoke;
5567
5568         /*
5569          * We need this here because mono_marshal_get_runtime_invoke can place 
5570          * the helper method in System.Object and not the target class.
5571          */
5572         if (exc) {
5573                 *exc = (MonoObject*)mono_runtime_class_init_full (info->vtable, FALSE);
5574                 if (*exc)
5575                         return NULL;
5576         } else {
5577                 mono_runtime_class_init (info->vtable);
5578         }
5579
5580         /* The wrappers expect this to be initialized to NULL */
5581         if (exc)
5582                 *exc = NULL;
5583
5584 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
5585         if (info->dyn_call_info) {
5586                 MonoMethodSignature *sig = mono_method_signature (method);
5587                 gpointer *args;
5588                 static RuntimeInvokeDynamicFunction dyn_runtime_invoke;
5589                 int i, pindex;
5590                 guint8 buf [128];
5591                 guint8 retval [128];
5592
5593                 if (!dyn_runtime_invoke) {
5594                         invoke = mono_marshal_get_runtime_invoke_dynamic ();
5595                         dyn_runtime_invoke = mono_jit_compile_method (invoke);
5596                 }
5597
5598                 /* Convert the arguments to the format expected by start_dyn_call () */
5599                 args = g_alloca ((sig->param_count + sig->hasthis) * sizeof (gpointer));
5600                 pindex = 0;
5601                 if (sig->hasthis)
5602                         args [pindex ++] = &obj;
5603                 for (i = 0; i < sig->param_count; ++i) {
5604                         MonoType *t = sig->params [i];
5605
5606                         if (t->byref) {
5607                                 args [pindex ++] = &params [i];
5608                         } else if (MONO_TYPE_IS_REFERENCE (t) || t->type == MONO_TYPE_PTR) {
5609                                 args [pindex ++] = &params [i];
5610                         } else {
5611                                 args [pindex ++] = params [i];
5612                         }
5613                 }
5614
5615                 //printf ("M: %s\n", mono_method_full_name (method, TRUE));
5616
5617                 mono_arch_start_dyn_call (info->dyn_call_info, (gpointer**)args, retval, buf, sizeof (buf));
5618
5619                 dyn_runtime_invoke (buf, exc, info->compiled_method);
5620
5621                 mono_arch_finish_dyn_call (info->dyn_call_info, buf);
5622
5623                 if (info->ret_box_class)
5624                         return mono_value_box (domain, info->ret_box_class, retval);
5625                 else
5626                         return *(MonoObject**)retval;
5627         }
5628 #endif
5629
5630         return runtime_invoke (obj, params, exc, info->compiled_method);
5631 }
5632
5633 void
5634 SIG_HANDLER_SIGNATURE (mono_sigfpe_signal_handler)
5635 {
5636         MonoException *exc = NULL;
5637         MonoJitInfo *ji;
5638 #if !(defined(MONO_ARCH_USE_SIGACTION) || defined(HOST_WIN32))
5639         void *info = NULL;
5640 #endif
5641         GET_CONTEXT;
5642
5643         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (ctx));
5644
5645 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
5646         if (mono_arch_is_int_overflow (ctx, info))
5647                 /*
5648                  * The spec says this throws ArithmeticException, but MS throws the derived
5649                  * OverflowException.
5650                  */
5651                 exc = mono_get_exception_overflow ();
5652         else
5653                 exc = mono_get_exception_divide_by_zero ();
5654 #else
5655         exc = mono_get_exception_divide_by_zero ();
5656 #endif
5657
5658         if (!ji) {
5659                 if (mono_chain_signal (SIG_HANDLER_PARAMS))
5660                         return;
5661
5662                 mono_handle_native_sigsegv (SIGSEGV, ctx);
5663         }
5664         
5665         mono_arch_handle_exception (ctx, exc, FALSE);
5666 }
5667
5668 void
5669 SIG_HANDLER_SIGNATURE (mono_sigill_signal_handler)
5670 {
5671         MonoException *exc;
5672         GET_CONTEXT;
5673
5674         exc = mono_get_exception_execution_engine ("SIGILL");
5675         
5676         mono_arch_handle_exception (ctx, exc, FALSE);
5677 }
5678
5679 #if defined(MONO_ARCH_USE_SIGACTION) || defined(HOST_WIN32)
5680 #define HAVE_SIG_INFO
5681 #endif
5682
5683 void
5684 SIG_HANDLER_SIGNATURE (mono_sigsegv_signal_handler)
5685 {
5686         MonoJitInfo *ji;
5687         MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
5688         gpointer fault_addr = NULL;
5689
5690         GET_CONTEXT;
5691
5692 #if defined(MONO_ARCH_SOFT_DEBUG_SUPPORTED) && defined(HAVE_SIG_INFO)
5693         if (mono_arch_is_single_step_event (info, ctx)) {
5694                 mono_debugger_agent_single_step_event (ctx);
5695                 return;
5696         } else if (mono_arch_is_breakpoint_event (info, ctx)) {
5697                 mono_debugger_agent_breakpoint_hit (ctx);
5698                 return;
5699         }
5700 #endif
5701
5702 #if !defined(HOST_WIN32) && defined(HAVE_SIG_INFO)
5703         fault_addr = info->si_addr;
5704         if (mono_aot_is_pagefault (info->si_addr)) {
5705                 mono_aot_handle_pagefault (info->si_addr);
5706                 return;
5707         }
5708 #endif
5709
5710         /* The thread might no be registered with the runtime */
5711         if (!mono_domain_get () || !jit_tls) {
5712                 if (mono_chain_signal (SIG_HANDLER_PARAMS))
5713                         return;
5714                 mono_handle_native_sigsegv (SIGSEGV, ctx);
5715         }
5716
5717         ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (ctx));
5718
5719 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
5720         if (mono_handle_soft_stack_ovf (jit_tls, ji, ctx, (guint8*)info->si_addr))
5721                 return;
5722
5723 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
5724         /* info->si_addr seems to be NULL on some kernels when handling stack overflows */
5725         fault_addr = info->si_addr;
5726         if (fault_addr == NULL) {
5727                 MonoContext mctx;
5728
5729                 mono_arch_sigctx_to_monoctx (ctx, &mctx);
5730
5731                 fault_addr = MONO_CONTEXT_GET_SP (&mctx);
5732         }
5733 #endif
5734
5735         /* The hard-guard page has been hit: there is not much we can do anymore
5736          * Print a hopefully clear message and abort.
5737          */
5738         if (jit_tls->stack_size && 
5739                 ABS ((guint8*)fault_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 8192 * sizeof (gpointer)) {
5740                 const char *method;
5741                 /* we don't do much now, but we can warn the user with a useful message */
5742                 fprintf (stderr, "Stack overflow: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
5743                 if (ji && ji->method)
5744                         method = mono_method_full_name (ji->method, TRUE);
5745                 else
5746                         method = "Unmanaged";
5747                 fprintf (stderr, "At %s\n", method);
5748                 _exit (1);
5749         } else {
5750                 /* The original handler might not like that it is executed on an altstack... */
5751                 if (!ji && mono_chain_signal (SIG_HANDLER_PARAMS))
5752                         return;
5753
5754                 mono_arch_handle_altstack_exception (ctx, info->si_addr, FALSE);
5755         }
5756 #else
5757
5758         if (!ji) {
5759                 if (mono_chain_signal (SIG_HANDLER_PARAMS))
5760                         return;
5761
5762                 mono_handle_native_sigsegv (SIGSEGV, ctx);
5763         }
5764                         
5765         mono_arch_handle_exception (ctx, NULL, FALSE);
5766 #endif
5767 }
5768
5769 void
5770 SIG_HANDLER_SIGNATURE (mono_sigint_signal_handler)
5771 {
5772         MonoException *exc;
5773         GET_CONTEXT;
5774
5775         exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
5776         
5777         mono_arch_handle_exception (ctx, exc, FALSE);
5778 }
5779
5780 /* mono_jit_create_remoting_trampoline:
5781  * @method: pointer to the method info
5782  *
5783  * Creates a trampoline which calls the remoting functions. This
5784  * is used in the vtable of transparent proxies.
5785  * 
5786  * Returns: a pointer to the newly created code 
5787  */
5788 static gpointer
5789 mono_jit_create_remoting_trampoline (MonoDomain *domain, MonoMethod *method, MonoRemotingTarget target)
5790 {
5791         MonoMethod *nm;
5792         guint8 *addr = NULL;
5793
5794         if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && mono_method_signature (method)->generic_param_count) {
5795                 return mono_create_specific_trampoline (method, MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING,
5796                         domain, NULL);
5797         }
5798
5799         if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) || 
5800             (mono_method_signature (method)->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
5801                 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
5802                 addr = mono_compile_method (nm);
5803         } else {
5804                 addr = mono_compile_method (method);
5805         }
5806         return mono_get_addr_from_ftnptr (addr);
5807 }
5808
5809 static gpointer *vtable_trampolines;
5810 static int vtable_trampolines_size;
5811
5812 gpointer
5813 mini_get_vtable_trampoline (int slot_index)
5814 {
5815         int index = slot_index + MONO_IMT_SIZE;
5816
5817         g_assert (slot_index >= - MONO_IMT_SIZE);
5818         if (!vtable_trampolines || slot_index + MONO_IMT_SIZE >= vtable_trampolines_size) {
5819                 mono_jit_lock ();
5820                 if (!vtable_trampolines || index >= vtable_trampolines_size) {
5821                         int new_size;
5822                         gpointer new_table;
5823
5824                         new_size = vtable_trampolines_size ? vtable_trampolines_size * 2 : 128;
5825                         while (new_size <= index)
5826                                 new_size *= 2;
5827                         new_table = g_new0 (gpointer, new_size);
5828
5829                         if (vtable_trampolines)
5830                                 memcpy (new_table, vtable_trampolines, vtable_trampolines_size * sizeof (gpointer));
5831                         g_free (vtable_trampolines);
5832                         mono_memory_barrier ();
5833                         vtable_trampolines = new_table;
5834                         vtable_trampolines_size = new_size;
5835                 }
5836                 mono_jit_unlock ();
5837         }
5838
5839         if (!vtable_trampolines [index])
5840                 vtable_trampolines [index] = mono_create_specific_trampoline (GUINT_TO_POINTER (slot_index), MONO_TRAMPOLINE_VCALL, mono_get_root_domain (), NULL);
5841         return vtable_trampolines [index];
5842 }
5843
5844 static gpointer
5845 mini_get_imt_trampoline (int slot_index)
5846 {
5847         return mini_get_vtable_trampoline (slot_index - MONO_IMT_SIZE);
5848 }
5849
5850 static void
5851 mini_parse_debug_options (void)
5852 {
5853         char *options = getenv ("MONO_DEBUG");
5854         gchar **args, **ptr;
5855         
5856         if (!options)
5857                 return;
5858
5859         args = g_strsplit (options, ",", -1);
5860
5861         for (ptr = args; ptr && *ptr; ptr++) {
5862                 const char *arg = *ptr;
5863
5864                 if (!strcmp (arg, "handle-sigint"))
5865                         debug_options.handle_sigint = TRUE;
5866                 else if (!strcmp (arg, "keep-delegates"))
5867                         debug_options.keep_delegates = TRUE;
5868                 else if (!strcmp (arg, "reverse-pinvoke-exceptions"))
5869                         debug_options.reverse_pinvoke_exceptions = TRUE;
5870                 else if (!strcmp (arg, "collect-pagefault-stats"))
5871                         debug_options.collect_pagefault_stats = TRUE;
5872                 else if (!strcmp (arg, "break-on-unverified"))
5873                         debug_options.break_on_unverified = TRUE;
5874                 else if (!strcmp (arg, "no-gdb-backtrace"))
5875                         debug_options.no_gdb_backtrace = TRUE;
5876                 else if (!strcmp (arg, "suspend-on-sigsegv"))
5877                         debug_options.suspend_on_sigsegv = TRUE;
5878                 else if (!strcmp (arg, "dont-free-domains"))
5879                         mono_dont_free_domains = TRUE;
5880                 else if (!strcmp (arg, "dyn-runtime-invoke"))
5881                         debug_options.dyn_runtime_invoke = TRUE;
5882                 else if (!strcmp (arg, "gdb"))
5883                         debug_options.gdb = TRUE;
5884                 else if (!strcmp (arg, "explicit-null-checks"))
5885                         debug_options.explicit_null_checks = TRUE;
5886                 else if (!strcmp (arg, "gen-seq-points"))
5887                         debug_options.gen_seq_points = TRUE;
5888                 else if (!strcmp (arg, "init-stacks"))
5889                         debug_options.init_stacks = TRUE;
5890                 else if (!strcmp (arg, "casts"))
5891                         debug_options.better_cast_details = TRUE;
5892                 else {
5893                         fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
5894                         fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'reverse-pinvoke-exceptions', 'collect-pagefault-stats', 'break-on-unverified', 'no-gdb-backtrace', 'dont-free-domains', 'suspend-on-sigsegv', 'dyn-runtime-invoke', 'gdb', 'explicit-null-checks', 'init-stacks'\n");
5895                         exit (1);
5896                 }
5897         }
5898
5899         g_strfreev (args);
5900 }
5901
5902 MonoDebugOptions *
5903 mini_get_debug_options (void)
5904 {
5905         return &debug_options;
5906 }
5907
5908 static gpointer
5909 mini_create_ftnptr (MonoDomain *domain, gpointer addr)
5910 {
5911 #ifdef __ia64__
5912         gpointer *desc;
5913
5914         desc = mono_domain_code_reserve (domain, 2 * sizeof (gpointer));
5915
5916         desc [0] = addr;
5917         desc [1] = NULL;
5918
5919         return desc;
5920 #elif defined(__ppc64__) || defined(__powerpc64__)
5921         gpointer *desc;
5922
5923         desc = mono_domain_alloc0 (domain, 3 * sizeof (gpointer));
5924
5925         desc [0] = addr;
5926         desc [1] = NULL;
5927         desc [2] = NULL;
5928
5929         return desc;
5930 #else
5931         return addr;
5932 #endif
5933 }
5934
5935 static gpointer
5936 mini_get_addr_from_ftnptr (gpointer descr)
5937 {
5938 #if defined(__ia64__) || defined(__ppc64__) || defined(__powerpc64__)
5939         return *(gpointer*)descr;
5940 #else
5941         return descr;
5942 #endif
5943 }       
5944
5945 static void
5946 register_jit_stats (void)
5947 {
5948         mono_counters_register ("Compiled methods", MONO_COUNTER_JIT | MONO_COUNTER_WORD, &mono_jit_stats.methods_compiled);
5949         mono_counters_register ("Methods from AOT", MONO_COUNTER_JIT | MONO_COUNTER_WORD, &mono_jit_stats.methods_aot);
5950         mono_counters_register ("Methods JITted using LLVM", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_with_llvm);   
5951         mono_counters_register ("Methods JITted using mono JIT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_without_llvm);
5952         mono_counters_register ("Total time spent JITting (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_time);
5953 }
5954
5955 static void runtime_invoke_info_free (gpointer value);
5956  
5957 static void
5958 mini_create_jit_domain_info (MonoDomain *domain)
5959 {
5960         MonoJitDomainInfo *info = g_new0 (MonoJitDomainInfo, 1);
5961
5962         info->class_init_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
5963         info->jump_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
5964         info->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
5965         info->delegate_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
5966         info->llvm_vcall_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
5967         info->runtime_invoke_hash = g_hash_table_new_full (mono_aligned_addr_hash, NULL, NULL, runtime_invoke_info_free);
5968         info->seq_points = g_hash_table_new_full (mono_aligned_addr_hash, NULL, NULL, g_free);
5969         info->arch_seq_points = g_hash_table_new (mono_aligned_addr_hash, NULL);
5970
5971         domain->runtime_info = info;
5972 }
5973
5974 static void
5975 delete_jump_list (gpointer key, gpointer value, gpointer user_data)
5976 {
5977         g_slist_free (value);
5978 }
5979
5980 static void
5981 dynamic_method_info_free (gpointer key, gpointer value, gpointer user_data)
5982 {
5983         MonoJitDynamicMethodInfo *di = value;
5984         mono_code_manager_destroy (di->code_mp);
5985         g_free (di);
5986 }
5987
5988 static void
5989 runtime_invoke_info_free (gpointer value)
5990 {
5991         RuntimeInvokeInfo *info = (RuntimeInvokeInfo*)value;
5992
5993 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
5994         if (info->dyn_call_info)
5995                 mono_arch_dyn_call_free (info->dyn_call_info);
5996 #endif
5997         g_free (info);
5998 }
5999
6000 static void
6001 mini_free_jit_domain_info (MonoDomain *domain)
6002 {
6003         MonoJitDomainInfo *info = domain_jit_info (domain);
6004
6005         if (info->jump_target_hash) {
6006                 g_hash_table_foreach (info->jump_target_hash, delete_jump_list, NULL);
6007                 g_hash_table_destroy (info->jump_target_hash);
6008         }
6009         if (info->jump_target_got_slot_hash) {
6010                 g_hash_table_foreach (info->jump_target_got_slot_hash, delete_jump_list, NULL);
6011                 g_hash_table_destroy (info->jump_target_got_slot_hash);
6012         }
6013         if (info->dynamic_code_hash) {
6014                 g_hash_table_foreach (info->dynamic_code_hash, dynamic_method_info_free, NULL);
6015                 g_hash_table_destroy (info->dynamic_code_hash);
6016         }
6017         if (info->method_code_hash)
6018                 g_hash_table_destroy (info->method_code_hash);
6019         g_hash_table_destroy (info->class_init_trampoline_hash);
6020         g_hash_table_destroy (info->jump_trampoline_hash);
6021         g_hash_table_destroy (info->jit_trampoline_hash);
6022         g_hash_table_destroy (info->delegate_trampoline_hash);
6023         if (info->static_rgctx_trampoline_hash)
6024                 g_hash_table_destroy (info->static_rgctx_trampoline_hash);
6025         g_hash_table_destroy (info->llvm_vcall_trampoline_hash);
6026         g_hash_table_destroy (info->runtime_invoke_hash);
6027         g_hash_table_destroy (info->seq_points);
6028         g_hash_table_destroy (info->arch_seq_points);
6029
6030         if (info->agent_info)
6031                 mono_debugger_agent_free_domain_info (domain);
6032
6033         g_free (domain->runtime_info);
6034         domain->runtime_info = NULL;
6035 }
6036
6037 MonoDomain *
6038 mini_init (const char *filename, const char *runtime_version)
6039 {
6040         MonoDomain *domain;
6041         MonoRuntimeCallbacks callbacks;
6042
6043         MONO_PROBE_VES_INIT_BEGIN ();
6044
6045 #if defined(__linux__) && !defined(__native_client__)
6046         if (access ("/proc/self/maps", F_OK) != 0) {
6047                 g_print ("Mono requires /proc to be mounted.\n");
6048                 exit (1);
6049         }
6050 #endif
6051
6052         /* Happens when using the embedding interface */
6053         if (!default_opt_set)
6054                 default_opt = mono_parse_default_optimizations (NULL);
6055
6056         InitializeCriticalSection (&jit_mutex);
6057
6058 #ifdef MONO_DEBUGGER_SUPPORTED
6059         if (mini_debug_running_inside_mdb ())
6060                 mini_debugger_init ();
6061 #endif
6062
6063 #ifdef MINI_HAVE_FAST_TLS
6064         MINI_FAST_TLS_INIT (mono_jit_tls);
6065         MINI_FAST_TLS_INIT (mono_lmf_addr);
6066 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
6067         MINI_FAST_TLS_INIT (mono_lmf);
6068 #endif
6069 #endif
6070
6071 #ifdef MONO_ARCH_HAVE_TLS_GET
6072         mono_runtime_set_has_tls_get (MONO_ARCH_HAVE_TLS_GET);
6073 #else
6074         mono_runtime_set_has_tls_get (FALSE);
6075 #endif
6076
6077         if (!global_codeman)
6078                 global_codeman = mono_code_manager_new ();
6079         jit_icall_name_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6080
6081         memset (&callbacks, 0, sizeof (callbacks));
6082         callbacks.create_ftnptr = mini_create_ftnptr;
6083         callbacks.get_addr_from_ftnptr = mini_get_addr_from_ftnptr;
6084         callbacks.get_runtime_build_info = mono_get_runtime_build_info;
6085
6086 #ifdef MONO_ARCH_HAVE_IMT
6087         if (mono_use_imt) {
6088                 callbacks.get_vtable_trampoline = mini_get_vtable_trampoline;
6089                 callbacks.get_imt_trampoline = mini_get_imt_trampoline;
6090         }
6091 #endif
6092
6093         mono_install_callbacks (&callbacks);
6094
6095         if (getenv ("MONO_DEBUG") != NULL)
6096                 mini_parse_debug_options ();
6097         
6098         mono_arch_cpu_init ();
6099
6100         mono_arch_init ();
6101
6102         mono_unwind_init ();
6103
6104         mini_gc_init ();
6105
6106         if (getenv ("MONO_XDEBUG")) {
6107                 char *xdebug_opts = getenv ("MONO_XDEBUG");
6108                 mono_xdebug_init (xdebug_opts);
6109                 /* So methods for multiple domains don't have the same address */
6110                 mono_dont_free_domains = TRUE;
6111                 mono_using_xdebug = TRUE;
6112         } else if (mini_get_debug_options ()->gdb) {
6113                 mono_xdebug_init ((char*)"gdb");
6114                 mono_dont_free_domains = TRUE;
6115                 mono_using_xdebug = TRUE;
6116         }
6117
6118 #ifdef ENABLE_LLVM
6119         if (mono_use_llvm) {
6120                 if (!mono_llvm_load (NULL)) {
6121                         mono_use_llvm = FALSE;
6122                         fprintf (stderr, "Mono Warning: llvm support could not be loaded.\n");
6123                 }
6124         }
6125         if (mono_use_llvm)
6126                 mono_llvm_init ();
6127 #endif
6128
6129         mono_trampolines_init ();
6130
6131         if (!g_thread_supported ())
6132                 g_thread_init (NULL);
6133
6134         mono_jit_tls_id = TlsAlloc ();
6135         setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
6136
6137         if (default_opt & MONO_OPT_AOT)
6138                 mono_aot_init ();
6139
6140         mono_debugger_agent_init ();
6141
6142 #ifdef MONO_ARCH_GSHARED_SUPPORTED
6143         mono_set_generic_sharing_supported (TRUE);
6144 #endif
6145
6146 #ifndef MONO_CROSS_COMPILE
6147         mono_runtime_install_handlers ();
6148 #endif
6149         mono_threads_install_cleanup (mini_thread_cleanup);
6150
6151 #ifdef MONO_ARCH_HAVE_NOTIFY_PENDING_EXC
6152         // This is experimental code so provide an env var to switch it off
6153         if (getenv ("MONO_DISABLE_PENDING_EXCEPTIONS")) {
6154                 printf ("MONO_DISABLE_PENDING_EXCEPTIONS env var set.\n");
6155         } else {
6156                 check_for_pending_exc = FALSE;
6157                 mono_threads_install_notify_pending_exc (mono_arch_notify_pending_exc);
6158         }
6159 #endif
6160
6161 #define JIT_TRAMPOLINES_WORK
6162 #ifdef JIT_TRAMPOLINES_WORK
6163         mono_install_compile_method (mono_jit_compile_method);
6164         mono_install_free_method (mono_jit_free_method);
6165         mono_install_trampoline (mono_create_jit_trampoline);
6166         mono_install_jump_trampoline (mono_create_jump_trampoline);
6167         mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
6168         mono_install_delegate_trampoline (mono_create_delegate_trampoline);
6169         mono_install_create_domain_hook (mini_create_jit_domain_info);
6170         mono_install_free_domain_hook (mini_free_jit_domain_info);
6171 #endif
6172 #define JIT_INVOKE_WORKS
6173 #ifdef JIT_INVOKE_WORKS
6174         mono_install_runtime_invoke (mono_jit_runtime_invoke);
6175 #endif
6176         mono_install_stack_walk (mono_jit_walk_stack);
6177         mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
6178         mono_install_get_class_from_name (mono_aot_get_class_from_name);
6179         mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
6180
6181         if (debug_options.collect_pagefault_stats) {
6182                 mono_aot_set_make_unreadable (TRUE);
6183         }
6184
6185         if (runtime_version)
6186                 domain = mono_init_version (filename, runtime_version);
6187         else
6188                 domain = mono_init_from_assembly (filename, filename);
6189
6190         if (mono_aot_only) {
6191                 /* This helps catch code allocation requests */
6192                 mono_code_manager_set_read_only (domain->code_mp);
6193         }
6194
6195 #ifdef MONO_ARCH_HAVE_IMT
6196         if (mono_use_imt) {
6197                 if (mono_aot_only)
6198                         mono_install_imt_thunk_builder (mono_aot_get_imt_thunk);
6199                 else
6200                         mono_install_imt_thunk_builder (mono_arch_build_imt_thunk);
6201         }
6202 #endif
6203
6204         /* This must come after mono_init () in the aot-only case */
6205         mono_exceptions_init ();
6206         mono_install_handler (mono_get_throw_exception ());
6207
6208         mono_icall_init ();
6209
6210         mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info", 
6211                                 ves_icall_get_frame_info);
6212         mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace", 
6213                                 ves_icall_get_trace);
6214         mono_add_internal_call ("System.Exception::get_trace", 
6215                                 ves_icall_System_Exception_get_trace);
6216         mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityFrame",
6217                                 ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
6218         mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityStack",
6219                                 ves_icall_System_Security_SecurityFrame_GetSecurityStack);
6220         mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers", 
6221                                 mono_runtime_install_handlers);
6222
6223         mono_create_helper_signatures ();
6224
6225         register_jit_stats ();
6226
6227 #define JIT_CALLS_WORK
6228 #ifdef JIT_CALLS_WORK
6229         /* Needs to be called here since register_jit_icall depends on it */
6230         mono_marshal_init ();
6231
6232         mono_arch_register_lowlevel_calls ();
6233         register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
6234         register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
6235         register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
6236         register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
6237         register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
6238         register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "void", TRUE);
6239         register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
6240
6241         register_icall (mono_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
6242         register_icall (mono_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
6243         register_icall (mono_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception", 
6244                                  "void ptr", TRUE);
6245         register_icall (mono_thread_get_undeniable_exception, "mono_thread_get_undeniable_exception", "object", FALSE);
6246         register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "void", FALSE);
6247         register_icall (mono_thread_force_interruption_checkpoint, "mono_thread_force_interruption_checkpoint", "void", FALSE);
6248         register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
6249         register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
6250
6251 #if defined(__native_client__) || defined(__native_client_codegen__)
6252         register_icall (mono_nacl_gc, "mono_nacl_gc", "void", TRUE);
6253 #endif
6254         /* 
6255          * NOTE, NOTE, NOTE, NOTE:
6256          * when adding emulation for some opcodes, remember to also add a dummy
6257          * rule to the burg files, because we need the arity information to be correct.
6258          */
6259 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
6260         mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, TRUE);
6261         mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, FALSE);
6262         mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, FALSE);
6263         mono_register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, FALSE);
6264         mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, FALSE);
6265         mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, FALSE);
6266         mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, FALSE);
6267 #endif
6268
6269 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
6270         mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, TRUE);
6271         mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, TRUE);
6272         mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, TRUE);
6273 #endif
6274
6275 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
6276         mono_register_opcode_emulation (CEE_DIV, "__emul_idiv", "int32 int32 int32", mono_idiv, FALSE);
6277         mono_register_opcode_emulation (CEE_DIV_UN, "__emul_idiv_un", "int32 int32 int32", mono_idiv_un, FALSE);
6278         mono_register_opcode_emulation (CEE_REM, "__emul_irem", "int32 int32 int32", mono_irem, FALSE);
6279         mono_register_opcode_emulation (CEE_REM_UN, "__emul_irem_un", "int32 int32 int32", mono_irem_un, FALSE);
6280         mono_register_opcode_emulation (OP_IDIV, "__emul_op_idiv", "int32 int32 int32", mono_idiv, FALSE);
6281         mono_register_opcode_emulation (OP_IDIV_UN, "__emul_op_idiv_un", "int32 int32 int32", mono_idiv_un, FALSE);
6282         mono_register_opcode_emulation (OP_IREM, "__emul_op_irem", "int32 int32 int32", mono_irem, FALSE);
6283         mono_register_opcode_emulation (OP_IREM_UN, "__emul_op_irem_un", "int32 int32 int32", mono_irem_un, FALSE);
6284 #endif
6285
6286 #ifdef MONO_ARCH_EMULATE_MUL_DIV
6287         mono_register_opcode_emulation (CEE_MUL, "__emul_imul", "int32 int32 int32", mono_imul, TRUE);
6288         mono_register_opcode_emulation (OP_IMUL, "__emul_op_imul", "int32 int32 int32", mono_imul, TRUE);
6289 #endif
6290
6291 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_MUL_OVF)
6292         mono_register_opcode_emulation (CEE_MUL_OVF, "__emul_imul_ovf", "int32 int32 int32", mono_imul_ovf, FALSE);
6293         mono_register_opcode_emulation (CEE_MUL_OVF_UN, "__emul_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, FALSE);
6294         mono_register_opcode_emulation (OP_IMUL_OVF, "__emul_op_imul_ovf", "int32 int32 int32", mono_imul_ovf, FALSE);
6295         mono_register_opcode_emulation (OP_IMUL_OVF_UN, "__emul_op_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, FALSE);
6296 #endif
6297
6298 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_SOFT_FLOAT)
6299         mono_register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, FALSE);
6300 #endif
6301
6302         mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, FALSE);
6303         mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, FALSE);
6304         mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, FALSE);
6305         mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, FALSE);
6306
6307 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
6308         mono_register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, FALSE);
6309 #endif
6310 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
6311         mono_register_opcode_emulation (CEE_CONV_R_UN, "__emul_conv_r_un", "double int32", mono_conv_to_r8_un, FALSE);
6312         mono_register_opcode_emulation (OP_ICONV_TO_R_UN, "__emul_iconv_to_r_un", "double int32", mono_conv_to_r8_un, FALSE);
6313 #endif
6314 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
6315         mono_register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, FALSE);
6316 #endif
6317 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
6318         mono_register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, FALSE);
6319 #endif
6320 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
6321         mono_register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", "double long", mono_lconv_to_r8_un, FALSE);
6322 #endif
6323 #ifdef MONO_ARCH_EMULATE_FREM
6324 #if defined(__default_codegen__)
6325         mono_register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, FALSE);
6326 #elif defined(__native_client_codegen__)
6327         mono_register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", mono_fmod, FALSE);
6328 #endif
6329 #endif
6330
6331 #ifdef MONO_ARCH_SOFT_FLOAT
6332         mono_register_opcode_emulation (OP_FSUB, "__emul_fsub", "double double double", mono_fsub, FALSE);
6333         mono_register_opcode_emulation (OP_FADD, "__emul_fadd", "double double double", mono_fadd, FALSE);
6334         mono_register_opcode_emulation (OP_FMUL, "__emul_fmul", "double double double", mono_fmul, FALSE);
6335         mono_register_opcode_emulation (OP_FNEG, "__emul_fneg", "double double", mono_fneg, FALSE);
6336         mono_register_opcode_emulation (CEE_CONV_R8, "__emul_conv_r8", "double int32", mono_conv_to_r8, FALSE);
6337         mono_register_opcode_emulation (OP_ICONV_TO_R8, "__emul_iconv_to_r8", "double int32", mono_conv_to_r8, FALSE);
6338         mono_register_opcode_emulation (CEE_CONV_R4, "__emul_conv_r4", "double int32", mono_conv_to_r4, FALSE);
6339         mono_register_opcode_emulation (OP_ICONV_TO_R4, "__emul_iconv_to_r4", "double int32", mono_conv_to_r4, FALSE);
6340         mono_register_opcode_emulation (OP_FCONV_TO_R4, "__emul_fconv_to_r4", "double double", mono_fconv_r4, FALSE);
6341         mono_register_opcode_emulation (OP_FCONV_TO_I1, "__emul_fconv_to_i1", "int8 double", mono_fconv_i1, FALSE);
6342         mono_register_opcode_emulation (OP_FCONV_TO_I2, "__emul_fconv_to_i2", "int16 double", mono_fconv_i2, FALSE);
6343         mono_register_opcode_emulation (OP_FCONV_TO_I4, "__emul_fconv_to_i4", "int32 double", mono_fconv_i4, FALSE);
6344         mono_register_opcode_emulation (OP_FCONV_TO_U1, "__emul_fconv_to_u1", "uint8 double", mono_fconv_u1, FALSE);
6345         mono_register_opcode_emulation (OP_FCONV_TO_U2, "__emul_fconv_to_u2", "uint16 double", mono_fconv_u2, FALSE);
6346 #if SIZEOF_VOID_P == 4
6347         mono_register_opcode_emulation (OP_FCONV_TO_I, "__emul_fconv_to_i", "int32 double", mono_fconv_i4, FALSE);
6348 #endif
6349
6350         mono_register_opcode_emulation (OP_FBEQ, "__emul_fcmp_eq", "uint32 double double", mono_fcmp_eq, FALSE);
6351         mono_register_opcode_emulation (OP_FBLT, "__emul_fcmp_lt", "uint32 double double", mono_fcmp_lt, FALSE);
6352         mono_register_opcode_emulation (OP_FBGT, "__emul_fcmp_gt", "uint32 double double", mono_fcmp_gt, FALSE);
6353         mono_register_opcode_emulation (OP_FBLE, "__emul_fcmp_le", "uint32 double double", mono_fcmp_le, FALSE);
6354         mono_register_opcode_emulation (OP_FBGE, "__emul_fcmp_ge", "uint32 double double", mono_fcmp_ge, FALSE);
6355         mono_register_opcode_emulation (OP_FBNE_UN, "__emul_fcmp_ne_un", "uint32 double double", mono_fcmp_ne_un, FALSE);
6356         mono_register_opcode_emulation (OP_FBLT_UN, "__emul_fcmp_lt_un", "uint32 double double", mono_fcmp_lt_un, FALSE);
6357         mono_register_opcode_emulation (OP_FBGT_UN, "__emul_fcmp_gt_un", "uint32 double double", mono_fcmp_gt_un, FALSE);
6358         mono_register_opcode_emulation (OP_FBLE_UN, "__emul_fcmp_le_un", "uint32 double double", mono_fcmp_le_un, FALSE);
6359         mono_register_opcode_emulation (OP_FBGE_UN, "__emul_fcmp_ge_un", "uint32 double double", mono_fcmp_ge_un, FALSE);
6360
6361         mono_register_opcode_emulation (OP_FCEQ, "__emul_fcmp_ceq", "uint32 double double", mono_fceq, FALSE);
6362         mono_register_opcode_emulation (OP_FCGT, "__emul_fcmp_cgt", "uint32 double double", mono_fcgt, FALSE);
6363         mono_register_opcode_emulation (OP_FCGT_UN, "__emul_fcmp_cgt_un", "uint32 double double", mono_fcgt_un, FALSE);
6364         mono_register_opcode_emulation (OP_FCLT, "__emul_fcmp_clt", "uint32 double double", mono_fclt, FALSE);
6365         mono_register_opcode_emulation (OP_FCLT_UN, "__emul_fcmp_clt_un", "uint32 double double", mono_fclt_un, FALSE);
6366
6367         register_icall (mono_fload_r4, "mono_fload_r4", "double ptr", FALSE);
6368         register_icall (mono_fstore_r4, "mono_fstore_r4", "void double ptr", FALSE);
6369         register_icall (mono_fload_r4_arg, "mono_fload_r4_arg", "uint32 double", FALSE);
6370         register_icall (mono_isfinite, "mono_isfinite", "uint32 double", FALSE);
6371 #endif
6372
6373 #ifdef COMPRESSED_INTERFACE_BITMAP
6374         register_icall (mono_class_interface_match, "mono_class_interface_match", "uint32 ptr int32", TRUE);
6375 #endif
6376
6377 #if SIZEOF_REGISTER == 4
6378         mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, TRUE);
6379 #endif
6380
6381         /* other jit icalls */
6382         register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
6383         register_icall (mono_class_static_field_address , "mono_class_static_field_address", 
6384                                  "ptr ptr ptr", FALSE);
6385         register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
6386         register_icall (mono_ldtoken_wrapper_generic_shared, "mono_ldtoken_wrapper_generic_shared",
6387                 "ptr ptr ptr ptr", FALSE);
6388         register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
6389         register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
6390         register_icall (mono_helper_stelem_ref_check, "helper_stelem_ref_check", "void object object", FALSE);
6391         register_icall (mono_object_new, "mono_object_new", "object ptr ptr", FALSE);
6392         register_icall (mono_object_new_specific, "mono_object_new_specific", "object ptr", FALSE);
6393         register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
6394         register_icall (mono_array_new_specific, "mono_array_new_specific", "object ptr int32", FALSE);
6395         register_icall (mono_runtime_class_init, "mono_runtime_class_init", "void ptr", FALSE);
6396         register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
6397         register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
6398         register_icall (mono_ldvirtfn_gshared, "mono_ldvirtfn_gshared", "ptr object ptr", FALSE);
6399         register_icall (mono_helper_compile_generic_method, "compile_generic_method", "ptr object ptr ptr", FALSE);
6400         register_icall (mono_helper_ldstr, "helper_ldstr", "object ptr int", FALSE);
6401         register_icall (mono_helper_ldstr_mscorlib, "helper_ldstr_mscorlib", "object int", FALSE);
6402         register_icall (mono_helper_newobj_mscorlib, "helper_newobj_mscorlib", "object int", FALSE);
6403         register_icall (mono_value_copy, "mono_value_copy", "void ptr ptr ptr", FALSE);
6404         register_icall (mono_object_castclass, "mono_object_castclass", "object object ptr", FALSE);
6405         register_icall (mono_break, "mono_break", NULL, TRUE);
6406         register_icall (mono_create_corlib_exception_0, "mono_create_corlib_exception_0", "object int", TRUE);
6407         register_icall (mono_create_corlib_exception_1, "mono_create_corlib_exception_1", "object int object", TRUE);
6408         register_icall (mono_create_corlib_exception_2, "mono_create_corlib_exception_2", "object int object object", TRUE);
6409         register_icall (mono_array_new_1, "mono_array_new_1", "object ptr int", FALSE);
6410         register_icall (mono_array_new_2, "mono_array_new_2", "object ptr int int", FALSE);
6411         register_icall (mono_array_new_3, "mono_array_new_3", "object ptr int int int", FALSE);
6412         register_icall (mono_get_native_calli_wrapper, "mono_get_native_calli_wrapper", "ptr ptr ptr ptr", FALSE);
6413         register_icall (mono_resume_unwind, "mono_resume_unwind", "void", TRUE);
6414
6415         register_icall (mono_gc_wbarrier_value_copy_bitmap, "mono_gc_wbarrier_value_copy_bitmap", "void ptr ptr int int", FALSE);
6416
6417         register_icall (mono_object_castclass_with_cache, "mono_object_castclass_with_cache", "object object ptr ptr", FALSE);
6418         register_icall (mono_object_isinst_with_cache, "mono_object_isinst_with_cache", "object object ptr ptr", FALSE);
6419
6420 #endif
6421
6422         mono_generic_sharing_init ();
6423
6424 #ifdef MONO_ARCH_SIMD_INTRINSICS
6425         mono_simd_intrinsics_init ();
6426 #endif
6427
6428 #if MONO_SUPPORT_TASKLETS
6429         mono_tasklets_init ();
6430 #endif
6431
6432         if (mono_compile_aot)
6433                 /* 
6434                  * Avoid running managed code when AOT compiling, since the platform
6435                  * might only support aot-only execution.
6436                  */
6437                 mono_runtime_set_no_exec (TRUE);
6438
6439 #define JIT_RUNTIME_WORKS
6440 #ifdef JIT_RUNTIME_WORKS
6441         mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
6442         mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
6443         mono_thread_attach (domain);
6444 #endif
6445
6446         mono_profiler_runtime_initialized ();
6447
6448         MONO_PROBE_VES_INIT_END ();
6449         
6450         return domain;
6451 }
6452
6453 MonoJitStats mono_jit_stats = {0};
6454
6455 static void 
6456 print_jit_stats (void)
6457 {
6458         if (mono_jit_stats.enabled) {
6459                 g_print ("Mono Jit statistics\n");
6460                 g_print ("Methods cache lookup:   %ld\n", mono_jit_stats.methods_lookups);
6461                 g_print ("Basic blocks:           %ld\n", mono_jit_stats.basic_blocks);
6462                 g_print ("Max basic blocks:       %ld\n", mono_jit_stats.max_basic_blocks);
6463                 g_print ("Allocated vars:         %ld\n", mono_jit_stats.allocate_var);
6464                 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
6465                 g_print ("Native code size:       %ld\n", mono_jit_stats.native_code_size);
6466                 g_print ("Max code size ratio:    %.2f (%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
6467                                  mono_jit_stats.max_ratio_method);
6468                 g_print ("Biggest method:         %ld (%s)\n", mono_jit_stats.biggest_method_size,
6469                                  mono_jit_stats.biggest_method);
6470                 g_print ("Code reallocs:          %ld\n", mono_jit_stats.code_reallocs);
6471                 g_print ("Allocated code size:    %ld\n", mono_jit_stats.allocated_code_size);
6472                 g_print ("Inlineable methods:     %ld\n", mono_jit_stats.inlineable_methods);
6473                 g_print ("Inlined methods:        %ld\n", mono_jit_stats.inlined_methods);
6474                 g_print ("Regvars:                %ld\n", mono_jit_stats.regvars);
6475                 g_print ("Locals stack size:      %ld\n", mono_jit_stats.locals_stack_size);
6476
6477                 g_print ("\nCreated object count:   %ld\n", mono_stats.new_object_count);
6478                 g_print ("Delegates created:      %ld\n", mono_stats.delegate_creations);
6479                 g_print ("Initialized classes:    %ld\n", mono_stats.initialized_class_count);
6480                 g_print ("Used classes:           %ld\n", mono_stats.used_class_count);
6481                 g_print ("Generic vtables:        %ld\n", mono_stats.generic_vtable_count);
6482                 g_print ("Methods:                %ld\n", mono_stats.method_count);
6483                 g_print ("Static data size:       %ld\n", mono_stats.class_static_data_size);
6484                 g_print ("VTable data size:       %ld\n", mono_stats.class_vtable_size);
6485                 g_print ("Mscorlib mempool size:  %d\n", mono_mempool_get_allocated (mono_defaults.corlib->mempool));
6486
6487                 g_print ("\nInitialized classes:    %ld\n", mono_stats.generic_class_count);
6488                 g_print ("Inflated types:         %ld\n", mono_stats.inflated_type_count);
6489                 g_print ("Generics virtual invokes: %ld\n", mono_jit_stats.generic_virtual_invocations);
6490
6491                 g_print ("Sharable generic methods: %ld\n", mono_stats.generics_sharable_methods);
6492                 g_print ("Unsharable generic methods: %ld\n", mono_stats.generics_unsharable_methods);
6493                 g_print ("Shared generic methods: %ld\n", mono_stats.generics_shared_methods);
6494
6495                 g_print ("Dynamic code allocs:    %ld\n", mono_stats.dynamic_code_alloc_count);
6496                 g_print ("Dynamic code bytes:     %ld\n", mono_stats.dynamic_code_bytes_count);
6497                 g_print ("Dynamic code frees:     %ld\n", mono_stats.dynamic_code_frees_count);
6498
6499                 g_print ("IMT tables size:        %ld\n", mono_stats.imt_tables_size);
6500                 g_print ("IMT number of tables:   %ld\n", mono_stats.imt_number_of_tables);
6501                 g_print ("IMT number of methods:  %ld\n", mono_stats.imt_number_of_methods);
6502                 g_print ("IMT used slots:         %ld\n", mono_stats.imt_used_slots);
6503                 g_print ("IMT colliding slots:    %ld\n", mono_stats.imt_slots_with_collisions);
6504                 g_print ("IMT max collisions:     %ld\n", mono_stats.imt_max_collisions_in_slot);
6505                 g_print ("IMT methods at max col: %ld\n", mono_stats.imt_method_count_when_max_collisions);
6506                 g_print ("IMT thunks size:        %ld\n", mono_stats.imt_thunks_size);
6507
6508                 g_print ("JIT info table inserts: %ld\n", mono_stats.jit_info_table_insert_count);
6509                 g_print ("JIT info table removes: %ld\n", mono_stats.jit_info_table_remove_count);
6510                 g_print ("JIT info table lookups: %ld\n", mono_stats.jit_info_table_lookup_count);
6511
6512                 g_print ("Hazardous pointers:     %ld\n", mono_stats.hazardous_pointer_count);
6513                 g_print ("Minor GC collections:   %ld\n", mono_stats.minor_gc_count);
6514                 g_print ("Major GC collections:   %ld\n", mono_stats.major_gc_count);
6515                 g_print ("Minor GC time in msecs: %lf\n", (double)mono_stats.minor_gc_time_usecs / 1000.0);
6516                 g_print ("Major GC time in msecs: %lf\n", (double)mono_stats.major_gc_time_usecs / 1000.0);
6517                 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
6518                         g_print ("\nDecl security check   : %ld\n", mono_jit_stats.cas_declsec_check);
6519                         g_print ("LinkDemand (user)     : %ld\n", mono_jit_stats.cas_linkdemand);
6520                         g_print ("LinkDemand (icall)    : %ld\n", mono_jit_stats.cas_linkdemand_icall);
6521                         g_print ("LinkDemand (pinvoke)  : %ld\n", mono_jit_stats.cas_linkdemand_pinvoke);
6522                         g_print ("LinkDemand (aptc)     : %ld\n", mono_jit_stats.cas_linkdemand_aptc);
6523                         g_print ("Demand (code gen)     : %ld\n", mono_jit_stats.cas_demand_generation);
6524                 }
6525
6526                 g_free (mono_jit_stats.max_ratio_method);
6527                 mono_jit_stats.max_ratio_method = NULL;
6528                 g_free (mono_jit_stats.biggest_method);
6529                 mono_jit_stats.biggest_method = NULL;
6530         }
6531 }
6532
6533 void
6534 mini_cleanup (MonoDomain *domain)
6535 {
6536         mono_runtime_shutdown_stat_profiler ();
6537         
6538 #ifndef DISABLE_COM
6539         cominterop_release_all_rcws ();
6540 #endif
6541
6542 #ifndef MONO_CROSS_COMPILE      
6543         mono_runtime_shutdown ();
6544         /* 
6545          * mono_runtime_cleanup() and mono_domain_finalize () need to
6546          * be called early since they need the execution engine still
6547          * fully working (mono_domain_finalize may invoke managed finalizers
6548          * and mono_runtime_cleanup will wait for other threads to finish).
6549          */
6550         mono_domain_finalize (domain, 2000);
6551 #endif
6552
6553         /* This accesses metadata so needs to be called before runtime shutdown */
6554         print_jit_stats ();
6555
6556         mono_profiler_shutdown ();
6557
6558 #ifndef MONO_CROSS_COMPILE
6559         mono_runtime_cleanup (domain);
6560 #endif
6561
6562         free_jit_tls_data (TlsGetValue (mono_jit_tls_id));
6563
6564         mono_icall_cleanup ();
6565
6566         mono_runtime_cleanup_handlers ();
6567
6568         mono_domain_free (domain, TRUE);
6569
6570         mono_debugger_cleanup ();
6571
6572 #ifdef ENABLE_LLVM
6573         if (mono_use_llvm)
6574                 mono_llvm_cleanup ();
6575 #endif
6576
6577         mono_aot_cleanup ();
6578
6579         mono_trampolines_cleanup ();
6580
6581         mono_unwind_cleanup ();
6582
6583         if (!mono_dont_free_global_codeman)
6584                 mono_code_manager_destroy (global_codeman);
6585         g_hash_table_destroy (jit_icall_name_hash);
6586         g_free (emul_opcode_map);
6587         g_free (emul_opcode_opcodes);
6588         g_free (vtable_trampolines);
6589
6590         mono_arch_cleanup ();
6591
6592         mono_generic_sharing_cleanup ();
6593
6594         mono_cleanup ();
6595
6596         mono_trace_cleanup ();
6597
6598         mono_counters_dump (-1, stdout);
6599
6600         if (mono_inject_async_exc_method)
6601                 mono_method_desc_free (mono_inject_async_exc_method);
6602
6603         TlsFree(mono_jit_tls_id);
6604
6605         DeleteCriticalSection (&jit_mutex);
6606
6607         DeleteCriticalSection (&mono_delegate_section);
6608 }
6609
6610 void
6611 mono_set_defaults (int verbose_level, guint32 opts)
6612 {
6613         mini_verbose = verbose_level;
6614         default_opt = opts;
6615         default_opt_set = TRUE;
6616 }
6617
6618 void
6619 mono_disable_optimizations (guint32 opts)
6620 {
6621         default_opt &= ~opts;
6622 }
6623
6624 /*
6625  * mono_get_runtime_build_info:
6626  *
6627  *   Return the runtime version + build date in string format.
6628  * The returned string is owned by the caller.
6629  */
6630 char*
6631 mono_get_runtime_build_info (void)
6632 {
6633         if (mono_build_date)
6634                 return g_strdup_printf ("%s (%s %s)", VERSION, FULL_VERSION, mono_build_date);
6635         else
6636                 return g_strdup_printf ("%s (%s)", VERSION, FULL_VERSION);
6637 }
6638
6639 static void
6640 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
6641 {
6642         GHashTable *assemblies = (GHashTable*)user_data;
6643         MonoImage *image = mono_assembly_get_image (ass);
6644         MonoMethod *method, *invoke;
6645         int i, count = 0;
6646
6647         if (g_hash_table_lookup (assemblies, ass))
6648                 return;
6649
6650         g_hash_table_insert (assemblies, ass, ass);
6651
6652         if (mini_verbose > 0)
6653                 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
6654
6655         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
6656                 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
6657                 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
6658                         continue;
6659
6660                 count++;
6661                 if (mini_verbose > 1) {
6662                         char * desc = mono_method_full_name (method, TRUE);
6663                         g_print ("Compiling %d %s\n", count, desc);
6664                         g_free (desc);
6665                 }
6666                 mono_compile_method (method);
6667                 if (strcmp (method->name, "Finalize") == 0) {
6668                         invoke = mono_marshal_get_runtime_invoke (method, FALSE);
6669                         mono_compile_method (invoke);
6670                 }
6671                 if (method->klass->marshalbyref && mono_method_signature (method)->hasthis) {
6672                         invoke = mono_marshal_get_remoting_invoke_with_check (method);
6673                         mono_compile_method (invoke);
6674                 }
6675         }
6676
6677         /* Load and precompile referenced assemblies as well */
6678         for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
6679                 mono_assembly_load_reference (image, i);
6680                 if (image->references [i])
6681                         mono_precompile_assembly (image->references [i], assemblies);
6682         }
6683 }
6684
6685 void mono_precompile_assemblies ()
6686 {
6687         GHashTable *assemblies = g_hash_table_new (NULL, NULL);
6688
6689         mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
6690
6691         g_hash_table_destroy (assemblies);
6692 }
6693
6694 #ifndef DISABLE_JIT
6695
6696 void*
6697 mono_arch_instrument_epilog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments) {
6698         return mono_arch_instrument_epilog_full (cfg, func, p, enable_arguments, FALSE);
6699 }
6700
6701 void
6702 mono_cfg_add_try_hole (MonoCompile *cfg, MonoExceptionClause *clause, guint8 *start, MonoBasicBlock *bb)
6703 {
6704         TryBlockHole *hole = mono_mempool_alloc (cfg->mempool, sizeof (TryBlockHole));
6705         hole->clause = clause;
6706         hole->start_offset = start - cfg->native_code;
6707         hole->basic_block = bb;
6708
6709         cfg->try_block_holes = g_slist_append_mempool (cfg->mempool, cfg->try_block_holes, hole);
6710 }
6711
6712 void
6713 mono_cfg_set_exception (MonoCompile *cfg, int type)
6714 {
6715         cfg->exception_type = type;
6716 }
6717
6718 #endif