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