Use MONO_FAST_TLS_ADDR instead of explicitly taking the address of mono_lmf.
[mono-project.git] / mono / mini / mini.c
blob3f71b3f46893d4d89083fcc10e62cbd4eee6298c
1 /*
2 * mini.c: The new Mono code generator.
4 * Authors:
5 * Paolo Molaro (lupus@ximian.com)
6 * Dietmar Maurer (dietmar@ximian.com)
8 * Copyright 2002-2003 Ximian, Inc.
9 * Copyright 2003-2010 Novell, Inc.
10 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
13 #define MONO_LLVM_IN_MINI 1
14 #include <config.h>
15 #include <signal.h>
16 #ifdef HAVE_ALLOCA_H
17 #include <alloca.h>
18 #endif
19 #ifdef HAVE_UNISTD_H
20 #include <unistd.h>
21 #endif
22 #include <math.h>
23 #ifdef HAVE_SYS_TIME_H
24 #include <sys/time.h>
25 #endif
27 #include <mono/utils/memcheck.h>
29 #include <mono/metadata/assembly.h>
30 #include <mono/metadata/loader.h>
31 #include <mono/metadata/tabledefs.h>
32 #include <mono/metadata/class.h>
33 #include <mono/metadata/object.h>
34 #include <mono/metadata/tokentype.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/threads.h>
37 #include <mono/metadata/appdomain.h>
38 #include <mono/metadata/debug-helpers.h>
39 #include <mono/io-layer/io-layer.h>
40 #include "mono/metadata/profiler.h"
41 #include <mono/metadata/profiler-private.h>
42 #include <mono/metadata/mono-config.h>
43 #include <mono/metadata/environment.h>
44 #include <mono/metadata/mono-debug.h>
45 #include <mono/metadata/gc-internal.h>
46 #include <mono/metadata/threads-types.h>
47 #include <mono/metadata/verify.h>
48 #include <mono/metadata/verify-internals.h>
49 #include <mono/metadata/mempool-internals.h>
50 #include <mono/metadata/attach.h>
51 #include <mono/metadata/runtime.h>
52 #include <mono/utils/mono-math.h>
53 #include <mono/utils/mono-compiler.h>
54 #include <mono/utils/mono-counters.h>
55 #include <mono/utils/mono-logger-internal.h>
56 #include <mono/utils/mono-mmap.h>
57 #include <mono/utils/mono-tls.h>
58 #include <mono/utils/dtrace.h>
60 #include "mini.h"
61 #include "mini-llvm.h"
62 #include "tasklets.h"
63 #include <string.h>
64 #include <ctype.h>
65 #include "trace.h"
66 #include "version.h"
68 #include "jit-icalls.h"
70 #include "debug-mini.h"
71 #include "mini-gc.h"
72 #include "debugger-agent.h"
74 static gpointer mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt, MonoException **ex);
77 static guint32 default_opt = 0;
78 static gboolean default_opt_set = FALSE;
80 MonoNativeTlsKey mono_jit_tls_id;
82 #ifdef MONO_HAVE_FAST_TLS
83 MONO_FAST_TLS_DECLARE(mono_jit_tls);
84 #endif
86 #ifndef MONO_ARCH_MONITOR_ENTER_ADJUSTMENT
87 #define MONO_ARCH_MONITOR_ENTER_ADJUSTMENT 1
88 #endif
90 MonoTraceSpec *mono_jit_trace_calls = NULL;
91 gboolean mono_compile_aot = FALSE;
92 /* If this is set, no code is generated dynamically, everything is taken from AOT files */
93 gboolean mono_aot_only = FALSE;
94 /* Whenever to use IMT */
95 #ifdef MONO_ARCH_HAVE_IMT
96 gboolean mono_use_imt = TRUE;
97 #else
98 gboolean mono_use_imt = FALSE;
99 #endif
100 MonoMethodDesc *mono_inject_async_exc_method = NULL;
101 int mono_inject_async_exc_pos;
102 MonoMethodDesc *mono_break_at_bb_method = NULL;
103 int mono_break_at_bb_bb_num;
104 gboolean mono_do_x86_stack_align = TRUE;
105 const char *mono_build_date;
106 gboolean mono_do_signal_chaining;
107 static gboolean mono_using_xdebug;
108 static int mini_verbose = 0;
111 * This flag controls whenever the runtime uses LLVM for JIT compilation, and whenever
112 * it can load AOT code compiled by LLVM.
114 gboolean mono_use_llvm = FALSE;
116 #define mono_jit_lock() EnterCriticalSection (&jit_mutex)
117 #define mono_jit_unlock() LeaveCriticalSection (&jit_mutex)
118 static CRITICAL_SECTION jit_mutex;
120 static MonoCodeManager *global_codeman = NULL;
122 static GHashTable *jit_icall_name_hash = NULL;
124 static MonoDebugOptions debug_options;
126 #ifdef VALGRIND_JIT_REGISTER_MAP
127 static int valgrind_register = 0;
128 #endif
131 * Table written to by the debugger with a 1-based index into the
132 * mono_breakpoint_info table, which contains changes made to
133 * the JIT instructions by the debugger.
135 gssize
136 mono_breakpoint_info_index [MONO_BREAKPOINT_ARRAY_SIZE];
138 /* Whenever to check for pending exceptions in managed-to-native wrappers */
139 gboolean check_for_pending_exc = TRUE;
141 /* Whenever to disable passing/returning small valuetypes in registers for managed methods */
142 gboolean disable_vtypes_in_regs = FALSE;
144 gboolean mono_dont_free_global_codeman;
146 gpointer
147 mono_realloc_native_code (MonoCompile *cfg)
149 #if defined(__default_codegen__)
150 return g_realloc (cfg->native_code, cfg->code_size);
151 #elif defined(__native_client_codegen__)
152 guint old_padding;
153 gpointer native_code;
154 guint alignment_check;
156 /* Save the old alignment offset so we can re-align after the realloc. */
157 old_padding = (guint)(cfg->native_code - cfg->native_code_alloc);
159 cfg->native_code_alloc = g_realloc ( cfg->native_code_alloc,
160 cfg->code_size + kNaClAlignment );
162 /* Align native_code to next nearest kNaClAlignment byte. */
163 native_code = (guint)cfg->native_code_alloc + kNaClAlignment;
164 native_code = (guint)native_code & ~kNaClAlignmentMask;
166 /* Shift the data to be 32-byte aligned again. */
167 memmove (native_code, cfg->native_code_alloc + old_padding, cfg->code_size);
169 alignment_check = (guint)native_code & kNaClAlignmentMask;
170 g_assert (alignment_check == 0);
171 return native_code;
172 #else
173 g_assert_not_reached ();
174 return cfg->native_code;
175 #endif
178 #ifdef __native_client_codegen__
180 /* Prevent instructions from straddling a 32-byte alignment boundary. */
181 /* Instructions longer than 32 bytes must be aligned internally. */
182 /* IN: pcode, instlen */
183 /* OUT: pcode */
184 void mono_nacl_align_inst(guint8 **pcode, int instlen) {
185 int space_in_block;
187 space_in_block = kNaClAlignment - ((uintptr_t)(*pcode) & kNaClAlignmentMask);
189 if (G_UNLIKELY (instlen >= kNaClAlignment)) {
190 g_assert_not_reached();
191 } else if (instlen > space_in_block) {
192 *pcode = mono_arch_nacl_pad(*pcode, space_in_block);
196 /* Move emitted call sequence to the end of a kNaClAlignment-byte block. */
197 /* IN: start pointer to start of call sequence */
198 /* IN: pcode pointer to end of call sequence (current "IP") */
199 /* OUT: start pointer to the start of the call sequence after padding */
200 /* OUT: pcode pointer to the end of the call sequence after padding */
201 void mono_nacl_align_call(guint8 **start, guint8 **pcode) {
202 const size_t MAX_NACL_CALL_LENGTH = kNaClAlignment;
203 guint8 copy_of_call[MAX_NACL_CALL_LENGTH];
204 guint8 *temp;
206 const size_t length = (size_t)((*pcode)-(*start));
207 g_assert(length < MAX_NACL_CALL_LENGTH);
209 memcpy(copy_of_call, *start, length);
210 temp = mono_nacl_pad_call(*start, (guint8)length);
211 memcpy(temp, copy_of_call, length);
212 (*start) = temp;
213 (*pcode) = temp + length;
216 /* mono_nacl_pad_call(): Insert padding for Native Client call instructions */
217 /* code pointer to buffer for emitting code */
218 /* ilength length of call instruction */
219 guint8 *mono_nacl_pad_call(guint8 *code, guint8 ilength) {
220 int freeSpaceInBlock = kNaClAlignment - ((uintptr_t)code & kNaClAlignmentMask);
221 int padding = freeSpaceInBlock - ilength;
223 if (padding < 0) {
224 /* There isn't enough space in this block for the instruction. */
225 /* Fill this block and start a new one. */
226 code = mono_arch_nacl_pad(code, freeSpaceInBlock);
227 freeSpaceInBlock = kNaClAlignment;
228 padding = freeSpaceInBlock - ilength;
230 g_assert(ilength > 0);
231 g_assert(padding >= 0);
232 g_assert(padding < kNaClAlignment);
233 if (0 == padding) return code;
234 return mono_arch_nacl_pad(code, padding);
237 guint8 *mono_nacl_align(guint8 *code) {
238 int padding = kNaClAlignment - ((uintptr_t)code & kNaClAlignmentMask);
239 if (padding != kNaClAlignment) code = mono_arch_nacl_pad(code, padding);
240 return code;
243 void mono_nacl_fix_patches(const guint8 *code, MonoJumpInfo *ji)
245 MonoJumpInfo *patch_info;
246 for (patch_info = ji; patch_info; patch_info = patch_info->next) {
247 unsigned char *ip = patch_info->ip.i + code;
248 ip = mono_arch_nacl_skip_nops(ip);
249 patch_info->ip.i = ip - code;
252 #endif /* __native_client_codegen__ */
254 gboolean
255 mono_running_on_valgrind (void)
257 if (RUNNING_ON_VALGRIND){
258 #ifdef VALGRIND_JIT_REGISTER_MAP
259 valgrind_register = TRUE;
260 #endif
261 return TRUE;
262 } else
263 return FALSE;
266 typedef struct {
267 MonoExceptionClause *clause;
268 MonoBasicBlock *basic_block;
269 int start_offset;
270 } TryBlockHole;
272 typedef struct {
273 void *ip;
274 MonoMethod *method;
275 } FindTrampUserData;
277 static void
278 find_tramp (gpointer key, gpointer value, gpointer user_data)
280 FindTrampUserData *ud = (FindTrampUserData*)user_data;
282 if (value == ud->ip)
283 ud->method = (MonoMethod*)key;
286 /* debug function */
287 G_GNUC_UNUSED static char*
288 get_method_from_ip (void *ip)
290 MonoJitInfo *ji;
291 char *method;
292 char *res;
293 MonoDomain *domain = mono_domain_get ();
294 MonoDebugSourceLocation *location;
295 FindTrampUserData user_data;
297 ji = mono_jit_info_table_find (domain, ip);
298 if (!ji) {
299 user_data.ip = ip;
300 user_data.method = NULL;
301 mono_domain_lock (domain);
302 g_hash_table_foreach (domain_jit_info (domain)->jit_trampoline_hash, find_tramp, &user_data);
303 mono_domain_unlock (domain);
304 if (user_data.method) {
305 char *mname = mono_method_full_name (user_data.method, TRUE);
306 res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
307 g_free (mname);
308 return res;
310 else
311 return NULL;
313 method = mono_method_full_name (ji->method, TRUE);
314 /* FIXME: unused ? */
315 location = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
317 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);
319 mono_debug_free_source_location (location);
320 g_free (method);
322 return res;
325 /**
326 * mono_pmip:
327 * @ip: an instruction pointer address
329 * This method is used from a debugger to get the name of the
330 * method at address @ip. This routine is typically invoked from
331 * a debugger like this:
333 * (gdb) print mono_pmip ($pc)
335 * Returns: the name of the method at address @ip.
337 G_GNUC_UNUSED char *
338 mono_pmip (void *ip)
340 return get_method_from_ip (ip);
343 /**
344 * mono_print_method_from_ip
345 * @ip: an instruction pointer address
347 * This method is used from a debugger to get the name of the
348 * method at address @ip.
350 * This prints the name of the method at address @ip in the standard
351 * output. Unlike mono_pmip which returns a string, this routine
352 * prints the value on the standard output.
354 #ifdef __GNUC__
355 /* Prevent the linker from optimizing this away in embedding setups to help debugging */
356 __attribute__((used))
357 #endif
358 void
359 mono_print_method_from_ip (void *ip)
361 MonoJitInfo *ji;
362 char *method;
363 MonoDebugSourceLocation *source;
364 MonoDomain *domain = mono_domain_get ();
365 MonoDomain *target_domain = mono_domain_get ();
366 FindTrampUserData user_data;
368 ji = mini_jit_info_table_find (domain, ip, &target_domain);
369 if (!ji) {
370 user_data.ip = ip;
371 user_data.method = NULL;
372 mono_domain_lock (domain);
373 g_hash_table_foreach (domain_jit_info (domain)->jit_trampoline_hash, find_tramp, &user_data);
374 mono_domain_unlock (domain);
375 if (user_data.method) {
376 char *mname = mono_method_full_name (user_data.method, TRUE);
377 printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
378 g_free (mname);
380 else
381 g_print ("No method at %p\n", ip);
382 fflush (stdout);
383 return;
385 method = mono_method_full_name (ji->method, TRUE);
386 source = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), target_domain);
388 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);
390 if (source)
391 g_print ("%s:%d\n", source->source_file, source->row);
392 fflush (stdout);
394 mono_debug_free_source_location (source);
395 g_free (method);
399 * mono_method_same_domain:
401 * Determine whenever two compiled methods are in the same domain, thus
402 * the address of the callee can be embedded in the caller.
404 gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
406 if (!caller || !callee)
407 return FALSE;
410 * If the call was made from domain-neutral to domain-specific
411 * code, we can't patch the call site.
413 if (caller->domain_neutral && !callee->domain_neutral)
414 return FALSE;
416 if ((caller->method->klass == mono_defaults.appdomain_class) &&
417 (strstr (caller->method->name, "InvokeInDomain"))) {
418 /* The InvokeInDomain methods change the current appdomain */
419 return FALSE;
422 return TRUE;
426 * mono_global_codeman_reserve:
428 * Allocate code memory from the global code manager.
430 void *mono_global_codeman_reserve (int size)
432 void *ptr;
434 if (mono_aot_only)
435 g_error ("Attempting to allocate from the global code manager while running with --aot-only.\n");
437 if (!global_codeman) {
438 /* This can happen during startup */
439 global_codeman = mono_code_manager_new ();
440 return mono_code_manager_reserve (global_codeman, size);
442 else {
443 mono_jit_lock ();
444 ptr = mono_code_manager_reserve (global_codeman, size);
445 mono_jit_unlock ();
446 return ptr;
450 #if defined(__native_client_codegen__) && defined(__native_client__)
451 /* Given the temporary buffer (allocated by mono_global_codeman_reserve) into
452 * which we are generating code, return a pointer to the destination in the
453 * dynamic code segment into which the code will be copied when
454 * mono_global_codeman_commit is called.
455 * LOCKING: Acquires the jit lock.
457 void*
458 nacl_global_codeman_get_dest (void *data)
460 void *dest;
461 mono_jit_lock ();
462 dest = nacl_code_manager_get_code_dest (global_codeman, data);
463 mono_jit_unlock ();
464 return dest;
467 void
468 mono_global_codeman_commit (void *data, int size, int newsize)
470 mono_jit_lock ();
471 mono_code_manager_commit (global_codeman, data, size, newsize);
472 mono_jit_unlock ();
476 * Convenience function which calls mono_global_codeman_commit to validate and
477 * copy the code. The caller sets *buf_base and *buf_size to the start and size
478 * of the buffer (allocated by mono_global_codeman_reserve), and *code_end to
479 * the byte after the last instruction byte. On return, *buf_base will point to
480 * the start of the copied in the code segment, and *code_end will point after
481 * the end of the copied code.
483 void
484 nacl_global_codeman_validate (guint8 **buf_base, int buf_size, guint8 **code_end)
486 guint8 *tmp = nacl_global_codeman_get_dest (*buf_base);
487 mono_global_codeman_commit (*buf_base, buf_size, *code_end - *buf_base);
488 *code_end = tmp + (*code_end - *buf_base);
489 *buf_base = tmp;
491 #else
492 /* no-op versions of Native Client functions */
493 void*
494 nacl_global_codeman_get_dest (void *data)
496 return data;
499 void
500 mono_global_codeman_commit (void *data, int size, int newsize)
504 void
505 nacl_global_codeman_validate (guint8 **buf_base, int buf_size, guint8 **code_end)
509 #endif /* __native_client__ */
512 * mono_create_unwind_op:
514 * Create an unwind op with the given parameters.
516 MonoUnwindOp*
517 mono_create_unwind_op (int when, int tag, int reg, int val)
519 MonoUnwindOp *op = g_new0 (MonoUnwindOp, 1);
521 op->op = tag;
522 op->reg = reg;
523 op->val = val;
524 op->when = when;
526 return op;
530 * mono_emit_unwind_op:
532 * Add an unwind op with the given parameters for the list of unwind ops stored in
533 * cfg->unwind_ops.
535 void
536 mono_emit_unwind_op (MonoCompile *cfg, int when, int tag, int reg, int val)
538 MonoUnwindOp *op = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoUnwindOp));
540 op->op = tag;
541 op->reg = reg;
542 op->val = val;
543 op->when = when;
545 cfg->unwind_ops = g_slist_append_mempool (cfg->mempool, cfg->unwind_ops, op);
548 MonoJumpInfoToken *
549 mono_jump_info_token_new2 (MonoMemPool *mp, MonoImage *image, guint32 token, MonoGenericContext *context)
551 MonoJumpInfoToken *res = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
552 res->image = image;
553 res->token = token;
554 res->has_context = context != NULL;
555 if (context)
556 memcpy (&res->context, context, sizeof (MonoGenericContext));
558 return res;
561 MonoJumpInfoToken *
562 mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
564 return mono_jump_info_token_new2 (mp, image, token, NULL);
568 * mono_tramp_info_create:
570 * Create a MonoTrampInfo structure from the arguments. This function assumes ownership
571 * of NAME, JI, and UNWIND_OPS.
573 MonoTrampInfo*
574 mono_tramp_info_create (const char *name, guint8 *code, guint32 code_size, MonoJumpInfo *ji, GSList *unwind_ops)
576 MonoTrampInfo *info = g_new0 (MonoTrampInfo, 1);
578 info->name = (char*)name;
579 info->code = code;
580 info->code_size = code_size;
581 info->ji = ji;
582 info->unwind_ops = unwind_ops;
584 return info;
587 void
588 mono_tramp_info_free (MonoTrampInfo *info)
590 GSList *l;
592 g_free (info->name);
594 // FIXME: ji
595 for (l = info->unwind_ops; l; l = l->next)
596 g_free (l->data);
597 g_slist_free (info->unwind_ops);
598 g_free (info);
601 #define MONO_INIT_VARINFO(vi,id) do { \
602 (vi)->range.first_use.pos.bid = 0xffff; \
603 (vi)->reg = -1; \
604 (vi)->idx = (id); \
605 } while (0)
608 * mono_unlink_bblock:
610 * Unlink two basic blocks.
612 void
613 mono_unlink_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
615 int i, pos;
616 gboolean found;
618 found = FALSE;
619 for (i = 0; i < from->out_count; ++i) {
620 if (to == from->out_bb [i]) {
621 found = TRUE;
622 break;
625 if (found) {
626 pos = 0;
627 for (i = 0; i < from->out_count; ++i) {
628 if (from->out_bb [i] != to)
629 from->out_bb [pos ++] = from->out_bb [i];
631 g_assert (pos == from->out_count - 1);
632 from->out_count--;
635 found = FALSE;
636 for (i = 0; i < to->in_count; ++i) {
637 if (from == to->in_bb [i]) {
638 found = TRUE;
639 break;
642 if (found) {
643 pos = 0;
644 for (i = 0; i < to->in_count; ++i) {
645 if (to->in_bb [i] != from)
646 to->in_bb [pos ++] = to->in_bb [i];
648 g_assert (pos == to->in_count - 1);
649 to->in_count--;
654 * mono_bblocks_linked:
656 * Return whenever BB1 and BB2 are linked in the CFG.
658 gboolean
659 mono_bblocks_linked (MonoBasicBlock *bb1, MonoBasicBlock *bb2)
661 int i;
663 for (i = 0; i < bb1->out_count; ++i) {
664 if (bb1->out_bb [i] == bb2)
665 return TRUE;
668 return FALSE;
671 static int
672 mono_find_block_region_notry (MonoCompile *cfg, int offset)
674 MonoMethodHeader *header = cfg->header;
675 MonoExceptionClause *clause;
676 int i;
678 for (i = 0; i < header->num_clauses; ++i) {
679 clause = &header->clauses [i];
680 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
681 (offset < (clause->handler_offset)))
682 return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
684 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
685 if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
686 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
687 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
688 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
689 else
690 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
694 return -1;
698 * mono_get_block_region_notry:
700 * Return the region corresponding to REGION, ignoring try clauses nested inside
701 * finally clauses.
704 mono_get_block_region_notry (MonoCompile *cfg, int region)
706 if ((region & (0xf << 4)) == MONO_REGION_TRY) {
707 MonoMethodHeader *header = cfg->header;
710 * This can happen if a try clause is nested inside a finally clause.
712 int clause_index = (region >> 8) - 1;
713 g_assert (clause_index >= 0 && clause_index < header->num_clauses);
715 region = mono_find_block_region_notry (cfg, header->clauses [clause_index].try_offset);
718 return region;
721 MonoInst *
722 mono_find_spvar_for_region (MonoCompile *cfg, int region)
724 region = mono_get_block_region_notry (cfg, region);
726 return g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
729 static void
730 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
732 int i;
734 array [*dfn] = start;
735 /* g_print ("visit %d at %p (BB%ld)\n", *dfn, start->cil_code, start->block_num); */
736 for (i = 0; i < start->out_count; ++i) {
737 if (start->out_bb [i]->dfn)
738 continue;
739 (*dfn)++;
740 start->out_bb [i]->dfn = *dfn;
741 start->out_bb [i]->df_parent = start;
742 array [*dfn] = start->out_bb [i];
743 df_visit (start->out_bb [i], dfn, array);
747 guint32
748 mono_reverse_branch_op (guint32 opcode)
750 static const int reverse_map [] = {
751 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
752 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
754 static const int reverse_fmap [] = {
755 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
756 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
758 static const int reverse_lmap [] = {
759 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
760 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
762 static const int reverse_imap [] = {
763 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
764 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
767 if (opcode >= CEE_BEQ && opcode <= CEE_BLT_UN) {
768 opcode = reverse_map [opcode - CEE_BEQ];
769 } else if (opcode >= OP_FBEQ && opcode <= OP_FBLT_UN) {
770 opcode = reverse_fmap [opcode - OP_FBEQ];
771 } else if (opcode >= OP_LBEQ && opcode <= OP_LBLT_UN) {
772 opcode = reverse_lmap [opcode - OP_LBEQ];
773 } else if (opcode >= OP_IBEQ && opcode <= OP_IBLT_UN) {
774 opcode = reverse_imap [opcode - OP_IBEQ];
775 } else
776 g_assert_not_reached ();
778 return opcode;
781 guint
782 mono_type_to_store_membase (MonoCompile *cfg, MonoType *type)
784 if (type->byref)
785 return OP_STORE_MEMBASE_REG;
787 handle_enum:
788 switch (type->type) {
789 case MONO_TYPE_I1:
790 case MONO_TYPE_U1:
791 case MONO_TYPE_BOOLEAN:
792 return OP_STOREI1_MEMBASE_REG;
793 case MONO_TYPE_I2:
794 case MONO_TYPE_U2:
795 case MONO_TYPE_CHAR:
796 return OP_STOREI2_MEMBASE_REG;
797 case MONO_TYPE_I4:
798 case MONO_TYPE_U4:
799 return OP_STOREI4_MEMBASE_REG;
800 case MONO_TYPE_I:
801 case MONO_TYPE_U:
802 case MONO_TYPE_PTR:
803 case MONO_TYPE_FNPTR:
804 return OP_STORE_MEMBASE_REG;
805 case MONO_TYPE_CLASS:
806 case MONO_TYPE_STRING:
807 case MONO_TYPE_OBJECT:
808 case MONO_TYPE_SZARRAY:
809 case MONO_TYPE_ARRAY:
810 return OP_STORE_MEMBASE_REG;
811 case MONO_TYPE_I8:
812 case MONO_TYPE_U8:
813 return OP_STOREI8_MEMBASE_REG;
814 case MONO_TYPE_R4:
815 return OP_STORER4_MEMBASE_REG;
816 case MONO_TYPE_R8:
817 return OP_STORER8_MEMBASE_REG;
818 case MONO_TYPE_VALUETYPE:
819 if (type->data.klass->enumtype) {
820 type = mono_class_enum_basetype (type->data.klass);
821 goto handle_enum;
823 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
824 return OP_STOREX_MEMBASE;
825 return OP_STOREV_MEMBASE;
826 case MONO_TYPE_TYPEDBYREF:
827 return OP_STOREV_MEMBASE;
828 case MONO_TYPE_GENERICINST:
829 type = &type->data.generic_class->container_class->byval_arg;
830 goto handle_enum;
831 case MONO_TYPE_VAR:
832 case MONO_TYPE_MVAR:
833 /* FIXME: all the arguments must be references for now,
834 * later look inside cfg and see if the arg num is
835 * really a reference
837 g_assert (cfg->generic_sharing_context);
838 return OP_STORE_MEMBASE_REG;
839 default:
840 g_error ("unknown type 0x%02x in type_to_store_membase", type->type);
842 return -1;
845 guint
846 mono_type_to_load_membase (MonoCompile *cfg, MonoType *type)
848 if (type->byref)
849 return OP_LOAD_MEMBASE;
851 type = mono_type_get_underlying_type (type);
853 switch (type->type) {
854 case MONO_TYPE_I1:
855 return OP_LOADI1_MEMBASE;
856 case MONO_TYPE_U1:
857 case MONO_TYPE_BOOLEAN:
858 return OP_LOADU1_MEMBASE;
859 case MONO_TYPE_I2:
860 return OP_LOADI2_MEMBASE;
861 case MONO_TYPE_U2:
862 case MONO_TYPE_CHAR:
863 return OP_LOADU2_MEMBASE;
864 case MONO_TYPE_I4:
865 return OP_LOADI4_MEMBASE;
866 case MONO_TYPE_U4:
867 return OP_LOADU4_MEMBASE;
868 case MONO_TYPE_I:
869 case MONO_TYPE_U:
870 case MONO_TYPE_PTR:
871 case MONO_TYPE_FNPTR:
872 return OP_LOAD_MEMBASE;
873 case MONO_TYPE_CLASS:
874 case MONO_TYPE_STRING:
875 case MONO_TYPE_OBJECT:
876 case MONO_TYPE_SZARRAY:
877 case MONO_TYPE_ARRAY:
878 return OP_LOAD_MEMBASE;
879 case MONO_TYPE_I8:
880 case MONO_TYPE_U8:
881 return OP_LOADI8_MEMBASE;
882 case MONO_TYPE_R4:
883 return OP_LOADR4_MEMBASE;
884 case MONO_TYPE_R8:
885 return OP_LOADR8_MEMBASE;
886 case MONO_TYPE_VALUETYPE:
887 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (type)))
888 return OP_LOADX_MEMBASE;
889 case MONO_TYPE_TYPEDBYREF:
890 return OP_LOADV_MEMBASE;
891 case MONO_TYPE_GENERICINST:
892 if (mono_type_generic_inst_is_valuetype (type))
893 return OP_LOADV_MEMBASE;
894 else
895 return OP_LOAD_MEMBASE;
896 break;
897 case MONO_TYPE_VAR:
898 case MONO_TYPE_MVAR:
899 /* FIXME: all the arguments must be references for now,
900 * later look inside cfg and see if the arg num is
901 * really a reference
903 g_assert (cfg->generic_sharing_context);
904 return OP_LOAD_MEMBASE;
905 default:
906 g_error ("unknown type 0x%02x in type_to_load_membase", type->type);
908 return -1;
911 static guint
912 mini_type_to_ldind (MonoCompile* cfg, MonoType *type)
914 if (cfg->generic_sharing_context && !type->byref) {
915 /* FIXME: all the arguments must be references for now,
916 * later look inside cfg and see if the arg num is
917 * really a reference
919 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
920 return CEE_LDIND_REF;
922 return mono_type_to_ldind (type);
925 guint
926 mini_type_to_stind (MonoCompile* cfg, MonoType *type)
928 if (cfg->generic_sharing_context && !type->byref) {
929 /* FIXME: all the arguments must be references for now,
930 * later look inside cfg and see if the arg num is
931 * really a reference
933 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
934 return CEE_STIND_REF;
936 return mono_type_to_stind (type);
940 mono_op_imm_to_op (int opcode)
942 switch (opcode) {
943 case OP_ADD_IMM:
944 #if SIZEOF_REGISTER == 4
945 return OP_IADD;
946 #else
947 return OP_LADD;
948 #endif
949 case OP_IADD_IMM:
950 return OP_IADD;
951 case OP_LADD_IMM:
952 return OP_LADD;
953 case OP_ISUB_IMM:
954 return OP_ISUB;
955 case OP_LSUB_IMM:
956 return OP_LSUB;
957 case OP_IMUL_IMM:
958 return OP_IMUL;
959 case OP_AND_IMM:
960 #if SIZEOF_REGISTER == 4
961 return OP_IAND;
962 #else
963 return OP_LAND;
964 #endif
965 case OP_OR_IMM:
966 #if SIZEOF_REGISTER == 4
967 return OP_IOR;
968 #else
969 return OP_LOR;
970 #endif
971 case OP_XOR_IMM:
972 #if SIZEOF_REGISTER == 4
973 return OP_IXOR;
974 #else
975 return OP_LXOR;
976 #endif
977 case OP_IAND_IMM:
978 return OP_IAND;
979 case OP_LAND_IMM:
980 return OP_LAND;
981 case OP_IOR_IMM:
982 return OP_IOR;
983 case OP_LOR_IMM:
984 return OP_LOR;
985 case OP_IXOR_IMM:
986 return OP_IXOR;
987 case OP_LXOR_IMM:
988 return OP_LXOR;
989 case OP_ISHL_IMM:
990 return OP_ISHL;
991 case OP_LSHL_IMM:
992 return OP_LSHL;
993 case OP_ISHR_IMM:
994 return OP_ISHR;
995 case OP_LSHR_IMM:
996 return OP_LSHR;
997 case OP_ISHR_UN_IMM:
998 return OP_ISHR_UN;
999 case OP_LSHR_UN_IMM:
1000 return OP_LSHR_UN;
1001 case OP_IDIV_IMM:
1002 return OP_IDIV;
1003 case OP_IDIV_UN_IMM:
1004 return OP_IDIV_UN;
1005 case OP_IREM_UN_IMM:
1006 return OP_IREM_UN;
1007 case OP_IREM_IMM:
1008 return OP_IREM;
1009 case OP_DIV_IMM:
1010 #if SIZEOF_REGISTER == 4
1011 return OP_IDIV;
1012 #else
1013 return OP_LDIV;
1014 #endif
1015 case OP_REM_IMM:
1016 #if SIZEOF_REGISTER == 4
1017 return OP_IREM;
1018 #else
1019 return OP_LREM;
1020 #endif
1021 case OP_ADDCC_IMM:
1022 return OP_ADDCC;
1023 case OP_ADC_IMM:
1024 return OP_ADC;
1025 case OP_SUBCC_IMM:
1026 return OP_SUBCC;
1027 case OP_SBB_IMM:
1028 return OP_SBB;
1029 case OP_IADC_IMM:
1030 return OP_IADC;
1031 case OP_ISBB_IMM:
1032 return OP_ISBB;
1033 case OP_COMPARE_IMM:
1034 return OP_COMPARE;
1035 case OP_ICOMPARE_IMM:
1036 return OP_ICOMPARE;
1037 case OP_LOCALLOC_IMM:
1038 return OP_LOCALLOC;
1039 default:
1040 printf ("%s\n", mono_inst_name (opcode));
1041 g_assert_not_reached ();
1042 return -1;
1047 * mono_decompose_op_imm:
1049 * Replace the OP_.._IMM INS with its non IMM variant.
1051 void
1052 mono_decompose_op_imm (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins)
1054 MonoInst *temp;
1056 MONO_INST_NEW (cfg, temp, OP_ICONST);
1057 temp->inst_c0 = ins->inst_imm;
1058 temp->dreg = mono_alloc_ireg (cfg);
1059 mono_bblock_insert_before_ins (bb, ins, temp);
1060 ins->opcode = mono_op_imm_to_op (ins->opcode);
1061 if (ins->opcode == OP_LOCALLOC)
1062 ins->sreg1 = temp->dreg;
1063 else
1064 ins->sreg2 = temp->dreg;
1066 bb->max_vreg = MAX (bb->max_vreg, cfg->next_vreg);
1069 static void
1070 set_vreg_to_inst (MonoCompile *cfg, int vreg, MonoInst *inst)
1072 if (vreg >= cfg->vreg_to_inst_len) {
1073 MonoInst **tmp = cfg->vreg_to_inst;
1074 int size = cfg->vreg_to_inst_len;
1076 while (vreg >= cfg->vreg_to_inst_len)
1077 cfg->vreg_to_inst_len = cfg->vreg_to_inst_len ? cfg->vreg_to_inst_len * 2 : 32;
1078 cfg->vreg_to_inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * cfg->vreg_to_inst_len);
1079 if (size)
1080 memcpy (cfg->vreg_to_inst, tmp, size * sizeof (MonoInst*));
1082 cfg->vreg_to_inst [vreg] = inst;
1085 #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)))
1086 #define mono_type_is_float(type) (!(type)->byref && (((type)->type == MONO_TYPE_R8) || ((type)->type == MONO_TYPE_R4)))
1088 #ifdef DISABLE_JIT
1090 MonoInst*
1091 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1093 return NULL;
1096 #else
1098 MonoInst*
1099 mono_compile_create_var_for_vreg (MonoCompile *cfg, MonoType *type, int opcode, int vreg)
1101 MonoInst *inst;
1102 int num = cfg->num_varinfo;
1103 gboolean regpair;
1105 if ((num + 1) >= cfg->varinfo_count) {
1106 int orig_count = cfg->varinfo_count;
1107 cfg->varinfo_count = cfg->varinfo_count ? (cfg->varinfo_count * 2) : 64;
1108 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
1109 cfg->vars = (MonoMethodVar *)g_realloc (cfg->vars, sizeof (MonoMethodVar) * cfg->varinfo_count);
1110 memset (&cfg->vars [orig_count], 0, (cfg->varinfo_count - orig_count) * sizeof (MonoMethodVar));
1113 cfg->stat_allocate_var++;
1115 MONO_INST_NEW (cfg, inst, opcode);
1116 inst->inst_c0 = num;
1117 inst->inst_vtype = type;
1118 inst->klass = mono_class_from_mono_type (type);
1119 type_to_eval_stack_type (cfg, type, inst);
1120 /* if set to 1 the variable is native */
1121 inst->backend.is_pinvoke = 0;
1122 inst->dreg = vreg;
1124 if (cfg->compute_gc_maps) {
1125 if (type->byref) {
1126 mono_mark_vreg_as_mp (cfg, vreg);
1127 } else {
1128 MonoType *t = mini_type_get_underlying_type (NULL, type);
1129 if ((MONO_TYPE_ISSTRUCT (t) && inst->klass->has_references) || mini_type_is_reference (cfg, t)) {
1130 inst->flags |= MONO_INST_GC_TRACK;
1131 mono_mark_vreg_as_ref (cfg, vreg);
1136 cfg->varinfo [num] = inst;
1138 MONO_INIT_VARINFO (&cfg->vars [num], num);
1139 MONO_VARINFO (cfg, num)->vreg = vreg;
1141 if (vreg != -1)
1142 set_vreg_to_inst (cfg, vreg, inst);
1144 #if SIZEOF_REGISTER == 4
1145 #ifdef MONO_ARCH_SOFT_FLOAT
1146 regpair = mono_type_is_long (type) || mono_type_is_float (type);
1147 #else
1148 regpair = mono_type_is_long (type);
1149 #endif
1150 #else
1151 regpair = FALSE;
1152 #endif
1154 if (regpair) {
1155 MonoInst *tree;
1158 * These two cannot be allocated using create_var_for_vreg since that would
1159 * put it into the cfg->varinfo array, confusing many parts of the JIT.
1163 * Set flags to VOLATILE so SSA skips it.
1166 if (cfg->verbose_level >= 4) {
1167 printf (" Create LVAR R%d (R%d, R%d)\n", inst->dreg, inst->dreg + 1, inst->dreg + 2);
1170 #ifdef MONO_ARCH_SOFT_FLOAT
1171 if (cfg->opt & MONO_OPT_SSA) {
1172 if (mono_type_is_float (type))
1173 inst->flags = MONO_INST_VOLATILE;
1175 #endif
1177 /* Allocate a dummy MonoInst for the first vreg */
1178 MONO_INST_NEW (cfg, tree, OP_LOCAL);
1179 tree->dreg = inst->dreg + 1;
1180 if (cfg->opt & MONO_OPT_SSA)
1181 tree->flags = MONO_INST_VOLATILE;
1182 tree->inst_c0 = num;
1183 tree->type = STACK_I4;
1184 tree->inst_vtype = &mono_defaults.int32_class->byval_arg;
1185 tree->klass = mono_class_from_mono_type (tree->inst_vtype);
1187 set_vreg_to_inst (cfg, inst->dreg + 1, tree);
1189 /* Allocate a dummy MonoInst for the second vreg */
1190 MONO_INST_NEW (cfg, tree, OP_LOCAL);
1191 tree->dreg = inst->dreg + 2;
1192 if (cfg->opt & MONO_OPT_SSA)
1193 tree->flags = MONO_INST_VOLATILE;
1194 tree->inst_c0 = num;
1195 tree->type = STACK_I4;
1196 tree->inst_vtype = &mono_defaults.int32_class->byval_arg;
1197 tree->klass = mono_class_from_mono_type (tree->inst_vtype);
1199 set_vreg_to_inst (cfg, inst->dreg + 2, tree);
1202 cfg->num_varinfo++;
1203 if (cfg->verbose_level > 2)
1204 g_print ("created temp %d (R%d) of type %s\n", num, vreg, mono_type_get_name (type));
1205 return inst;
1208 MonoInst*
1209 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1211 int dreg;
1213 if (mono_type_is_long (type))
1214 dreg = mono_alloc_dreg (cfg, STACK_I8);
1215 #ifdef MONO_ARCH_SOFT_FLOAT
1216 else if (mono_type_is_float (type))
1217 dreg = mono_alloc_dreg (cfg, STACK_R8);
1218 #endif
1219 else
1220 /* All the others are unified */
1221 dreg = mono_alloc_preg (cfg);
1223 return mono_compile_create_var_for_vreg (cfg, type, opcode, dreg);
1227 * Transform a MonoInst into a load from the variable of index var_index.
1229 void
1230 mono_compile_make_var_load (MonoCompile *cfg, MonoInst *dest, gssize var_index) {
1231 memset (dest, 0, sizeof (MonoInst));
1232 dest->inst_i0 = cfg->varinfo [var_index];
1233 dest->opcode = mini_type_to_ldind (cfg, dest->inst_i0->inst_vtype);
1234 type_to_eval_stack_type (cfg, dest->inst_i0->inst_vtype, dest);
1235 dest->klass = dest->inst_i0->klass;
1238 #endif
1240 void
1241 mono_mark_vreg_as_ref (MonoCompile *cfg, int vreg)
1243 if (vreg >= cfg->vreg_is_ref_len) {
1244 gboolean *tmp = cfg->vreg_is_ref;
1245 int size = cfg->vreg_is_ref_len;
1247 while (vreg >= cfg->vreg_is_ref_len)
1248 cfg->vreg_is_ref_len = cfg->vreg_is_ref_len ? cfg->vreg_is_ref_len * 2 : 32;
1249 cfg->vreg_is_ref = mono_mempool_alloc0 (cfg->mempool, sizeof (gboolean) * cfg->vreg_is_ref_len);
1250 if (size)
1251 memcpy (cfg->vreg_is_ref, tmp, size * sizeof (gboolean));
1253 cfg->vreg_is_ref [vreg] = TRUE;
1256 void
1257 mono_mark_vreg_as_mp (MonoCompile *cfg, int vreg)
1259 if (vreg >= cfg->vreg_is_mp_len) {
1260 gboolean *tmp = cfg->vreg_is_mp;
1261 int size = cfg->vreg_is_mp_len;
1263 while (vreg >= cfg->vreg_is_mp_len)
1264 cfg->vreg_is_mp_len = cfg->vreg_is_mp_len ? cfg->vreg_is_mp_len * 2 : 32;
1265 cfg->vreg_is_mp = mono_mempool_alloc0 (cfg->mempool, sizeof (gboolean) * cfg->vreg_is_mp_len);
1266 if (size)
1267 memcpy (cfg->vreg_is_mp, tmp, size * sizeof (gboolean));
1269 cfg->vreg_is_mp [vreg] = TRUE;
1272 static MonoType*
1273 type_from_stack_type (MonoInst *ins) {
1274 switch (ins->type) {
1275 case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1276 case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1277 case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1278 case STACK_R8: return &mono_defaults.double_class->byval_arg;
1279 case STACK_MP:
1281 * this if used to be commented without any specific reason, but
1282 * it breaks #80235 when commented
1284 if (ins->klass)
1285 return &ins->klass->this_arg;
1286 else
1287 return &mono_defaults.object_class->this_arg;
1288 case STACK_OBJ:
1289 /* ins->klass may not be set for ldnull.
1290 * Also, if we have a boxed valuetype, we want an object lass,
1291 * not the valuetype class
1293 if (ins->klass && !ins->klass->valuetype)
1294 return &ins->klass->byval_arg;
1295 return &mono_defaults.object_class->byval_arg;
1296 case STACK_VTYPE: return &ins->klass->byval_arg;
1297 default:
1298 g_error ("stack type %d to montype not handled\n", ins->type);
1300 return NULL;
1303 MonoType*
1304 mono_type_from_stack_type (MonoInst *ins) {
1305 return type_from_stack_type (ins);
1309 * mono_add_ins_to_end:
1311 * Same as MONO_ADD_INS, but add INST before any branches at the end of BB.
1313 void
1314 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
1316 int opcode;
1318 if (!bb->code) {
1319 MONO_ADD_INS (bb, inst);
1320 return;
1323 switch (bb->last_ins->opcode) {
1324 case OP_BR:
1325 case OP_BR_REG:
1326 case CEE_BEQ:
1327 case CEE_BGE:
1328 case CEE_BGT:
1329 case CEE_BLE:
1330 case CEE_BLT:
1331 case CEE_BNE_UN:
1332 case CEE_BGE_UN:
1333 case CEE_BGT_UN:
1334 case CEE_BLE_UN:
1335 case CEE_BLT_UN:
1336 case OP_SWITCH:
1337 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
1338 break;
1339 default:
1340 if (MONO_IS_COND_BRANCH_OP (bb->last_ins)) {
1341 /* Need to insert the ins before the compare */
1342 if (bb->code == bb->last_ins) {
1343 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
1344 return;
1347 if (bb->code->next == bb->last_ins) {
1348 /* Only two instructions */
1349 opcode = bb->code->opcode;
1351 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)) {
1352 /* NEW IR */
1353 mono_bblock_insert_before_ins (bb, bb->code, inst);
1354 } else {
1355 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
1357 } else {
1358 opcode = bb->last_ins->prev->opcode;
1360 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)) {
1361 /* NEW IR */
1362 mono_bblock_insert_before_ins (bb, bb->last_ins->prev, inst);
1363 } else {
1364 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
1368 else
1369 MONO_ADD_INS (bb, inst);
1370 break;
1374 void
1375 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
1377 MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
1378 MonoJumpInfoBBTable *table;
1380 table = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
1381 table->table = bbs;
1382 table->table_size = num_blocks;
1384 ji->ip.label = label;
1385 ji->type = MONO_PATCH_INFO_SWITCH;
1386 ji->data.table = table;
1387 ji->next = cfg->patch_info;
1388 cfg->patch_info = ji;
1391 static MonoMethodSignature *
1392 mono_get_array_new_va_signature (int arity)
1394 static GHashTable *sighash = NULL;
1395 MonoMethodSignature *res;
1396 int i;
1398 mono_jit_lock ();
1399 if (!sighash) {
1400 sighash = g_hash_table_new (NULL, NULL);
1402 else if ((res = g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
1403 mono_jit_unlock ();
1404 return res;
1407 res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
1409 res->pinvoke = 1;
1410 #ifdef MONO_ARCH_VARARG_ICALLS
1411 /* Only set this only some archs since not all backends can handle varargs+pinvoke */
1412 res->call_convention = MONO_CALL_VARARG;
1413 #endif
1415 #ifdef TARGET_WIN32
1416 res->call_convention = MONO_CALL_C;
1417 #endif
1419 res->params [0] = &mono_defaults.int_class->byval_arg;
1420 for (i = 0; i < arity; i++)
1421 res->params [i + 1] = &mono_defaults.int_class->byval_arg;
1423 res->ret = &mono_defaults.object_class->byval_arg;
1425 g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
1426 mono_jit_unlock ();
1428 return res;
1431 MonoJitICallInfo *
1432 mono_get_array_new_va_icall (int rank)
1434 MonoMethodSignature *esig;
1435 char icall_name [256];
1436 char *name;
1437 MonoJitICallInfo *info;
1439 /* Need to register the icall so it gets an icall wrapper */
1440 sprintf (icall_name, "ves_array_new_va_%d", rank);
1442 mono_jit_lock ();
1443 info = mono_find_jit_icall_by_name (icall_name);
1444 if (info == NULL) {
1445 esig = mono_get_array_new_va_signature (rank);
1446 name = g_strdup (icall_name);
1447 info = mono_register_jit_icall (mono_array_new_va, name, esig, FALSE);
1449 g_hash_table_insert (jit_icall_name_hash, name, name);
1451 mono_jit_unlock ();
1453 return info;
1456 gboolean
1457 mini_class_is_system_array (MonoClass *klass)
1459 if (klass->parent == mono_defaults.array_class)
1460 return TRUE;
1461 else
1462 return FALSE;
1465 gboolean
1466 mini_assembly_can_skip_verification (MonoDomain *domain, MonoMethod *method)
1468 MonoAssembly *assembly = method->klass->image->assembly;
1469 if (method->wrapper_type != MONO_WRAPPER_NONE && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
1470 return FALSE;
1471 if (assembly->in_gac || assembly->image == mono_defaults.corlib)
1472 return FALSE;
1473 if (mono_security_get_mode () != MONO_SECURITY_MODE_NONE)
1474 return FALSE;
1475 return mono_assembly_has_skip_verification (assembly);
1479 * mini_method_verify:
1481 * Verify the method using the new verfier.
1483 * Returns true if the method is invalid.
1485 static gboolean
1486 mini_method_verify (MonoCompile *cfg, MonoMethod *method, gboolean fail_compile)
1488 GSList *tmp, *res;
1489 gboolean is_fulltrust;
1490 MonoLoaderError *error;
1492 if (method->verification_success)
1493 return FALSE;
1495 if (!mono_verifier_is_enabled_for_method (method))
1496 return FALSE;
1498 /*skip verification implies the assembly must be */
1499 is_fulltrust = mono_verifier_is_method_full_trust (method) || mini_assembly_can_skip_verification (cfg->domain, method);
1501 res = mono_method_verify_with_current_settings (method, cfg->skip_visibility, is_fulltrust);
1503 if ((error = mono_loader_get_last_error ())) {
1504 if (fail_compile)
1505 cfg->exception_type = error->exception_type;
1506 else
1507 mono_loader_clear_error ();
1508 if (res)
1509 mono_free_verify_list (res);
1510 return TRUE;
1513 if (res) {
1514 for (tmp = res; tmp; tmp = tmp->next) {
1515 MonoVerifyInfoExtended *info = (MonoVerifyInfoExtended *)tmp->data;
1516 if (info->info.status == MONO_VERIFY_ERROR) {
1517 if (fail_compile) {
1518 char *method_name = mono_method_full_name (method, TRUE);
1519 cfg->exception_type = info->exception_type;
1520 cfg->exception_message = g_strdup_printf ("Error verifying %s: %s", method_name, info->info.message);
1521 g_free (method_name);
1523 mono_free_verify_list (res);
1524 return TRUE;
1526 if (info->info.status == MONO_VERIFY_NOT_VERIFIABLE && (!is_fulltrust || info->exception_type == MONO_EXCEPTION_METHOD_ACCESS || info->exception_type == MONO_EXCEPTION_FIELD_ACCESS)) {
1527 if (fail_compile) {
1528 char *method_name = mono_method_full_name (method, TRUE);
1529 cfg->exception_type = info->exception_type;
1530 cfg->exception_message = g_strdup_printf ("Error verifying %s: %s", method_name, info->info.message);
1531 g_free (method_name);
1533 mono_free_verify_list (res);
1534 return TRUE;
1537 mono_free_verify_list (res);
1539 method->verification_success = 1;
1540 return FALSE;
1543 /*Returns true if something went wrong*/
1544 gboolean
1545 mono_compile_is_broken (MonoCompile *cfg, MonoMethod *method, gboolean fail_compile)
1547 MonoMethod *method_definition = method;
1548 gboolean dont_verify = method->klass->image->assembly->corlib_internal;
1550 while (method_definition->is_inflated) {
1551 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
1552 method_definition = imethod->declaring;
1555 return !dont_verify && mini_method_verify (cfg, method_definition, fail_compile);
1558 static gconstpointer
1559 mono_icall_get_wrapper_full (MonoJitICallInfo* callinfo, gboolean do_compile)
1561 char *name;
1562 MonoMethod *wrapper;
1563 gconstpointer trampoline;
1564 MonoDomain *domain = mono_get_root_domain ();
1566 if (callinfo->wrapper) {
1567 return callinfo->wrapper;
1570 if (callinfo->trampoline)
1571 return callinfo->trampoline;
1574 * We use the lock on the root domain instead of the JIT lock to protect
1575 * callinfo->trampoline, since we do a lot of stuff inside the critical section.
1577 mono_loader_lock (); /*FIXME mono_compile_method requires the loader lock, by large.*/
1578 mono_domain_lock (domain);
1580 if (callinfo->trampoline) {
1581 mono_domain_unlock (domain);
1582 mono_loader_unlock ();
1583 return callinfo->trampoline;
1586 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1587 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1588 g_free (name);
1590 if (do_compile)
1591 trampoline = mono_compile_method (wrapper);
1592 else
1593 trampoline = mono_create_ftnptr (domain, mono_create_jit_trampoline_in_domain (domain, wrapper));
1594 mono_register_jit_icall_wrapper (callinfo, trampoline);
1596 callinfo->trampoline = trampoline;
1598 mono_domain_unlock (domain);
1599 mono_loader_unlock ();
1601 return callinfo->trampoline;
1604 gconstpointer
1605 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
1607 return mono_icall_get_wrapper_full (callinfo, FALSE);
1610 static void
1611 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
1613 if (!domain_jit_info (domain)->dynamic_code_hash)
1614 domain_jit_info (domain)->dynamic_code_hash = g_hash_table_new (NULL, NULL);
1615 g_hash_table_insert (domain_jit_info (domain)->dynamic_code_hash, method, ji);
1618 static MonoJitDynamicMethodInfo*
1619 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
1621 MonoJitDynamicMethodInfo *res;
1623 if (domain_jit_info (domain)->dynamic_code_hash)
1624 res = g_hash_table_lookup (domain_jit_info (domain)->dynamic_code_hash, method);
1625 else
1626 res = NULL;
1627 return res;
1630 typedef struct {
1631 MonoClass *vtype;
1632 GList *active, *inactive;
1633 GSList *slots;
1634 } StackSlotInfo;
1636 static gint
1637 compare_by_interval_start_pos_func (gconstpointer a, gconstpointer b)
1639 MonoMethodVar *v1 = (MonoMethodVar*)a;
1640 MonoMethodVar *v2 = (MonoMethodVar*)b;
1642 if (v1 == v2)
1643 return 0;
1644 else if (v1->interval->range && v2->interval->range)
1645 return v1->interval->range->from - v2->interval->range->from;
1646 else if (v1->interval->range)
1647 return -1;
1648 else
1649 return 1;
1652 #ifndef DISABLE_JIT
1654 #if 0
1655 #define LSCAN_DEBUG(a) do { a; } while (0)
1656 #else
1657 #define LSCAN_DEBUG(a)
1658 #endif
1660 static gint32*
1661 mono_allocate_stack_slots2 (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
1663 int i, slot, offset, size;
1664 guint32 align;
1665 MonoMethodVar *vmv;
1666 MonoInst *inst;
1667 gint32 *offsets;
1668 GList *vars = NULL, *l, *unhandled;
1669 StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
1670 MonoType *t;
1671 int nvtypes;
1672 gboolean reuse_slot;
1674 LSCAN_DEBUG (printf ("Allocate Stack Slots 2 for %s:\n", mono_method_full_name (cfg->method, TRUE)));
1676 scalar_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
1677 vtype_stack_slots = NULL;
1678 nvtypes = 0;
1680 offsets = mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
1681 for (i = 0; i < cfg->num_varinfo; ++i)
1682 offsets [i] = -1;
1684 for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1685 inst = cfg->varinfo [i];
1686 vmv = MONO_VARINFO (cfg, i);
1688 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
1689 continue;
1691 vars = g_list_prepend (vars, vmv);
1694 vars = g_list_sort (g_list_copy (vars), compare_by_interval_start_pos_func);
1696 /* Sanity check */
1698 i = 0;
1699 for (unhandled = vars; unhandled; unhandled = unhandled->next) {
1700 MonoMethodVar *current = unhandled->data;
1702 if (current->interval->range) {
1703 g_assert (current->interval->range->from >= i);
1704 i = current->interval->range->from;
1709 offset = 0;
1710 *stack_align = 0;
1711 for (unhandled = vars; unhandled; unhandled = unhandled->next) {
1712 MonoMethodVar *current = unhandled->data;
1714 vmv = current;
1715 inst = cfg->varinfo [vmv->idx];
1717 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
1718 * pinvoke wrappers when they call functions returning structures */
1719 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF) {
1720 size = mono_class_native_size (mono_class_from_mono_type (inst->inst_vtype), &align);
1722 else {
1723 int ialign;
1725 size = mono_type_size (inst->inst_vtype, &ialign);
1726 align = ialign;
1728 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (inst->inst_vtype)))
1729 align = 16;
1732 reuse_slot = TRUE;
1733 if (cfg->disable_reuse_stack_slots)
1734 reuse_slot = FALSE;
1736 t = mono_type_get_underlying_type (inst->inst_vtype);
1737 switch (t->type) {
1738 case MONO_TYPE_GENERICINST:
1739 if (!mono_type_generic_inst_is_valuetype (t)) {
1740 slot_info = &scalar_stack_slots [t->type];
1741 break;
1743 /* Fall through */
1744 case MONO_TYPE_VALUETYPE:
1745 if (!vtype_stack_slots)
1746 vtype_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * 256);
1747 for (i = 0; i < nvtypes; ++i)
1748 if (t->data.klass == vtype_stack_slots [i].vtype)
1749 break;
1750 if (i < nvtypes)
1751 slot_info = &vtype_stack_slots [i];
1752 else {
1753 g_assert (nvtypes < 256);
1754 vtype_stack_slots [nvtypes].vtype = t->data.klass;
1755 slot_info = &vtype_stack_slots [nvtypes];
1756 nvtypes ++;
1758 if (cfg->disable_reuse_ref_stack_slots)
1759 reuse_slot = FALSE;
1760 break;
1762 case MONO_TYPE_PTR:
1763 case MONO_TYPE_I:
1764 case MONO_TYPE_U:
1765 #if SIZEOF_VOID_P == 4
1766 case MONO_TYPE_I4:
1767 #else
1768 case MONO_TYPE_I8:
1769 #endif
1770 if (cfg->disable_ref_noref_stack_slot_share) {
1771 slot_info = &scalar_stack_slots [MONO_TYPE_I];
1772 break;
1774 /* Fall through */
1776 case MONO_TYPE_CLASS:
1777 case MONO_TYPE_OBJECT:
1778 case MONO_TYPE_ARRAY:
1779 case MONO_TYPE_SZARRAY:
1780 case MONO_TYPE_STRING:
1781 /* Share non-float stack slots of the same size */
1782 slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
1783 if (cfg->disable_reuse_ref_stack_slots)
1784 reuse_slot = FALSE;
1785 break;
1787 default:
1788 slot_info = &scalar_stack_slots [t->type];
1791 slot = 0xffffff;
1792 if (cfg->comp_done & MONO_COMP_LIVENESS) {
1793 int pos;
1794 gboolean changed;
1796 //printf ("START %2d %08x %08x\n", vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
1798 if (!current->interval->range) {
1799 if (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))
1800 pos = ~0;
1801 else {
1802 /* Dead */
1803 inst->flags |= MONO_INST_IS_DEAD;
1804 continue;
1807 else
1808 pos = current->interval->range->from;
1810 LSCAN_DEBUG (printf ("process R%d ", inst->dreg));
1811 if (current->interval->range)
1812 LSCAN_DEBUG (mono_linterval_print (current->interval));
1813 LSCAN_DEBUG (printf ("\n"));
1815 /* Check for intervals in active which expired or inactive */
1816 changed = TRUE;
1817 /* FIXME: Optimize this */
1818 while (changed) {
1819 changed = FALSE;
1820 for (l = slot_info->active; l != NULL; l = l->next) {
1821 MonoMethodVar *v = (MonoMethodVar*)l->data;
1823 if (v->interval->last_range->to < pos) {
1824 slot_info->active = g_list_delete_link (slot_info->active, l);
1825 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [v->idx]));
1826 LSCAN_DEBUG (printf ("Interval R%d has expired, adding 0x%x to slots\n", cfg->varinfo [v->idx]->dreg, offsets [v->idx]));
1827 changed = TRUE;
1828 break;
1830 else if (!mono_linterval_covers (v->interval, pos)) {
1831 slot_info->inactive = g_list_append (slot_info->inactive, v);
1832 slot_info->active = g_list_delete_link (slot_info->active, l);
1833 LSCAN_DEBUG (printf ("Interval R%d became inactive\n", cfg->varinfo [v->idx]->dreg));
1834 changed = TRUE;
1835 break;
1840 /* Check for intervals in inactive which expired or active */
1841 changed = TRUE;
1842 /* FIXME: Optimize this */
1843 while (changed) {
1844 changed = FALSE;
1845 for (l = slot_info->inactive; l != NULL; l = l->next) {
1846 MonoMethodVar *v = (MonoMethodVar*)l->data;
1848 if (v->interval->last_range->to < pos) {
1849 slot_info->inactive = g_list_delete_link (slot_info->inactive, l);
1850 // FIXME: Enabling this seems to cause impossible to debug crashes
1851 //slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [v->idx]));
1852 LSCAN_DEBUG (printf ("Interval R%d has expired, adding 0x%x to slots\n", cfg->varinfo [v->idx]->dreg, offsets [v->idx]));
1853 changed = TRUE;
1854 break;
1856 else if (mono_linterval_covers (v->interval, pos)) {
1857 slot_info->active = g_list_append (slot_info->active, v);
1858 slot_info->inactive = g_list_delete_link (slot_info->inactive, l);
1859 LSCAN_DEBUG (printf ("\tInterval R%d became active\n", cfg->varinfo [v->idx]->dreg));
1860 changed = TRUE;
1861 break;
1867 * This also handles the case when the variable is used in an
1868 * exception region, as liveness info is not computed there.
1871 * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
1872 * opcodes.
1874 if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
1875 if (slot_info->slots) {
1876 slot = GPOINTER_TO_INT (slot_info->slots->data);
1878 slot_info->slots = slot_info->slots->next;
1881 /* FIXME: We might want to consider the inactive intervals as well if slot_info->slots is empty */
1883 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
1887 #if 0
1889 static int count = 0;
1890 count ++;
1892 if (count == atoi (getenv ("COUNT3")))
1893 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
1894 if (count > atoi (getenv ("COUNT3")))
1895 slot = 0xffffff;
1896 else {
1897 mono_print_ins (inst);
1900 #endif
1902 LSCAN_DEBUG (printf ("R%d %s -> 0x%x\n", inst->dreg, mono_type_full_name (t), slot));
1904 if (inst->flags & MONO_INST_LMF) {
1905 size = sizeof (MonoLMF);
1906 align = sizeof (mgreg_t);
1907 reuse_slot = FALSE;
1910 if (!reuse_slot)
1911 slot = 0xffffff;
1913 if (slot == 0xffffff) {
1915 * Allways allocate valuetypes to sizeof (gpointer) to allow more
1916 * efficient copying (and to work around the fact that OP_MEMCPY
1917 * and OP_MEMSET ignores alignment).
1919 if (MONO_TYPE_ISSTRUCT (t)) {
1920 align = MAX (align, sizeof (gpointer));
1921 align = MAX (align, mono_class_min_align (mono_class_from_mono_type (t)));
1924 if (backward) {
1925 offset += size;
1926 offset += align - 1;
1927 offset &= ~(align - 1);
1928 slot = offset;
1930 else {
1931 offset += align - 1;
1932 offset &= ~(align - 1);
1933 slot = offset;
1934 offset += size;
1937 if (*stack_align == 0)
1938 *stack_align = align;
1941 offsets [vmv->idx] = slot;
1943 g_list_free (vars);
1944 for (i = 0; i < MONO_TYPE_PINNED; ++i) {
1945 if (scalar_stack_slots [i].active)
1946 g_list_free (scalar_stack_slots [i].active);
1948 for (i = 0; i < nvtypes; ++i) {
1949 if (vtype_stack_slots [i].active)
1950 g_list_free (vtype_stack_slots [i].active);
1953 cfg->stat_locals_stack_size += offset;
1955 *stack_size = offset;
1956 return offsets;
1960 * mono_allocate_stack_slots:
1962 * Allocate stack slots for all non register allocated variables using a
1963 * linear scan algorithm.
1964 * Returns: an array of stack offsets.
1965 * STACK_SIZE is set to the amount of stack space needed.
1966 * STACK_ALIGN is set to the alignment needed by the locals area.
1968 gint32*
1969 mono_allocate_stack_slots (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
1971 int i, slot, offset, size;
1972 guint32 align;
1973 MonoMethodVar *vmv;
1974 MonoInst *inst;
1975 gint32 *offsets;
1976 GList *vars = NULL, *l;
1977 StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
1978 MonoType *t;
1979 int nvtypes;
1980 gboolean reuse_slot;
1982 if ((cfg->num_varinfo > 0) && MONO_VARINFO (cfg, 0)->interval)
1983 return mono_allocate_stack_slots2 (cfg, backward, stack_size, stack_align);
1985 scalar_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
1986 vtype_stack_slots = NULL;
1987 nvtypes = 0;
1989 offsets = mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
1990 for (i = 0; i < cfg->num_varinfo; ++i)
1991 offsets [i] = -1;
1993 for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1994 inst = cfg->varinfo [i];
1995 vmv = MONO_VARINFO (cfg, i);
1997 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
1998 continue;
2000 vars = g_list_prepend (vars, vmv);
2003 vars = mono_varlist_sort (cfg, vars, 0);
2004 offset = 0;
2005 *stack_align = sizeof(mgreg_t);
2006 for (l = vars; l; l = l->next) {
2007 vmv = l->data;
2008 inst = cfg->varinfo [vmv->idx];
2010 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
2011 * pinvoke wrappers when they call functions returning structures */
2012 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF) {
2013 size = mono_class_native_size (mono_class_from_mono_type (inst->inst_vtype), &align);
2014 } else {
2015 int ialign;
2017 size = mono_type_size (inst->inst_vtype, &ialign);
2018 align = ialign;
2020 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type (inst->inst_vtype)))
2021 align = 16;
2024 reuse_slot = TRUE;
2025 if (cfg->disable_reuse_stack_slots)
2026 reuse_slot = FALSE;
2028 t = mono_type_get_underlying_type (inst->inst_vtype);
2029 if (t->byref) {
2030 slot_info = &scalar_stack_slots [MONO_TYPE_I];
2031 } else {
2032 switch (t->type) {
2033 case MONO_TYPE_GENERICINST:
2034 if (!mono_type_generic_inst_is_valuetype (t)) {
2035 slot_info = &scalar_stack_slots [t->type];
2036 break;
2038 /* Fall through */
2039 case MONO_TYPE_VALUETYPE:
2040 if (!vtype_stack_slots)
2041 vtype_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * 256);
2042 for (i = 0; i < nvtypes; ++i)
2043 if (t->data.klass == vtype_stack_slots [i].vtype)
2044 break;
2045 if (i < nvtypes)
2046 slot_info = &vtype_stack_slots [i];
2047 else {
2048 g_assert (nvtypes < 256);
2049 vtype_stack_slots [nvtypes].vtype = t->data.klass;
2050 slot_info = &vtype_stack_slots [nvtypes];
2051 nvtypes ++;
2053 if (cfg->disable_reuse_ref_stack_slots)
2054 reuse_slot = FALSE;
2055 break;
2057 case MONO_TYPE_PTR:
2058 case MONO_TYPE_I:
2059 case MONO_TYPE_U:
2060 #if SIZEOF_VOID_P == 4
2061 case MONO_TYPE_I4:
2062 #else
2063 case MONO_TYPE_I8:
2064 #endif
2065 if (cfg->disable_ref_noref_stack_slot_share) {
2066 slot_info = &scalar_stack_slots [MONO_TYPE_I];
2067 break;
2069 /* Fall through */
2071 case MONO_TYPE_CLASS:
2072 case MONO_TYPE_OBJECT:
2073 case MONO_TYPE_ARRAY:
2074 case MONO_TYPE_SZARRAY:
2075 case MONO_TYPE_STRING:
2076 /* Share non-float stack slots of the same size */
2077 slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
2078 if (cfg->disable_reuse_ref_stack_slots)
2079 reuse_slot = FALSE;
2080 break;
2082 default:
2083 slot_info = &scalar_stack_slots [t->type];
2087 slot = 0xffffff;
2088 if (cfg->comp_done & MONO_COMP_LIVENESS) {
2089 //printf ("START %2d %08x %08x\n", vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
2091 /* expire old intervals in active */
2092 while (slot_info->active) {
2093 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
2095 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
2096 break;
2098 //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);
2100 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
2101 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
2105 * This also handles the case when the variable is used in an
2106 * exception region, as liveness info is not computed there.
2109 * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
2110 * opcodes.
2112 if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
2113 if (slot_info->slots) {
2114 slot = GPOINTER_TO_INT (slot_info->slots->data);
2116 slot_info->slots = slot_info->slots->next;
2119 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
2124 static int count = 0;
2125 count ++;
2128 if (count == atoi (getenv ("COUNT")))
2129 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
2130 if (count > atoi (getenv ("COUNT")))
2131 slot = 0xffffff;
2132 else {
2133 mono_print_ins (inst);
2138 if (inst->flags & MONO_INST_LMF) {
2140 * This variable represents a MonoLMF structure, which has no corresponding
2141 * CLR type, so hard-code its size/alignment.
2143 size = sizeof (MonoLMF);
2144 align = sizeof (mgreg_t);
2145 reuse_slot = FALSE;
2148 if (!reuse_slot)
2149 slot = 0xffffff;
2151 if (slot == 0xffffff) {
2153 * Allways allocate valuetypes to sizeof (gpointer) to allow more
2154 * efficient copying (and to work around the fact that OP_MEMCPY
2155 * and OP_MEMSET ignores alignment).
2157 if (MONO_TYPE_ISSTRUCT (t)) {
2158 align = MAX (align, sizeof (gpointer));
2159 align = MAX (align, mono_class_min_align (mono_class_from_mono_type (t)));
2161 * Align the size too so the code generated for passing vtypes in
2162 * registers doesn't overwrite random locals.
2164 size = (size + (align - 1)) & ~(align -1);
2167 if (backward) {
2168 offset += size;
2169 offset += align - 1;
2170 offset &= ~(align - 1);
2171 slot = offset;
2173 else {
2174 offset += align - 1;
2175 offset &= ~(align - 1);
2176 slot = offset;
2177 offset += size;
2180 *stack_align = MAX (*stack_align, align);
2183 offsets [vmv->idx] = slot;
2185 g_list_free (vars);
2186 for (i = 0; i < MONO_TYPE_PINNED; ++i) {
2187 if (scalar_stack_slots [i].active)
2188 g_list_free (scalar_stack_slots [i].active);
2190 for (i = 0; i < nvtypes; ++i) {
2191 if (vtype_stack_slots [i].active)
2192 g_list_free (vtype_stack_slots [i].active);
2195 cfg->stat_locals_stack_size += offset;
2197 *stack_size = offset;
2198 return offsets;
2201 #else
2203 gint32*
2204 mono_allocate_stack_slots (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
2206 g_assert_not_reached ();
2207 return NULL;
2210 #endif /* DISABLE_JIT */
2212 #define EMUL_HIT_SHIFT 3
2213 #define EMUL_HIT_MASK ((1 << EMUL_HIT_SHIFT) - 1)
2214 /* small hit bitmap cache */
2215 static mono_byte emul_opcode_hit_cache [(OP_LAST>>EMUL_HIT_SHIFT) + 1] = {0};
2216 static short emul_opcode_num = 0;
2217 static short emul_opcode_alloced = 0;
2218 static short *emul_opcode_opcodes = NULL;
2219 static MonoJitICallInfo **emul_opcode_map = NULL;
2221 MonoJitICallInfo *
2222 mono_find_jit_opcode_emulation (int opcode)
2224 g_assert (opcode >= 0 && opcode <= OP_LAST);
2225 if (emul_opcode_hit_cache [opcode >> (EMUL_HIT_SHIFT + 3)] & (1 << (opcode & EMUL_HIT_MASK))) {
2226 int i;
2227 for (i = 0; i < emul_opcode_num; ++i) {
2228 if (emul_opcode_opcodes [i] == opcode)
2229 return emul_opcode_map [i];
2232 return NULL;
2235 void
2236 mono_register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, gboolean no_throw)
2238 MonoJitICallInfo *info;
2239 MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
2241 g_assert (!sig->hasthis);
2242 g_assert (sig->param_count < 3);
2244 info = mono_register_jit_icall (func, name, sig, no_throw);
2246 if (emul_opcode_num >= emul_opcode_alloced) {
2247 int incr = emul_opcode_alloced? emul_opcode_alloced/2: 16;
2248 emul_opcode_alloced += incr;
2249 emul_opcode_map = g_realloc (emul_opcode_map, sizeof (emul_opcode_map [0]) * emul_opcode_alloced);
2250 emul_opcode_opcodes = g_realloc (emul_opcode_opcodes, sizeof (emul_opcode_opcodes [0]) * emul_opcode_alloced);
2252 emul_opcode_map [emul_opcode_num] = info;
2253 emul_opcode_opcodes [emul_opcode_num] = opcode;
2254 emul_opcode_num++;
2255 emul_opcode_hit_cache [opcode >> (EMUL_HIT_SHIFT + 3)] |= (1 << (opcode & EMUL_HIT_MASK));
2258 static void
2259 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
2261 MonoMethodSignature *sig;
2263 if (sigstr)
2264 sig = mono_create_icall_signature (sigstr);
2265 else
2266 sig = NULL;
2268 mono_register_jit_icall (func, name, sig, save);
2271 static void
2272 print_dfn (MonoCompile *cfg) {
2273 int i, j;
2274 char *code;
2275 MonoBasicBlock *bb;
2276 MonoInst *c;
2279 char *method_name = mono_method_full_name (cfg->method, TRUE);
2280 g_print ("IR code for method %s\n", method_name);
2281 g_free (method_name);
2284 for (i = 0; i < cfg->num_bblocks; ++i) {
2285 bb = cfg->bblocks [i];
2286 /*if (bb->cil_code) {
2287 char* code1, *code2;
2288 code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
2289 if (bb->last_ins->cil_code)
2290 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
2291 else
2292 code2 = g_strdup ("");
2294 code1 [strlen (code1) - 1] = 0;
2295 code = g_strdup_printf ("%s -> %s", code1, code2);
2296 g_free (code1);
2297 g_free (code2);
2298 } else*/
2299 code = g_strdup ("\n");
2300 g_print ("\nBB%d (%d) (len: %d): %s", bb->block_num, i, bb->cil_length, code);
2301 MONO_BB_FOR_EACH_INS (bb, c) {
2302 mono_print_ins_index (-1, c);
2305 g_print ("\tprev:");
2306 for (j = 0; j < bb->in_count; ++j) {
2307 g_print (" BB%d", bb->in_bb [j]->block_num);
2309 g_print ("\t\tsucc:");
2310 for (j = 0; j < bb->out_count; ++j) {
2311 g_print (" BB%d", bb->out_bb [j]->block_num);
2313 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
2315 if (bb->idom)
2316 g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
2318 if (bb->dominators)
2319 mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
2320 if (bb->dfrontier)
2321 mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
2322 g_free (code);
2325 g_print ("\n");
2328 void
2329 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
2331 MONO_ADD_INS (bb, inst);
2334 void
2335 mono_bblock_insert_after_ins (MonoBasicBlock *bb, MonoInst *ins, MonoInst *ins_to_insert)
2337 if (ins == NULL) {
2338 ins = bb->code;
2339 bb->code = ins_to_insert;
2341 /* Link with next */
2342 ins_to_insert->next = ins;
2343 if (ins)
2344 ins->prev = ins_to_insert;
2346 if (bb->last_ins == NULL)
2347 bb->last_ins = ins_to_insert;
2348 } else {
2349 /* Link with next */
2350 ins_to_insert->next = ins->next;
2351 if (ins->next)
2352 ins->next->prev = ins_to_insert;
2354 /* Link with previous */
2355 ins->next = ins_to_insert;
2356 ins_to_insert->prev = ins;
2358 if (bb->last_ins == ins)
2359 bb->last_ins = ins_to_insert;
2363 void
2364 mono_bblock_insert_before_ins (MonoBasicBlock *bb, MonoInst *ins, MonoInst *ins_to_insert)
2366 if (ins == NULL) {
2367 ins = bb->code;
2368 if (ins)
2369 ins->prev = ins_to_insert;
2370 bb->code = ins_to_insert;
2371 ins_to_insert->next = ins;
2372 if (bb->last_ins == NULL)
2373 bb->last_ins = ins_to_insert;
2374 } else {
2375 /* Link with previous */
2376 if (ins->prev)
2377 ins->prev->next = ins_to_insert;
2378 ins_to_insert->prev = ins->prev;
2380 /* Link with next */
2381 ins->prev = ins_to_insert;
2382 ins_to_insert->next = ins;
2384 if (bb->code == ins)
2385 bb->code = ins_to_insert;
2390 * mono_verify_bblock:
2392 * Verify that the next and prev pointers are consistent inside the instructions in BB.
2394 void
2395 mono_verify_bblock (MonoBasicBlock *bb)
2397 MonoInst *ins, *prev;
2399 prev = NULL;
2400 for (ins = bb->code; ins; ins = ins->next) {
2401 g_assert (ins->prev == prev);
2402 prev = ins;
2404 if (bb->last_ins)
2405 g_assert (!bb->last_ins->next);
2409 * mono_verify_cfg:
2411 * Perform consistency checks on the JIT data structures and the IR
2413 void
2414 mono_verify_cfg (MonoCompile *cfg)
2416 MonoBasicBlock *bb;
2418 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2419 mono_verify_bblock (bb);
2422 void
2423 mono_destroy_compile (MonoCompile *cfg)
2425 GSList *l;
2427 if (cfg->header)
2428 mono_metadata_free_mh (cfg->header);
2429 //mono_mempool_stats (cfg->mempool);
2430 mono_free_loop_info (cfg);
2431 if (cfg->rs)
2432 mono_regstate_free (cfg->rs);
2433 if (cfg->spvars)
2434 g_hash_table_destroy (cfg->spvars);
2435 if (cfg->exvars)
2436 g_hash_table_destroy (cfg->exvars);
2437 for (l = cfg->headers_to_free; l; l = l->next)
2438 mono_metadata_free_mh (l->data);
2439 g_list_free (cfg->ldstr_list);
2440 g_hash_table_destroy (cfg->token_info_hash);
2441 if (cfg->abs_patches)
2442 g_hash_table_destroy (cfg->abs_patches);
2443 mono_mempool_destroy (cfg->mempool);
2445 mono_debug_free_method (cfg);
2447 g_free (cfg->varinfo);
2448 g_free (cfg->vars);
2449 g_free (cfg->exception_message);
2450 g_free (cfg);
2453 #ifdef MONO_HAVE_FAST_TLS
2454 MONO_FAST_TLS_DECLARE(mono_lmf_addr);
2455 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
2457 * When this is defined, the current lmf is stored in this tls variable instead of in
2458 * jit_tls->lmf.
2460 MONO_FAST_TLS_DECLARE(mono_lmf);
2461 #endif
2462 #endif
2464 MonoNativeTlsKey
2465 mono_get_jit_tls_key (void)
2467 return mono_jit_tls_id;
2470 gint32
2471 mono_get_jit_tls_offset (void)
2473 int offset;
2474 MONO_THREAD_VAR_OFFSET (mono_jit_tls, offset);
2475 return offset;
2478 gint32
2479 mono_get_lmf_tls_offset (void)
2481 #if defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
2482 int offset;
2483 MONO_THREAD_VAR_OFFSET(mono_lmf,offset);
2484 return offset;
2485 #else
2486 return -1;
2487 #endif
2490 gint32
2491 mono_get_lmf_addr_tls_offset (void)
2493 int offset;
2494 MONO_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
2495 return offset;
2498 MonoLMF *
2499 mono_get_lmf (void)
2501 #if defined(MONO_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
2502 return MONO_FAST_TLS_GET (mono_lmf);
2503 #else
2504 MonoJitTlsData *jit_tls;
2506 if ((jit_tls = mono_native_tls_get_value (mono_jit_tls_id)))
2507 return jit_tls->lmf;
2509 * We do not assert here because this function can be called from
2510 * mini-gc.c on a thread that has not executed any managed code, yet
2511 * (the thread object allocation can trigger a collection).
2513 return NULL;
2514 #endif
2517 MonoLMF **
2518 mono_get_lmf_addr (void)
2520 #ifdef MONO_HAVE_FAST_TLS
2521 return MONO_FAST_TLS_GET (mono_lmf_addr);
2522 #else
2523 MonoJitTlsData *jit_tls;
2525 if ((jit_tls = mono_native_tls_get_value (mono_jit_tls_id)))
2526 return &jit_tls->lmf;
2529 * When resolving the call to mono_jit_thread_attach full-aot will look
2530 * in the plt, which causes a call into the generic trampoline, which in turn
2531 * tries to resolve the lmf_addr creating a cyclic dependency. We cannot
2532 * call mono_jit_thread_attach from the native-to-managed wrapper, without
2533 * mono_get_lmf_addr, and mono_get_lmf_addr requires the thread to be attached.
2536 mono_jit_thread_attach (NULL);
2538 if ((jit_tls = mono_native_tls_get_value (mono_jit_tls_id)))
2539 return &jit_tls->lmf;
2541 g_assert_not_reached ();
2542 return NULL;
2543 #endif
2546 void
2547 mono_set_lmf (MonoLMF *lmf)
2549 #if defined(MONO_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
2550 MONO_FAST_TLS_SET (mono_lmf, lmf);
2551 #endif
2553 (*mono_get_lmf_addr ()) = lmf;
2556 static void
2557 mono_set_jit_tls (MonoJitTlsData *jit_tls)
2559 mono_native_tls_set_value (mono_jit_tls_id, jit_tls);
2561 #ifdef MONO_HAVE_FAST_TLS
2562 MONO_FAST_TLS_SET (mono_jit_tls, jit_tls);
2563 #endif
2566 static void
2567 mono_set_lmf_addr (gpointer lmf_addr)
2569 #ifdef MONO_HAVE_FAST_TLS
2570 MONO_FAST_TLS_SET (mono_lmf_addr, lmf_addr);
2571 #endif
2574 /* Called by native->managed wrappers */
2575 void
2576 mono_jit_thread_attach (MonoDomain *domain)
2578 if (!domain)
2580 * Happens when called from AOTed code which is only used in the root
2581 * domain.
2583 domain = mono_get_root_domain ();
2585 #ifdef MONO_HAVE_FAST_TLS
2586 if (!MONO_FAST_TLS_GET (mono_lmf_addr)) {
2587 mono_thread_attach (domain);
2588 // #678164
2589 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background);
2591 #else
2592 if (!mono_native_tls_get_value (mono_jit_tls_id)) {
2593 mono_thread_attach (domain);
2594 mono_thread_set_state (mono_thread_internal_current (), ThreadState_Background);
2596 #endif
2597 if (mono_domain_get () != domain)
2598 mono_domain_set (domain, TRUE);
2602 * mono_thread_abort:
2603 * @obj: exception object
2605 * abort the thread, print exception information and stack trace
2607 static void
2608 mono_thread_abort (MonoObject *obj)
2610 /* MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id); */
2612 /* handle_remove should be eventually called for this thread, too
2613 g_free (jit_tls);*/
2615 if ((mono_runtime_unhandled_exception_policy_get () == MONO_UNHANDLED_POLICY_LEGACY) ||
2616 (obj->vtable->klass == mono_defaults.threadabortexception_class)) {
2617 mono_thread_exit ();
2618 } else {
2619 MonoObject *other = NULL;
2620 MonoString *str = mono_object_to_string (obj, &other);
2621 if (str) {
2622 char *msg = mono_string_to_utf8 (str);
2623 fprintf (stderr, "[ERROR] FATAL UNHANDLED EXCEPTION: %s\n", msg);
2624 fflush (stderr);
2625 g_free (msg);
2628 exit (mono_environment_exitcode_get ());
2632 static void*
2633 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
2635 MonoJitTlsData *jit_tls;
2636 MonoLMF *lmf;
2638 jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
2639 if (jit_tls)
2640 return jit_tls;
2642 jit_tls = g_new0 (MonoJitTlsData, 1);
2644 jit_tls->abort_func = abort_func;
2645 jit_tls->end_of_stack = stack_start;
2647 mono_set_jit_tls (jit_tls);
2649 lmf = g_new0 (MonoLMF, 1);
2650 MONO_ARCH_INIT_TOP_LMF_ENTRY (lmf);
2652 jit_tls->first_lmf = lmf;
2654 #if defined(MONO_HAVE_FAST_TLS) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
2655 /* jit_tls->lmf is unused */
2656 MONO_FAST_TLS_SET (mono_lmf, lmf);
2657 mono_set_lmf_addr (MONO_FAST_TLS_ADDR (mono_lmf));
2658 #else
2659 mono_set_lmf_addr (&jit_tls->lmf);
2661 jit_tls->lmf = lmf;
2662 #endif
2664 mono_arch_setup_jit_tls_data (jit_tls);
2665 mono_setup_altstack (jit_tls);
2667 return jit_tls;
2670 static void
2671 free_jit_tls_data (MonoJitTlsData *jit_tls)
2673 mono_arch_free_jit_tls_data (jit_tls);
2674 mono_free_altstack (jit_tls);
2676 g_free (jit_tls->first_lmf);
2677 g_free (jit_tls);
2680 static void
2681 mono_thread_start_cb (intptr_t tid, gpointer stack_start, gpointer func)
2683 MonoInternalThread *thread;
2684 void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
2685 thread = mono_thread_internal_current ();
2686 mono_debugger_thread_created (tid, thread->root_domain_thread, jit_tls, func);
2687 if (thread)
2688 thread->jit_data = jit_tls;
2690 mono_arch_cpu_init ();
2693 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
2695 static void
2696 mono_thread_abort_dummy (MonoObject *obj)
2698 if (mono_thread_attach_aborted_cb)
2699 mono_thread_attach_aborted_cb (obj);
2700 else
2701 mono_thread_abort (obj);
2704 static void
2705 mono_thread_attach_cb (intptr_t tid, gpointer stack_start)
2707 MonoInternalThread *thread;
2708 void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
2709 thread = mono_thread_internal_current ();
2710 mono_debugger_thread_created (tid, thread->root_domain_thread, (MonoJitTlsData *) jit_tls, NULL);
2711 if (thread)
2712 thread->jit_data = jit_tls;
2713 if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
2714 mono_runtime_setup_stat_profiler ();
2716 mono_arch_cpu_init ();
2719 static void
2720 mini_thread_cleanup (MonoInternalThread *thread)
2722 MonoJitTlsData *jit_tls = thread->jit_data;
2724 if (jit_tls) {
2725 mono_debugger_thread_cleanup (jit_tls);
2727 /* We can't clean up tls information if we are on another thread, it will clean up the wrong stuff
2728 * It would be nice to issue a warning when this happens outside of the shutdown sequence. but it's
2729 * not a trivial thing.
2731 * The current offender is mono_thread_manage which cleanup threads from the outside.
2733 if (thread == mono_thread_internal_current ())
2734 mono_set_jit_tls (NULL);
2736 /* If we attach a thread but never call into managed land, we might never get an lmf.*/
2737 if (mono_get_lmf ()) {
2738 mono_set_lmf (NULL);
2739 mono_set_lmf_addr (NULL);
2742 free_jit_tls_data (jit_tls);
2744 thread->jit_data = NULL;
2748 static MonoInst*
2749 mono_create_tls_get (MonoCompile *cfg, int offset)
2751 #ifdef MONO_ARCH_HAVE_TLS_GET
2752 if (MONO_ARCH_HAVE_TLS_GET) {
2753 MonoInst* ins;
2755 if (offset == -1)
2756 return NULL;
2758 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
2759 ins->dreg = mono_alloc_preg (cfg);
2760 ins->inst_offset = offset;
2761 return ins;
2763 #endif
2764 return NULL;
2767 MonoInst*
2768 mono_get_jit_tls_intrinsic (MonoCompile *cfg)
2770 return mono_create_tls_get (cfg, mono_get_jit_tls_offset ());
2773 MonoInst*
2774 mono_get_domain_intrinsic (MonoCompile* cfg)
2776 return mono_create_tls_get (cfg, mono_domain_get_tls_offset ());
2779 MonoInst*
2780 mono_get_thread_intrinsic (MonoCompile* cfg)
2782 return mono_create_tls_get (cfg, mono_thread_get_tls_offset ());
2785 void
2786 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
2788 MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
2790 ji->ip.i = ip;
2791 ji->type = type;
2792 ji->data.target = target;
2793 ji->next = cfg->patch_info;
2795 cfg->patch_info = ji;
2798 MonoJumpInfo *
2799 mono_patch_info_list_prepend (MonoJumpInfo *list, int ip, MonoJumpInfoType type, gconstpointer target)
2801 MonoJumpInfo *ji = g_new0 (MonoJumpInfo, 1);
2803 ji->ip.i = ip;
2804 ji->type = type;
2805 ji->data.target = target;
2806 ji->next = list;
2808 return ji;
2811 void
2812 mono_remove_patch_info (MonoCompile *cfg, int ip)
2814 MonoJumpInfo **ji = &cfg->patch_info;
2816 while (*ji) {
2817 if ((*ji)->ip.i == ip)
2818 *ji = (*ji)->next;
2819 else
2820 ji = &((*ji)->next);
2825 * mono_patch_info_dup_mp:
2827 * Make a copy of PATCH_INFO, allocating memory from the mempool MP.
2829 MonoJumpInfo*
2830 mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info)
2832 MonoJumpInfo *res = mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
2833 memcpy (res, patch_info, sizeof (MonoJumpInfo));
2835 switch (patch_info->type) {
2836 case MONO_PATCH_INFO_RVA:
2837 case MONO_PATCH_INFO_LDSTR:
2838 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2839 case MONO_PATCH_INFO_LDTOKEN:
2840 case MONO_PATCH_INFO_DECLSEC:
2841 res->data.token = mono_mempool_alloc (mp, sizeof (MonoJumpInfoToken));
2842 memcpy (res->data.token, patch_info->data.token, sizeof (MonoJumpInfoToken));
2843 break;
2844 case MONO_PATCH_INFO_SWITCH:
2845 res->data.table = mono_mempool_alloc (mp, sizeof (MonoJumpInfoBBTable));
2846 memcpy (res->data.table, patch_info->data.table, sizeof (MonoJumpInfoBBTable));
2847 res->data.table->table = mono_mempool_alloc (mp, sizeof (MonoBasicBlock*) * patch_info->data.table->table_size);
2848 memcpy (res->data.table->table, patch_info->data.table->table, sizeof (MonoBasicBlock*) * patch_info->data.table->table_size);
2849 break;
2850 case MONO_PATCH_INFO_RGCTX_FETCH:
2851 res->data.rgctx_entry = mono_mempool_alloc (mp, sizeof (MonoJumpInfoRgctxEntry));
2852 memcpy (res->data.rgctx_entry, patch_info->data.rgctx_entry, sizeof (MonoJumpInfoRgctxEntry));
2853 res->data.rgctx_entry->data = mono_patch_info_dup_mp (mp, res->data.rgctx_entry->data);
2854 break;
2855 default:
2856 break;
2859 return res;
2862 guint
2863 mono_patch_info_hash (gconstpointer data)
2865 const MonoJumpInfo *ji = (MonoJumpInfo*)data;
2867 switch (ji->type) {
2868 case MONO_PATCH_INFO_RVA:
2869 case MONO_PATCH_INFO_LDSTR:
2870 case MONO_PATCH_INFO_LDTOKEN:
2871 case MONO_PATCH_INFO_DECLSEC:
2872 return (ji->type << 8) | ji->data.token->token;
2873 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2874 return (ji->type << 8) | ji->data.token->token | (ji->data.token->has_context ? (gsize)ji->data.token->context.class_inst : 0);
2875 case MONO_PATCH_INFO_INTERNAL_METHOD:
2876 return (ji->type << 8) | g_str_hash (ji->data.name);
2877 case MONO_PATCH_INFO_VTABLE:
2878 case MONO_PATCH_INFO_CLASS:
2879 case MONO_PATCH_INFO_IID:
2880 case MONO_PATCH_INFO_ADJUSTED_IID:
2881 case MONO_PATCH_INFO_CLASS_INIT:
2882 case MONO_PATCH_INFO_METHODCONST:
2883 case MONO_PATCH_INFO_METHOD:
2884 case MONO_PATCH_INFO_METHOD_JUMP:
2885 case MONO_PATCH_INFO_IMAGE:
2886 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2887 case MONO_PATCH_INFO_FIELD:
2888 case MONO_PATCH_INFO_SFLDA:
2889 case MONO_PATCH_INFO_SEQ_POINT_INFO:
2890 return (ji->type << 8) | (gssize)ji->data.target;
2891 default:
2892 return (ji->type << 8);
2897 * mono_patch_info_equal:
2899 * This might fail to recognize equivalent patches, i.e. floats, so its only
2900 * usable in those cases where this is not a problem, i.e. sharing GOT slots
2901 * in AOT.
2903 gint
2904 mono_patch_info_equal (gconstpointer ka, gconstpointer kb)
2906 const MonoJumpInfo *ji1 = (MonoJumpInfo*)ka;
2907 const MonoJumpInfo *ji2 = (MonoJumpInfo*)kb;
2909 if (ji1->type != ji2->type)
2910 return 0;
2912 switch (ji1->type) {
2913 case MONO_PATCH_INFO_RVA:
2914 case MONO_PATCH_INFO_LDSTR:
2915 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2916 case MONO_PATCH_INFO_LDTOKEN:
2917 case MONO_PATCH_INFO_DECLSEC:
2918 if ((ji1->data.token->image != ji2->data.token->image) ||
2919 (ji1->data.token->token != ji2->data.token->token) ||
2920 (ji1->data.token->has_context != ji2->data.token->has_context) ||
2921 (ji1->data.token->context.class_inst != ji2->data.token->context.class_inst) ||
2922 (ji1->data.token->context.method_inst != ji2->data.token->context.method_inst))
2923 return 0;
2924 break;
2925 case MONO_PATCH_INFO_INTERNAL_METHOD:
2926 return g_str_equal (ji1->data.name, ji2->data.name);
2928 case MONO_PATCH_INFO_RGCTX_FETCH: {
2929 MonoJumpInfoRgctxEntry *e1 = ji1->data.rgctx_entry;
2930 MonoJumpInfoRgctxEntry *e2 = ji2->data.rgctx_entry;
2932 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);
2934 default:
2935 if (ji1->data.target != ji2->data.target)
2936 return 0;
2937 break;
2940 return 1;
2943 gpointer
2944 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
2946 unsigned char *ip = patch_info->ip.i + code;
2947 gconstpointer target = NULL;
2949 switch (patch_info->type) {
2950 case MONO_PATCH_INFO_BB:
2952 * FIXME: This could be hit for methods without a prolog. Should use -1
2953 * but too much code depends on a 0 initial value.
2955 //g_assert (patch_info->data.bb->native_offset);
2956 target = patch_info->data.bb->native_offset + code;
2957 break;
2958 case MONO_PATCH_INFO_ABS:
2959 target = patch_info->data.target;
2960 break;
2961 case MONO_PATCH_INFO_LABEL:
2962 target = patch_info->data.inst->inst_c0 + code;
2963 break;
2964 case MONO_PATCH_INFO_IP:
2965 #if defined(__native_client__) && defined(__native_client_codegen__)
2966 /* Need to transform to the destination address, it's */
2967 /* emitted as an immediate in the code. */
2968 target = nacl_inverse_modify_patch_target(ip);
2969 #else
2970 target = ip;
2971 #endif
2972 break;
2973 case MONO_PATCH_INFO_METHOD_REL:
2974 target = code + patch_info->data.offset;
2975 break;
2976 case MONO_PATCH_INFO_INTERNAL_METHOD: {
2977 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
2978 if (!mi) {
2979 g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
2980 g_assert_not_reached ();
2982 target = mono_icall_get_wrapper (mi);
2983 break;
2985 case MONO_PATCH_INFO_METHOD_JUMP:
2986 target = mono_create_jump_trampoline (domain, patch_info->data.method, FALSE);
2987 #if defined(__native_client__) && defined(__native_client_codegen__)
2988 #if defined(TARGET_AMD64)
2989 /* This target is an absolute address, not relative to the */
2990 /* current code being emitted on AMD64. */
2991 target = nacl_inverse_modify_patch_target(target);
2992 #endif
2993 #endif
2994 break;
2995 case MONO_PATCH_INFO_METHOD:
2996 if (patch_info->data.method == method) {
2997 target = code;
2998 } else {
2999 /* get the trampoline to the method from the domain */
3000 target = mono_create_jit_trampoline_in_domain (domain, patch_info->data.method);
3002 break;
3003 case MONO_PATCH_INFO_SWITCH: {
3004 gpointer *jump_table;
3005 int i;
3007 #if defined(__native_client__) && defined(__native_client_codegen__)
3008 /* This memory will leak, but we don't care if we're */
3009 /* not deleting JIT'd methods anyway */
3010 jump_table = g_malloc0 (sizeof(gpointer) * patch_info->data.table->table_size);
3011 #else
3012 if (method && method->dynamic) {
3013 jump_table = mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
3014 } else {
3015 if (mono_aot_only) {
3016 jump_table = mono_domain_alloc (domain, sizeof (gpointer) * patch_info->data.table->table_size);
3017 } else {
3018 jump_table = mono_domain_code_reserve (domain, sizeof (gpointer) * patch_info->data.table->table_size);
3021 #endif
3023 for (i = 0; i < patch_info->data.table->table_size; i++) {
3024 #if defined(__native_client__) && defined(__native_client_codegen__)
3025 /* 'code' is relative to the current code blob, we */
3026 /* need to do this transform on it to make the */
3027 /* pointers in this table absolute */
3028 jump_table [i] = nacl_inverse_modify_patch_target (code) + GPOINTER_TO_INT (patch_info->data.table->table [i]);
3029 #else
3030 jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
3031 #endif
3034 #if defined(__native_client__) && defined(__native_client_codegen__)
3035 /* jump_table is in the data section, we need to transform */
3036 /* it here so when it gets modified in amd64_patch it will */
3037 /* then point back to the absolute data address */
3038 target = nacl_inverse_modify_patch_target (jump_table);
3039 #else
3040 target = jump_table;
3041 #endif
3042 break;
3044 case MONO_PATCH_INFO_METHODCONST:
3045 case MONO_PATCH_INFO_CLASS:
3046 case MONO_PATCH_INFO_IMAGE:
3047 case MONO_PATCH_INFO_FIELD:
3048 case MONO_PATCH_INFO_SIGNATURE:
3049 target = patch_info->data.target;
3050 break;
3051 case MONO_PATCH_INFO_IID:
3052 mono_class_init (patch_info->data.klass);
3053 target = GINT_TO_POINTER ((int)patch_info->data.klass->interface_id);
3054 break;
3055 case MONO_PATCH_INFO_ADJUSTED_IID:
3056 mono_class_init (patch_info->data.klass);
3057 target = GINT_TO_POINTER ((int)(-((patch_info->data.klass->interface_id + 1) * SIZEOF_VOID_P)));
3058 break;
3059 case MONO_PATCH_INFO_VTABLE:
3060 target = mono_class_vtable (domain, patch_info->data.klass);
3061 g_assert (target);
3062 break;
3063 case MONO_PATCH_INFO_CLASS_INIT: {
3064 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.klass);
3066 g_assert (vtable);
3067 target = mono_create_class_init_trampoline (vtable);
3068 break;
3070 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3071 target = mono_create_delegate_trampoline (domain, patch_info->data.klass);
3072 break;
3073 case MONO_PATCH_INFO_SFLDA: {
3074 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
3076 if (mono_class_field_is_special_static (patch_info->data.field)) {
3077 gpointer addr = NULL;
3079 mono_domain_lock (domain);
3080 if (domain->special_static_fields)
3081 addr = g_hash_table_lookup (domain->special_static_fields, patch_info->data.field);
3082 mono_domain_unlock (domain);
3083 g_assert (addr);
3084 return addr;
3087 g_assert (vtable);
3088 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && (method && mono_class_needs_cctor_run (vtable->klass, method)))
3089 /* Done by the generated code */
3091 else {
3092 if (run_cctors)
3093 mono_runtime_class_init (vtable);
3095 target = (char*)mono_vtable_get_static_field_data (vtable) + patch_info->data.field->offset;
3096 break;
3098 case MONO_PATCH_INFO_RVA: {
3099 guint32 field_index = mono_metadata_token_index (patch_info->data.token->token);
3100 guint32 rva;
3102 mono_metadata_field_info (patch_info->data.token->image, field_index - 1, NULL, &rva, NULL);
3103 target = mono_image_rva_map (patch_info->data.token->image, rva);
3104 break;
3106 case MONO_PATCH_INFO_R4:
3107 case MONO_PATCH_INFO_R8:
3108 target = patch_info->data.target;
3109 break;
3110 case MONO_PATCH_INFO_EXC_NAME:
3111 target = patch_info->data.name;
3112 break;
3113 case MONO_PATCH_INFO_LDSTR:
3114 target =
3115 mono_ldstr (domain, patch_info->data.token->image,
3116 mono_metadata_token_index (patch_info->data.token->token));
3117 break;
3118 case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
3119 gpointer handle;
3120 MonoClass *handle_class;
3122 handle = mono_ldtoken (patch_info->data.token->image,
3123 patch_info->data.token->token, &handle_class, patch_info->data.token->has_context ? &patch_info->data.token->context : NULL);
3124 mono_class_init (handle_class);
3125 mono_class_init (mono_class_from_mono_type (handle));
3127 target =
3128 mono_type_get_object (domain, handle);
3129 break;
3131 case MONO_PATCH_INFO_LDTOKEN: {
3132 gpointer handle;
3133 MonoClass *handle_class;
3135 handle = mono_ldtoken (patch_info->data.token->image,
3136 patch_info->data.token->token, &handle_class, NULL);
3137 mono_class_init (handle_class);
3139 target = handle;
3140 break;
3142 case MONO_PATCH_INFO_DECLSEC:
3143 target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
3144 break;
3145 case MONO_PATCH_INFO_ICALL_ADDR:
3146 /* run_cctors == 0 -> AOT */
3147 if (patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) {
3148 if (run_cctors) {
3149 target = mono_lookup_pinvoke_call (patch_info->data.method, NULL, NULL);
3150 if (!target)
3151 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));
3152 } else {
3153 target = NULL;
3155 } else {
3156 target = mono_lookup_internal_call (patch_info->data.method);
3158 if (!target && run_cctors)
3159 g_error ("Unregistered icall '%s'\n", mono_method_full_name (patch_info->data.method, TRUE));
3161 break;
3162 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3163 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
3164 if (!mi) {
3165 g_warning ("unknown MONO_PATCH_INFO_JIT_ICALL_ADDR %s", patch_info->data.name);
3166 g_assert_not_reached ();
3168 target = mi->func;
3169 break;
3171 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3172 target = mono_thread_interruption_request_flag ();
3173 break;
3174 case MONO_PATCH_INFO_METHOD_RGCTX: {
3175 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.method->klass);
3176 g_assert (vtable);
3178 target = mono_method_lookup_rgctx (vtable, mini_method_get_context (patch_info->data.method)->method_inst);
3179 break;
3181 case MONO_PATCH_INFO_BB_OVF:
3182 case MONO_PATCH_INFO_EXC_OVF:
3183 case MONO_PATCH_INFO_GOT_OFFSET:
3184 case MONO_PATCH_INFO_NONE:
3185 break;
3186 case MONO_PATCH_INFO_RGCTX_FETCH: {
3187 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3188 guint32 slot = -1;
3190 switch (entry->data->type) {
3191 case MONO_PATCH_INFO_CLASS:
3192 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));
3193 break;
3194 case MONO_PATCH_INFO_METHOD:
3195 case MONO_PATCH_INFO_METHODCONST:
3196 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));
3197 break;
3198 case MONO_PATCH_INFO_FIELD:
3199 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));
3200 break;
3201 default:
3202 g_assert_not_reached ();
3203 break;
3206 target = mono_create_rgctx_lazy_fetch_trampoline (slot);
3207 break;
3209 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3210 target = mono_create_generic_class_init_trampoline ();
3211 break;
3212 case MONO_PATCH_INFO_MONITOR_ENTER:
3213 target = mono_create_monitor_enter_trampoline ();
3214 break;
3215 case MONO_PATCH_INFO_MONITOR_EXIT:
3216 target = mono_create_monitor_exit_trampoline ();
3217 break;
3218 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3219 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3220 if (!run_cctors)
3221 /* AOT, not needed */
3222 target = NULL;
3223 else
3224 target = mono_arch_get_seq_point_info (domain, code);
3225 break;
3226 #endif
3227 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3228 #ifdef MONO_ARCH_LLVM_SUPPORTED
3229 g_assert (mono_use_llvm);
3230 target = mono_create_llvm_imt_trampoline (domain, patch_info->data.imt_tramp->method, patch_info->data.imt_tramp->vt_offset);
3231 #else
3232 g_assert_not_reached ();
3233 #endif
3234 break;
3235 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR: {
3236 int card_table_shift_bits;
3237 gpointer card_table_mask;
3239 target = mono_gc_get_card_table (&card_table_shift_bits, &card_table_mask);
3240 break;
3242 case MONO_PATCH_INFO_CASTCLASS_CACHE: {
3243 target = mono_domain_alloc0 (domain, sizeof (gpointer));
3244 break;
3246 default:
3247 g_assert_not_reached ();
3250 return (gpointer)target;
3253 void
3254 mono_add_seq_point (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, int native_offset)
3256 ins->inst_offset = native_offset;
3257 g_ptr_array_add (cfg->seq_points, ins);
3258 bb->seq_points = g_slist_prepend_mempool (cfg->mempool, bb->seq_points, ins);
3259 bb->last_seq_point = ins;
3262 #ifndef DISABLE_JIT
3264 static void
3265 mono_compile_create_vars (MonoCompile *cfg)
3267 MonoMethodSignature *sig;
3268 MonoMethodHeader *header;
3269 int i;
3271 header = cfg->header;
3273 sig = mono_method_signature (cfg->method);
3275 if (!MONO_TYPE_IS_VOID (sig->ret)) {
3276 cfg->ret = mono_compile_create_var (cfg, sig->ret, OP_ARG);
3277 /* Inhibit optimizations */
3278 cfg->ret->flags |= MONO_INST_VOLATILE;
3280 if (cfg->verbose_level > 2)
3281 g_print ("creating vars\n");
3283 cfg->args = mono_mempool_alloc0 (cfg->mempool, (sig->param_count + sig->hasthis) * sizeof (MonoInst*));
3285 if (sig->hasthis)
3286 cfg->args [0] = mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
3288 for (i = 0; i < sig->param_count; ++i) {
3289 cfg->args [i + sig->hasthis] = mono_compile_create_var (cfg, sig->params [i], OP_ARG);
3292 if (cfg->verbose_level > 2) {
3293 if (cfg->ret) {
3294 printf ("\treturn : ");
3295 mono_print_ins (cfg->ret);
3298 if (sig->hasthis) {
3299 printf ("\tthis: ");
3300 mono_print_ins (cfg->args [0]);
3303 for (i = 0; i < sig->param_count; ++i) {
3304 printf ("\targ [%d]: ", i);
3305 mono_print_ins (cfg->args [i + sig->hasthis]);
3309 cfg->locals_start = cfg->num_varinfo;
3310 cfg->locals = mono_mempool_alloc0 (cfg->mempool, header->num_locals * sizeof (MonoInst*));
3312 if (cfg->verbose_level > 2)
3313 g_print ("creating locals\n");
3315 for (i = 0; i < header->num_locals; ++i)
3316 cfg->locals [i] = mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
3318 if (cfg->verbose_level > 2)
3319 g_print ("locals done\n");
3321 mono_arch_create_vars (cfg);
3324 #endif /* #ifndef DISABLE_JIT */
3326 void
3327 mono_print_code (MonoCompile *cfg, const char* msg)
3329 MonoBasicBlock *bb;
3331 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
3332 mono_print_bb (bb, msg);
3335 #ifndef DISABLE_JIT
3337 static void
3338 mono_postprocess_patches (MonoCompile *cfg)
3340 MonoJumpInfo *patch_info;
3341 int i;
3343 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3344 switch (patch_info->type) {
3345 case MONO_PATCH_INFO_ABS: {
3346 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
3349 * Change patches of type MONO_PATCH_INFO_ABS into patches describing the
3350 * absolute address.
3352 if (info) {
3353 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
3354 // FIXME: CLEAN UP THIS MESS.
3355 if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) &&
3356 strstr (cfg->method->name, info->name)) {
3358 * This is an icall wrapper, and this is a call to the
3359 * wrapped function.
3361 if (cfg->compile_aot) {
3362 patch_info->type = MONO_PATCH_INFO_JIT_ICALL_ADDR;
3363 patch_info->data.name = info->name;
3365 } else {
3366 /* for these array methods we currently register the same function pointer
3367 * since it's a vararg function. But this means that mono_find_jit_icall_by_addr ()
3368 * will return the incorrect one depending on the order they are registered.
3369 * See tests/test-arr.cs
3371 if (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL) {
3372 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
3373 patch_info->data.name = info->name;
3378 if (patch_info->type == MONO_PATCH_INFO_ABS) {
3379 if (cfg->abs_patches) {
3380 MonoJumpInfo *abs_ji = g_hash_table_lookup (cfg->abs_patches, patch_info->data.target);
3381 if (abs_ji) {
3382 patch_info->type = abs_ji->type;
3383 patch_info->data.target = abs_ji->data.target;
3388 break;
3390 case MONO_PATCH_INFO_SWITCH: {
3391 gpointer *table;
3392 #if defined(__native_client__) && defined(__native_client_codegen__)
3393 /* This memory will leak. */
3394 /* TODO: can we free this when */
3395 /* making the final jump table? */
3396 table = g_malloc0 (sizeof(gpointer) * patch_info->data.table->table_size);
3397 #else
3398 if (cfg->method->dynamic) {
3399 table = mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
3400 } else {
3401 table = mono_domain_code_reserve (cfg->domain, sizeof (gpointer) * patch_info->data.table->table_size);
3403 #endif
3405 for (i = 0; i < patch_info->data.table->table_size; i++) {
3406 /* Might be NULL if the switch is eliminated */
3407 if (patch_info->data.table->table [i]) {
3408 g_assert (patch_info->data.table->table [i]->native_offset);
3409 table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
3410 } else {
3411 table [i] = NULL;
3414 patch_info->data.table->table = (MonoBasicBlock**)table;
3415 break;
3417 case MONO_PATCH_INFO_METHOD_JUMP: {
3418 MonoJumpList *jlist;
3419 MonoDomain *domain = cfg->domain;
3420 unsigned char *ip = cfg->native_code + patch_info->ip.i;
3421 #if defined(__native_client__) && defined(__native_client_codegen__)
3422 /* When this jump target gets evaluated, the method */
3423 /* will be installed in the dynamic code section, */
3424 /* not at the location of cfg->native_code. */
3425 ip = nacl_inverse_modify_patch_target (cfg->native_code) + patch_info->ip.i;
3426 #endif
3428 mono_domain_lock (domain);
3429 jlist = g_hash_table_lookup (domain_jit_info (domain)->jump_target_hash, patch_info->data.method);
3430 if (!jlist) {
3431 jlist = mono_domain_alloc0 (domain, sizeof (MonoJumpList));
3432 g_hash_table_insert (domain_jit_info (domain)->jump_target_hash, patch_info->data.method, jlist);
3434 jlist->list = g_slist_prepend (jlist->list, ip);
3435 mono_domain_unlock (domain);
3436 break;
3438 default:
3439 /* do nothing */
3440 break;
3445 static void
3446 collect_pred_seq_points (MonoBasicBlock *bb, MonoInst *ins, GSList **next, int depth)
3448 int i;
3449 MonoBasicBlock *in_bb;
3450 GSList *l;
3452 for (i = 0; i < bb->in_count; ++i) {
3453 in_bb = bb->in_bb [i];
3455 if (in_bb->last_seq_point) {
3456 int src_index = in_bb->last_seq_point->backend.size;
3457 int dst_index = ins->backend.size;
3459 /* bb->in_bb might contain duplicates */
3460 for (l = next [src_index]; l; l = l->next)
3461 if (GPOINTER_TO_UINT (l->data) == dst_index)
3462 break;
3463 if (!l)
3464 next [src_index] = g_slist_append (next [src_index], GUINT_TO_POINTER (dst_index));
3465 } else {
3466 /* Have to look at its predecessors */
3467 if (depth < 5)
3468 collect_pred_seq_points (in_bb, ins, next, depth + 1);
3473 static void
3474 mono_save_seq_point_info (MonoCompile *cfg)
3476 MonoBasicBlock *bb;
3477 GSList *bb_seq_points, *l;
3478 MonoInst *last;
3479 MonoDomain *domain = cfg->domain;
3480 int i;
3481 MonoSeqPointInfo *info;
3482 GSList **next;
3484 if (!cfg->seq_points)
3485 return;
3487 info = g_malloc0 (sizeof (MonoSeqPointInfo) + (cfg->seq_points->len - MONO_ZERO_LEN_ARRAY) * sizeof (SeqPoint));
3488 info->len = cfg->seq_points->len;
3489 for (i = 0; i < cfg->seq_points->len; ++i) {
3490 SeqPoint *sp = &info->seq_points [i];
3491 MonoInst *ins = g_ptr_array_index (cfg->seq_points, i);
3493 sp->il_offset = ins->inst_imm;
3494 sp->native_offset = ins->inst_offset;
3496 /* Used below */
3497 ins->backend.size = i;
3501 * For each sequence point, compute the list of sequence points immediately
3502 * following it, this is needed to implement 'step over' in the debugger agent.
3504 next = g_new0 (GSList*, cfg->seq_points->len);
3505 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3506 bb_seq_points = g_slist_reverse (bb->seq_points);
3507 last = NULL;
3508 for (l = bb_seq_points; l; l = l->next) {
3509 MonoInst *ins = l->data;
3511 if (ins->inst_imm == METHOD_ENTRY_IL_OFFSET || ins->inst_imm == METHOD_EXIT_IL_OFFSET)
3512 /* Used to implement method entry/exit events */
3513 continue;
3515 if (last != NULL) {
3516 /* Link with the previous seq point in the same bb */
3517 next [last->backend.size] = g_slist_append (next [last->backend.size], GUINT_TO_POINTER (ins->backend.size));
3518 } else {
3519 /* Link with the last bb in the previous bblocks */
3520 collect_pred_seq_points (bb, ins, next, 0);
3523 last = ins;
3527 if (cfg->verbose_level > 2) {
3528 printf ("\nSEQ POINT MAP: \n");
3531 for (i = 0; i < cfg->seq_points->len; ++i) {
3532 SeqPoint *sp = &info->seq_points [i];
3533 GSList *l;
3534 int j, next_index;
3536 sp->next_len = g_slist_length (next [i]);
3537 sp->next = g_new (int, sp->next_len);
3538 j = 0;
3539 if (cfg->verbose_level > 2 && next [i]) {
3540 printf ("\t0x%x ->", sp->il_offset);
3541 for (l = next [i]; l; l = l->next) {
3542 next_index = GPOINTER_TO_UINT (l->data);
3543 printf (" 0x%x", info->seq_points [next_index].il_offset);
3545 printf ("\n");
3547 for (l = next [i]; l; l = l->next) {
3548 next_index = GPOINTER_TO_UINT (l->data);
3549 sp->next [j ++] = next_index;
3551 g_slist_free (next [i]);
3553 g_free (next);
3555 cfg->seq_point_info = info;
3557 // FIXME: dynamic methods
3558 if (!cfg->compile_aot) {
3559 mono_domain_lock (domain);
3560 // FIXME: How can the lookup succeed ?
3561 if (!g_hash_table_lookup (domain_jit_info (domain)->seq_points, cfg->method_to_register))
3562 g_hash_table_insert (domain_jit_info (domain)->seq_points, cfg->method_to_register, info);
3563 mono_domain_unlock (domain);
3566 g_ptr_array_free (cfg->seq_points, TRUE);
3567 cfg->seq_points = NULL;
3570 void
3571 mono_codegen (MonoCompile *cfg)
3573 MonoBasicBlock *bb;
3574 int max_epilog_size;
3575 guint8 *code;
3576 MonoDomain *code_domain;
3578 if (mono_using_xdebug)
3580 * Recent gdb versions have trouble processing symbol files containing
3581 * overlapping address ranges, so allocate all code from the code manager
3582 * of the root domain. (#666152).
3584 code_domain = mono_get_root_domain ();
3585 else
3586 code_domain = cfg->domain;
3588 #if defined(__native_client_codegen__) && defined(__native_client__)
3589 void *code_dest;
3591 /* This keeps patch targets from being transformed during
3592 * ordinary method compilation, for local branches and jumps.
3594 nacl_allow_target_modification (FALSE);
3595 #endif
3597 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3598 cfg->spill_count = 0;
3599 /* we reuse dfn here */
3600 /* bb->dfn = bb_count++; */
3602 mono_arch_lowering_pass (cfg, bb);
3604 if (cfg->opt & MONO_OPT_PEEPHOLE)
3605 mono_arch_peephole_pass_1 (cfg, bb);
3607 if (!cfg->globalra)
3608 mono_local_regalloc (cfg, bb);
3610 if (cfg->opt & MONO_OPT_PEEPHOLE)
3611 mono_arch_peephole_pass_2 (cfg, bb);
3614 if (cfg->prof_options & MONO_PROFILE_COVERAGE)
3615 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
3617 code = mono_arch_emit_prolog (cfg);
3619 if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
3620 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
3622 cfg->code_len = code - cfg->native_code;
3623 cfg->prolog_end = cfg->code_len;
3625 mono_debug_open_method (cfg);
3627 /* emit code all basic blocks */
3628 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3629 bb->native_offset = cfg->code_len;
3630 bb->real_native_offset = cfg->code_len;
3631 //if ((bb == cfg->bb_entry) || !(bb->region == -1 && !bb->dfn))
3632 mono_arch_output_basic_block (cfg, bb);
3633 bb->native_length = cfg->code_len - bb->native_offset;
3635 if (bb == cfg->bb_exit) {
3636 cfg->epilog_begin = cfg->code_len;
3638 if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
3639 code = cfg->native_code + cfg->code_len;
3640 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
3641 cfg->code_len = code - cfg->native_code;
3642 g_assert (cfg->code_len < cfg->code_size);
3645 mono_arch_emit_epilog (cfg);
3649 #ifdef __native_client_codegen__
3650 mono_nacl_fix_patches (cfg->native_code, cfg->patch_info);
3651 #endif
3652 mono_arch_emit_exceptions (cfg);
3654 max_epilog_size = 0;
3656 /* we always allocate code in cfg->domain->code_mp to increase locality */
3657 cfg->code_size = cfg->code_len + max_epilog_size;
3658 /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
3660 if (cfg->method->dynamic) {
3661 guint unwindlen = 0;
3662 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
3663 unwindlen = mono_arch_unwindinfo_get_size (cfg->arch.unwindinfo);
3664 #endif
3665 /* Allocate the code into a separate memory pool so it can be freed */
3666 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
3667 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
3668 mono_domain_lock (cfg->domain);
3669 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
3670 mono_domain_unlock (cfg->domain);
3672 if (mono_using_xdebug)
3673 /* See the comment for cfg->code_domain */
3674 code = mono_domain_code_reserve (code_domain, cfg->code_size + unwindlen);
3675 else
3676 code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size + unwindlen);
3677 } else {
3678 guint unwindlen = 0;
3679 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
3680 unwindlen = mono_arch_unwindinfo_get_size (cfg->arch.unwindinfo);
3681 #endif
3682 code = mono_domain_code_reserve (code_domain, cfg->code_size + unwindlen);
3684 #if defined(__native_client_codegen__) && defined(__native_client__)
3685 nacl_allow_target_modification (TRUE);
3686 #endif
3688 g_assert (code);
3689 memcpy (code, cfg->native_code, cfg->code_len);
3690 #if defined(__default_codegen__)
3691 g_free (cfg->native_code);
3692 #elif defined(__native_client_codegen__)
3693 if (cfg->native_code_alloc) {
3694 g_free (cfg->native_code_alloc);
3695 cfg->native_code_alloc = 0;
3697 else if (cfg->native_code) {
3698 g_free (cfg->native_code);
3700 #endif /* __native_client_codegen__ */
3701 cfg->native_code = code;
3702 code = cfg->native_code + cfg->code_len;
3704 /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
3705 mono_postprocess_patches (cfg);
3707 #ifdef VALGRIND_JIT_REGISTER_MAP
3708 if (valgrind_register){
3709 char* nm = mono_method_full_name (cfg->method, TRUE);
3710 VALGRIND_JIT_REGISTER_MAP (nm, cfg->native_code, cfg->native_code + cfg->code_len);
3711 g_free (nm);
3713 #endif
3715 if (cfg->verbose_level > 0) {
3716 char* nm = mono_method_full_name (cfg->method, TRUE);
3717 g_print ("Method %s emitted at %p to %p (code length %d) [%s]\n",
3718 nm,
3719 cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
3720 g_free (nm);
3724 gboolean is_generic = FALSE;
3726 if (cfg->method->is_inflated || mono_method_get_generic_container (cfg->method) ||
3727 cfg->method->klass->generic_container || cfg->method->klass->generic_class) {
3728 is_generic = TRUE;
3731 if (cfg->generic_sharing_context)
3732 g_assert (is_generic);
3735 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
3736 mono_arch_save_unwind_info (cfg);
3737 #endif
3739 #if defined(__native_client_codegen__) && defined(__native_client__)
3740 if (!cfg->compile_aot) {
3741 if (cfg->method->dynamic) {
3742 code_dest = nacl_code_manager_get_code_dest(cfg->dynamic_info->code_mp, cfg->native_code);
3743 } else {
3744 code_dest = nacl_domain_get_code_dest(cfg->domain, cfg->native_code);
3747 #endif
3749 #if defined(__native_client_codegen__)
3750 mono_nacl_fix_patches (cfg->native_code, cfg->patch_info);
3751 #endif
3753 mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->dynamic_info ? cfg->dynamic_info->code_mp : NULL, cfg->run_cctors);
3755 if (cfg->method->dynamic) {
3756 if (mono_using_xdebug)
3757 mono_domain_code_commit (code_domain, cfg->native_code, cfg->code_size, cfg->code_len);
3758 else
3759 mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
3760 } else {
3761 mono_domain_code_commit (code_domain, cfg->native_code, cfg->code_size, cfg->code_len);
3763 #if defined(__native_client_codegen__) && defined(__native_client__)
3764 cfg->native_code = code_dest;
3765 #endif
3766 mono_profiler_code_buffer_new (cfg->native_code, cfg->code_len, MONO_PROFILER_CODE_BUFFER_METHOD, cfg->method);
3768 mono_arch_flush_icache (cfg->native_code, cfg->code_len);
3770 mono_debug_close_method (cfg);
3772 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
3773 mono_arch_unwindinfo_install_unwind_info (&cfg->arch.unwindinfo, cfg->native_code, cfg->code_len);
3774 #endif
3777 static void
3778 compute_reachable (MonoBasicBlock *bb)
3780 int i;
3782 if (!(bb->flags & BB_VISITED)) {
3783 bb->flags |= BB_VISITED;
3784 for (i = 0; i < bb->out_count; ++i)
3785 compute_reachable (bb->out_bb [i]);
3789 static void
3790 mono_handle_out_of_line_bblock (MonoCompile *cfg)
3792 MonoBasicBlock *bb;
3793 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
3794 if (bb->next_bb && bb->next_bb->out_of_line && bb->last_ins && !MONO_IS_BRANCH_OP (bb->last_ins)) {
3795 MonoInst *ins;
3796 MONO_INST_NEW (cfg, ins, OP_BR);
3797 MONO_ADD_INS (bb, ins);
3798 ins->inst_target_bb = bb->next_bb;
3803 static MonoJitInfo*
3804 create_jit_info (MonoCompile *cfg, MonoMethod *method_to_compile)
3806 GSList *tmp;
3807 MonoMethodHeader *header;
3808 MonoJitInfo *jinfo;
3809 int num_clauses;
3810 int generic_info_size, arch_eh_info_size = 0;
3811 int holes_size = 0, num_holes = 0;
3812 guint32 stack_size = 0;
3814 g_assert (method_to_compile == cfg->method);
3815 header = cfg->header;
3817 if (cfg->generic_sharing_context)
3818 generic_info_size = sizeof (MonoGenericJitInfo);
3819 else
3820 generic_info_size = 0;
3822 if (cfg->arch_eh_jit_info) {
3823 MonoJitArgumentInfo *arg_info;
3824 MonoMethodSignature *sig = mono_method_signature (cfg->method_to_register);
3827 * This cannot be computed during stack walking, as
3828 * mono_arch_get_argument_info () is not signal safe.
3830 arg_info = g_newa (MonoJitArgumentInfo, sig->param_count + 1);
3831 stack_size = mono_arch_get_argument_info (sig, sig->param_count, arg_info);
3833 if (stack_size)
3834 arch_eh_info_size = sizeof (MonoArchEHJitInfo);
3837 if (cfg->try_block_holes) {
3838 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
3839 TryBlockHole *hole = tmp->data;
3840 MonoExceptionClause *ec = hole->clause;
3841 int hole_end = hole->basic_block->native_offset + hole->basic_block->native_length;
3842 MonoBasicBlock *clause_last_bb = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
3843 g_assert (clause_last_bb);
3845 /* Holes at the end of a try region can be represented by simply reducing the size of the block itself.*/
3846 if (clause_last_bb->native_offset != hole_end)
3847 ++num_holes;
3849 if (num_holes)
3850 holes_size = sizeof (MonoTryBlockHoleTableJitInfo) + num_holes * sizeof (MonoTryBlockHoleJitInfo);
3851 if (G_UNLIKELY (cfg->verbose_level >= 4))
3852 printf ("Number of try block holes %d\n", num_holes);
3855 if (COMPILE_LLVM (cfg))
3856 num_clauses = cfg->llvm_ex_info_len;
3857 else
3858 num_clauses = header->num_clauses;
3860 if (cfg->method->dynamic) {
3861 jinfo = g_malloc0 (MONO_SIZEOF_JIT_INFO + (num_clauses * sizeof (MonoJitExceptionInfo)) +
3862 generic_info_size + holes_size + arch_eh_info_size);
3863 } else {
3864 jinfo = mono_domain_alloc0 (cfg->domain, MONO_SIZEOF_JIT_INFO +
3865 (num_clauses * sizeof (MonoJitExceptionInfo)) +
3866 generic_info_size + holes_size + arch_eh_info_size);
3869 jinfo->method = cfg->method_to_register;
3870 jinfo->code_start = cfg->native_code;
3871 jinfo->code_size = cfg->code_len;
3872 jinfo->used_regs = cfg->used_int_regs;
3873 jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
3874 jinfo->cas_inited = FALSE; /* initialization delayed at the first stalk walk using this method */
3875 jinfo->num_clauses = num_clauses;
3876 if (COMPILE_LLVM (cfg))
3877 jinfo->from_llvm = TRUE;
3879 if (cfg->generic_sharing_context) {
3880 MonoInst *inst;
3881 MonoGenericJitInfo *gi;
3883 jinfo->has_generic_jit_info = 1;
3885 gi = mono_jit_info_get_generic_jit_info (jinfo);
3886 g_assert (gi);
3888 gi->generic_sharing_context = cfg->generic_sharing_context;
3890 if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
3891 mini_method_get_context (method_to_compile)->method_inst ||
3892 method_to_compile->klass->valuetype) {
3893 g_assert (cfg->rgctx_var);
3896 gi->has_this = 1;
3898 if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
3899 mini_method_get_context (method_to_compile)->method_inst ||
3900 method_to_compile->klass->valuetype) {
3901 inst = cfg->rgctx_var;
3902 if (!COMPILE_LLVM (cfg))
3903 g_assert (inst->opcode == OP_REGOFFSET);
3904 } else {
3905 inst = cfg->args [0];
3908 if (COMPILE_LLVM (cfg)) {
3909 g_assert (cfg->llvm_this_reg != -1);
3910 gi->this_in_reg = 0;
3911 gi->this_reg = cfg->llvm_this_reg;
3912 gi->this_offset = cfg->llvm_this_offset;
3913 } else if (inst->opcode == OP_REGVAR) {
3914 gi->this_in_reg = 1;
3915 gi->this_reg = inst->dreg;
3916 } else {
3917 g_assert (inst->opcode == OP_REGOFFSET);
3918 #ifdef TARGET_X86
3919 g_assert (inst->inst_basereg == X86_EBP);
3920 #elif defined(TARGET_AMD64)
3921 g_assert (inst->inst_basereg == X86_EBP || inst->inst_basereg == X86_ESP);
3922 #endif
3923 g_assert (inst->inst_offset >= G_MININT32 && inst->inst_offset <= G_MAXINT32);
3925 gi->this_in_reg = 0;
3926 gi->this_reg = inst->inst_basereg;
3927 gi->this_offset = inst->inst_offset;
3931 if (num_holes) {
3932 MonoTryBlockHoleTableJitInfo *table;
3933 int i;
3935 jinfo->has_try_block_holes = 1;
3936 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3937 table->num_holes = (guint16)num_holes;
3938 i = 0;
3939 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
3940 guint32 start_bb_offset;
3941 MonoTryBlockHoleJitInfo *hole;
3942 TryBlockHole *hole_data = tmp->data;
3943 MonoExceptionClause *ec = hole_data->clause;
3944 int hole_end = hole_data->basic_block->native_offset + hole_data->basic_block->native_length;
3945 MonoBasicBlock *clause_last_bb = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
3946 g_assert (clause_last_bb);
3948 /* Holes at the end of a try region can be represented by simply reducing the size of the block itself.*/
3949 if (clause_last_bb->native_offset == hole_end)
3950 continue;
3952 start_bb_offset = hole_data->start_offset - hole_data->basic_block->native_offset;
3953 hole = &table->holes [i++];
3954 hole->clause = hole_data->clause - &header->clauses [0];
3955 hole->offset = (guint32)hole_data->start_offset;
3956 hole->length = (guint16)(hole_data->basic_block->native_length - start_bb_offset);
3958 if (G_UNLIKELY (cfg->verbose_level >= 4))
3959 printf ("\tTry block hole at eh clause %d offset %x length %x\n", hole->clause, hole->offset, hole->length);
3961 g_assert (i == num_holes);
3964 if (arch_eh_info_size) {
3965 MonoArchEHJitInfo *info;
3967 jinfo->has_arch_eh_info = 1;
3968 info = mono_jit_info_get_arch_eh_info (jinfo);
3970 info->stack_size = stack_size;
3973 if (COMPILE_LLVM (cfg)) {
3974 if (num_clauses)
3975 memcpy (&jinfo->clauses [0], &cfg->llvm_ex_info [0], num_clauses * sizeof (MonoJitExceptionInfo));
3976 } else if (header->num_clauses) {
3977 int i;
3979 for (i = 0; i < header->num_clauses; i++) {
3980 MonoExceptionClause *ec = &header->clauses [i];
3981 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
3982 MonoBasicBlock *tblock;
3983 MonoInst *exvar;
3985 ei->flags = ec->flags;
3987 exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
3988 ei->exvar_offset = exvar ? exvar->inst_offset : 0;
3990 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
3991 tblock = cfg->cil_offset_to_bb [ec->data.filter_offset];
3992 g_assert (tblock);
3993 ei->data.filter = cfg->native_code + tblock->native_offset;
3994 } else {
3995 ei->data.catch_class = ec->data.catch_class;
3998 tblock = cfg->cil_offset_to_bb [ec->try_offset];
3999 g_assert (tblock);
4000 g_assert (tblock->native_offset);
4001 ei->try_start = cfg->native_code + tblock->native_offset;
4002 if (tblock->extend_try_block) {
4004 * Extend the try block backwards to include parts of the previous call
4005 * instruction.
4007 ei->try_start = (guint8*)ei->try_start - MONO_ARCH_MONITOR_ENTER_ADJUSTMENT;
4009 tblock = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
4010 g_assert (tblock);
4011 if (!tblock->native_offset) {
4012 int j, end;
4013 for (j = ec->try_offset + ec->try_len, end = ec->try_offset; j >= end; --j) {
4014 MonoBasicBlock *bb = cfg->cil_offset_to_bb [j];
4015 if (bb && bb->native_offset) {
4016 tblock = bb;
4017 break;
4021 ei->try_end = cfg->native_code + tblock->native_offset;
4022 g_assert (tblock->native_offset);
4023 tblock = cfg->cil_offset_to_bb [ec->handler_offset];
4024 g_assert (tblock);
4025 ei->handler_start = cfg->native_code + tblock->native_offset;
4027 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
4028 TryBlockHole *hole = tmp->data;
4029 gpointer hole_end = cfg->native_code + (hole->basic_block->native_offset + hole->basic_block->native_length);
4030 if (hole->clause == ec && hole_end == ei->try_end) {
4031 if (G_UNLIKELY (cfg->verbose_level >= 4))
4032 printf ("\tShortening try block %d from %x to %x\n", i, (int)((guint8*)ei->try_end - cfg->native_code), hole->start_offset);
4034 ei->try_end = cfg->native_code + hole->start_offset;
4035 break;
4039 if (ec->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
4040 int end_offset;
4041 if (ec->handler_offset + ec->handler_len < header->code_size) {
4042 tblock = cfg->cil_offset_to_bb [ec->handler_offset + ec->handler_len];
4043 g_assert (tblock);
4044 end_offset = tblock->native_offset;
4045 } else {
4046 end_offset = cfg->epilog_begin;
4048 ei->data.handler_end = cfg->native_code + end_offset;
4053 if (G_UNLIKELY (cfg->verbose_level >= 4)) {
4054 int i;
4055 for (i = 0; i < jinfo->num_clauses; i++) {
4056 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
4057 int start = (guint8*)ei->try_start - cfg->native_code;
4058 int end = (guint8*)ei->try_end - cfg->native_code;
4059 int handler = (guint8*)ei->handler_start - cfg->native_code;
4061 printf ("JitInfo EH clause %d flags %x try %x-%x handler %x\n", i, ei->flags, start, end, handler);
4066 * Its possible to generate dwarf unwind info for xdebug etc, but not actually
4067 * using it during runtime, hence the define.
4069 #ifdef MONO_ARCH_HAVE_XP_UNWIND
4070 if (cfg->encoded_unwind_ops) {
4071 jinfo->used_regs = mono_cache_unwind_info (cfg->encoded_unwind_ops, cfg->encoded_unwind_ops_len);
4072 g_free (cfg->encoded_unwind_ops);
4073 } else if (cfg->unwind_ops) {
4074 guint32 info_len;
4075 guint8 *unwind_info = mono_unwind_ops_encode (cfg->unwind_ops, &info_len);
4077 jinfo->used_regs = mono_cache_unwind_info (unwind_info, info_len);
4078 g_free (unwind_info);
4080 #endif
4082 return jinfo;
4084 #endif
4087 * mini_get_shared_method:
4089 * Return the method which is actually compiled/registered when doing generic sharing.
4091 MonoMethod*
4092 mini_get_shared_method (MonoMethod *method)
4094 MonoGenericContext shared_context;
4095 MonoMethod *declaring_method, *res;
4096 int i;
4097 gboolean partial = FALSE;
4099 if (method->is_generic || method->klass->generic_container)
4100 declaring_method = method;
4101 else
4102 declaring_method = mono_method_get_declaring_generic_method (method);
4104 if (declaring_method->is_generic)
4105 shared_context = mono_method_get_generic_container (declaring_method)->context;
4106 else
4107 shared_context = declaring_method->klass->generic_container->context;
4109 /* Handle partial sharing */
4110 if (method != declaring_method && method->is_inflated && !mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE)) {
4111 MonoGenericContext *context = mono_method_get_context (method);
4112 MonoGenericInst *inst;
4113 MonoType **type_argv;
4116 * Create the shared context by replacing the ref type arguments with
4117 * type parameters, and keeping the rest.
4119 partial = TRUE;
4120 inst = context->class_inst;
4121 if (inst) {
4122 type_argv = g_new0 (MonoType*, inst->type_argc);
4123 for (i = 0; i < inst->type_argc; ++i) {
4124 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)
4125 type_argv [i] = shared_context.class_inst->type_argv [i];
4126 else
4127 type_argv [i] = inst->type_argv [i];
4130 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4131 g_free (type_argv);
4134 inst = context->method_inst;
4135 if (inst) {
4136 type_argv = g_new0 (MonoType*, inst->type_argc);
4137 for (i = 0; i < inst->type_argc; ++i) {
4138 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)
4139 type_argv [i] = shared_context.method_inst->type_argv [i];
4140 else
4141 type_argv [i] = inst->type_argv [i];
4144 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
4145 g_free (type_argv);
4149 res = mono_class_inflate_generic_method (declaring_method, &shared_context);
4150 if (!partial) {
4151 /* The result should be an inflated method whose parent is not inflated */
4152 g_assert (!res->klass->is_inflated);
4154 return res;
4157 #ifndef DISABLE_JIT
4159 * mini_method_compile:
4160 * @method: the method to compile
4161 * @opts: the optimization flags to use
4162 * @domain: the domain where the method will be compiled in
4163 * @run_cctors: whether we should run type ctors if possible
4164 * @compile_aot: whether this is an AOT compilation
4165 * @parts: debug flag
4167 * Returns: a MonoCompile* pointer. Caller must check the exception_type
4168 * field in the returned struct to see if compilation succeded.
4170 MonoCompile*
4171 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
4173 MonoMethodHeader *header;
4174 MonoMethodSignature *sig;
4175 MonoError err;
4176 guint8 *ip;
4177 MonoCompile *cfg;
4178 int dfn, i, code_size_ratio;
4179 gboolean deadce_has_run = FALSE;
4180 gboolean try_generic_shared, try_llvm = FALSE;
4181 MonoMethod *method_to_compile, *method_to_register;
4183 InterlockedIncrement (&mono_jit_stats.methods_compiled);
4184 if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
4185 mono_profiler_method_jit (method);
4186 if (MONO_PROBE_METHOD_COMPILE_BEGIN_ENABLED ())
4187 MONO_PROBE_METHOD_COMPILE_BEGIN (method);
4189 if (compile_aot)
4191 * We might get passed the original generic method definition or
4192 * instances with type parameters.
4193 * FIXME: Remove the method->klass->generic_class limitation.
4195 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
4196 (opts & MONO_OPT_GSHARED) && ((method->is_generic || method->klass->generic_container) || (!method->klass->generic_class && mono_method_is_generic_sharable_impl (method, TRUE)));
4197 else
4198 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
4199 (opts & MONO_OPT_GSHARED) && mono_method_is_generic_sharable_impl (method, FALSE);
4201 if (opts & MONO_OPT_GSHARED) {
4202 if (try_generic_shared)
4203 mono_stats.generics_sharable_methods++;
4204 else if (mono_method_is_generic_impl (method))
4205 mono_stats.generics_unsharable_methods++;
4208 #ifdef ENABLE_LLVM
4209 try_llvm = mono_use_llvm;
4210 #endif
4212 restart_compile:
4213 if (try_generic_shared) {
4214 method_to_compile = mini_get_shared_method (method);
4215 g_assert (method_to_compile);
4216 } else {
4217 method_to_compile = method;
4220 cfg = g_new0 (MonoCompile, 1);
4221 cfg->method = method_to_compile;
4222 cfg->header = mono_method_get_header (cfg->method);
4223 cfg->mempool = mono_mempool_new ();
4224 cfg->opt = opts;
4225 cfg->prof_options = mono_profiler_get_events ();
4226 cfg->run_cctors = run_cctors;
4227 cfg->domain = domain;
4228 cfg->verbose_level = mini_verbose;
4229 cfg->compile_aot = compile_aot;
4230 cfg->skip_visibility = method->skip_visibility;
4231 cfg->orig_method = method;
4232 cfg->gen_seq_points = debug_options.gen_seq_points;
4233 cfg->explicit_null_checks = debug_options.explicit_null_checks;
4234 cfg->soft_breakpoints = debug_options.soft_breakpoints;
4235 if (try_generic_shared)
4236 cfg->generic_sharing_context = (MonoGenericSharingContext*)&cfg->generic_sharing_context;
4237 cfg->compile_llvm = try_llvm;
4238 cfg->token_info_hash = g_hash_table_new (NULL, NULL);
4240 if (cfg->gen_seq_points)
4241 cfg->seq_points = g_ptr_array_new ();
4243 if (cfg->compile_aot && !try_generic_shared && (method->is_generic || method->klass->generic_container)) {
4244 cfg->exception_type = MONO_EXCEPTION_GENERIC_SHARING_FAILED;
4245 return cfg;
4248 if (cfg->generic_sharing_context) {
4249 method_to_register = method_to_compile;
4250 } else {
4251 g_assert (method == method_to_compile);
4252 method_to_register = method;
4254 cfg->method_to_register = method_to_register;
4256 mono_error_init (&err);
4257 sig = mono_method_signature_checked (cfg->method, &err);
4258 if (!sig) {
4259 cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
4260 cfg->exception_message = g_strdup (mono_error_get_message (&err));
4261 mono_error_cleanup (&err);
4262 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4263 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
4264 return cfg;
4267 header = cfg->header;
4268 if (!header) {
4269 MonoLoaderError *error;
4271 if ((error = mono_loader_get_last_error ())) {
4272 cfg->exception_type = error->exception_type;
4273 } else {
4274 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
4275 cfg->exception_message = g_strdup_printf ("Missing or incorrect header for method %s", cfg->method->name);
4277 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4278 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
4279 return cfg;
4282 #ifdef ENABLE_LLVM
4284 static gboolean inited;
4286 if (!inited) {
4287 inited = TRUE;
4291 * Check for methods which cannot be compiled by LLVM early, to avoid
4292 * the extra compilation pass.
4294 if (COMPILE_LLVM (cfg)) {
4295 mono_llvm_check_method_supported (cfg);
4296 if (cfg->disable_llvm) {
4297 if (cfg->verbose_level >= 1) {
4298 //nm = mono_method_full_name (cfg->method, TRUE);
4299 printf ("LLVM failed for '%s': %s\n", method->name, cfg->exception_message);
4300 //g_free (nm);
4302 mono_destroy_compile (cfg);
4303 try_llvm = FALSE;
4304 goto restart_compile;
4308 #endif
4310 /* The debugger has no liveness information, so avoid sharing registers/stack slots */
4311 if (mono_debug_using_mono_debugger () || debug_options.mdb_optimizations) {
4312 cfg->disable_reuse_registers = TRUE;
4313 cfg->disable_reuse_stack_slots = TRUE;
4315 * This decreases the change the debugger will read registers/stack slots which are
4316 * not yet initialized.
4318 cfg->disable_initlocals_opt = TRUE;
4320 cfg->extend_live_ranges = TRUE;
4322 /* Temporarily disable this when running in the debugger until we have support
4323 * for this in the debugger. */
4324 cfg->disable_omit_fp = TRUE;
4326 /* The debugger needs all locals to be on the stack or in a global register */
4327 cfg->disable_vreg_to_lvreg = TRUE;
4329 /* Don't remove unused variables when running inside the debugger since the user
4330 * may still want to view them. */
4331 cfg->disable_deadce_vars = TRUE;
4333 // cfg->opt |= MONO_OPT_SHARED;
4334 cfg->opt &= ~MONO_OPT_DEADCE;
4335 cfg->opt &= ~MONO_OPT_INLINE;
4336 cfg->opt &= ~MONO_OPT_COPYPROP;
4337 cfg->opt &= ~MONO_OPT_CONSPROP;
4338 cfg->opt &= ~MONO_OPT_GSHARED;
4340 /* This is needed for the soft debugger, which doesn't like code after the epilog */
4341 cfg->disable_out_of_line_bblocks = TRUE;
4344 if (mono_using_xdebug) {
4346 * Make each variable use its own register/stack slot and extend
4347 * their liveness to cover the whole method, making them displayable
4348 * in gdb even after they are dead.
4350 cfg->disable_reuse_registers = TRUE;
4351 cfg->disable_reuse_stack_slots = TRUE;
4352 cfg->extend_live_ranges = TRUE;
4353 cfg->compute_precise_live_ranges = TRUE;
4356 mini_gc_init_cfg (cfg);
4358 if (COMPILE_LLVM (cfg)) {
4359 cfg->opt |= MONO_OPT_ABCREM;
4362 if (getenv ("MONO_VERBOSE_METHOD")) {
4363 char *name = getenv ("MONO_VERBOSE_METHOD");
4365 if ((strchr (name, '.') > name) || strchr (name, ':')) {
4366 MonoMethodDesc *desc;
4368 desc = mono_method_desc_new (name, TRUE);
4369 if (mono_method_desc_full_match (desc, cfg->method)) {
4370 cfg->verbose_level = 4;
4372 mono_method_desc_free (desc);
4373 } else {
4374 if (strcmp (cfg->method->name, getenv ("MONO_VERBOSE_METHOD")) == 0)
4375 cfg->verbose_level = 4;
4379 ip = (guint8 *)header->code;
4381 cfg->intvars = mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * header->max_stack);
4383 if (cfg->verbose_level > 0) {
4384 char *method_name;
4385 if (COMPILE_LLVM (cfg))
4386 g_print ("converting llvm method %s\n", method_name = mono_method_full_name (method, TRUE));
4387 else if (cfg->generic_sharing_context)
4388 g_print ("converting shared method %s\n", method_name = mono_method_full_name (method_to_compile, TRUE));
4389 else
4390 g_print ("converting method %s\n", method_name = mono_method_full_name (method, TRUE));
4391 g_free (method_name);
4394 if (cfg->opt & (MONO_OPT_ABCREM | MONO_OPT_SSAPRE))
4395 cfg->opt |= MONO_OPT_SSA;
4398 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")))
4399 cfg->globalra = TRUE;
4402 //cfg->globalra = TRUE;
4404 //if (!strcmp (cfg->method->klass->name, "Tests") && !cfg->method->wrapper_type)
4405 // cfg->globalra = TRUE;
4408 static int count = 0;
4409 count ++;
4412 if (getenv ("COUNT2")) {
4413 cfg->globalra = TRUE;
4414 if (count == atoi (getenv ("COUNT2")))
4415 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
4416 if (count > atoi (getenv ("COUNT2")))
4417 cfg->globalra = FALSE;
4422 if (header->clauses)
4423 cfg->globalra = FALSE;
4425 if (cfg->method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED)
4426 /* The code in the prolog clobbers caller saved registers */
4427 cfg->globalra = FALSE;
4429 // FIXME: Disable globalra in case of tracing/profiling
4431 if (cfg->method->save_lmf)
4432 /* The LMF saving code might clobber caller saved registers */
4433 cfg->globalra = FALSE;
4435 if (header->code_size > 5000)
4436 // FIXME:
4437 /* Too large bblocks could overflow the ins positions */
4438 cfg->globalra = FALSE;
4440 cfg->rs = mono_regstate_new ();
4441 if (cfg->globalra)
4442 cfg->rs->next_vreg = MONO_MAX_IREGS + MONO_MAX_FREGS;
4443 cfg->next_vreg = cfg->rs->next_vreg;
4445 /* FIXME: Fix SSA to handle branches inside bblocks */
4446 if (cfg->opt & MONO_OPT_SSA)
4447 cfg->enable_extended_bblocks = FALSE;
4450 * FIXME: This confuses liveness analysis because variables which are assigned after
4451 * a branch inside a bblock become part of the kill set, even though the assignment
4452 * might not get executed. This causes the optimize_initlocals pass to delete some
4453 * assignments which are needed.
4454 * Also, the mono_if_conversion pass needs to be modified to recognize the code
4455 * created by this.
4457 //cfg->enable_extended_bblocks = TRUE;
4459 /*We must verify the method before doing any IR generation as mono_compile_create_vars can assert.*/
4460 if (mono_compile_is_broken (cfg, cfg->method, TRUE)) {
4461 if (mini_get_debug_options ()->break_on_unverified)
4462 G_BREAKPOINT ();
4463 return cfg;
4467 * create MonoInst* which represents arguments and local variables
4469 mono_compile_create_vars (cfg);
4471 /* SSAPRE is not supported on linear IR */
4472 cfg->opt &= ~MONO_OPT_SSAPRE;
4474 i = mono_method_to_ir (cfg, method_to_compile, NULL, NULL, NULL, NULL, NULL, 0, FALSE);
4476 if (i < 0) {
4477 if (try_generic_shared && cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4478 if (compile_aot) {
4479 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4480 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
4481 return cfg;
4483 mono_destroy_compile (cfg);
4484 try_generic_shared = FALSE;
4485 goto restart_compile;
4487 g_assert (cfg->exception_type != MONO_EXCEPTION_GENERIC_SHARING_FAILED);
4489 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4490 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
4491 /* cfg contains the details of the failure, so let the caller cleanup */
4492 return cfg;
4495 cfg->stat_basic_blocks += cfg->num_bblocks;
4497 if (COMPILE_LLVM (cfg)) {
4498 MonoInst *ins;
4500 /* The IR has to be in SSA form for LLVM */
4501 cfg->opt |= MONO_OPT_SSA;
4503 // FIXME:
4504 if (cfg->ret) {
4505 // Allow SSA on the result value
4506 cfg->ret->flags &= ~MONO_INST_VOLATILE;
4508 // Add an explicit return instruction referencing the return value
4509 MONO_INST_NEW (cfg, ins, OP_SETRET);
4510 ins->sreg1 = cfg->ret->dreg;
4512 MONO_ADD_INS (cfg->bb_exit, ins);
4515 cfg->opt &= ~MONO_OPT_LINEARS;
4517 /* FIXME: */
4518 cfg->opt &= ~MONO_OPT_BRANCH;
4521 /* todo: remove code when we have verified that the liveness for try/catch blocks
4522 * works perfectly
4525 * Currently, this can't be commented out since exception blocks are not
4526 * processed during liveness analysis.
4527 * It is also needed, because otherwise the local optimization passes would
4528 * delete assignments in cases like this:
4529 * r1 <- 1
4530 * <something which throws>
4531 * r1 <- 2
4532 * This also allows SSA to be run on methods containing exception clauses, since
4533 * SSA will ignore variables marked VOLATILE.
4535 mono_liveness_handle_exception_clauses (cfg);
4537 mono_handle_out_of_line_bblock (cfg);
4539 /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
4541 if (!COMPILE_LLVM (cfg))
4542 mono_decompose_long_opts (cfg);
4544 /* Should be done before branch opts */
4545 if (cfg->opt & (MONO_OPT_CONSPROP | MONO_OPT_COPYPROP))
4546 mono_local_cprop (cfg);
4548 if (cfg->opt & MONO_OPT_BRANCH)
4549 mono_optimize_branches (cfg);
4551 /* This must be done _before_ global reg alloc and _after_ decompose */
4552 mono_handle_global_vregs (cfg);
4553 if (cfg->opt & MONO_OPT_DEADCE)
4554 mono_local_deadce (cfg);
4555 /* Disable this for LLVM to make the IR easier to handle */
4556 if (!COMPILE_LLVM (cfg))
4557 mono_if_conversion (cfg);
4559 if ((cfg->opt & MONO_OPT_SSAPRE) || cfg->globalra)
4560 mono_remove_critical_edges (cfg);
4562 /* Depth-first ordering on basic blocks */
4563 cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
4565 cfg->max_block_num = cfg->num_bblocks;
4567 dfn = 0;
4568 df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
4569 if (cfg->num_bblocks != dfn + 1) {
4570 MonoBasicBlock *bb;
4572 cfg->num_bblocks = dfn + 1;
4574 /* remove unreachable code, because the code in them may be
4575 * inconsistent (access to dead variables for example) */
4576 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4577 bb->flags &= ~BB_VISITED;
4578 compute_reachable (cfg->bb_entry);
4579 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4580 if (bb->flags & BB_EXCEPTION_HANDLER)
4581 compute_reachable (bb);
4582 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4583 if (!(bb->flags & BB_VISITED)) {
4584 if (cfg->verbose_level > 1)
4585 g_print ("found unreachable code in BB%d\n", bb->block_num);
4586 bb->code = bb->last_ins = NULL;
4587 while (bb->out_count)
4588 mono_unlink_bblock (cfg, bb, bb->out_bb [0]);
4591 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4592 bb->flags &= ~BB_VISITED;
4595 if (((cfg->num_varinfo > 2000) || (cfg->num_bblocks > 1000)) && !cfg->compile_aot) {
4597 * we disable some optimizations if there are too many variables
4598 * because JIT time may become too expensive. The actual number needs
4599 * to be tweaked and eventually the non-linear algorithms should be fixed.
4601 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
4602 cfg->disable_ssa = TRUE;
4605 if (cfg->opt & MONO_OPT_LOOP) {
4606 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
4607 mono_compute_natural_loops (cfg);
4610 /* after method_to_ir */
4611 if (parts == 1) {
4612 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4613 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
4614 return cfg;
4618 if (header->num_clauses)
4619 cfg->disable_ssa = TRUE;
4622 //#define DEBUGSSA "logic_run"
4623 #define DEBUGSSA_CLASS "Tests"
4624 #ifdef DEBUGSSA
4626 if (!cfg->disable_ssa) {
4627 mono_local_cprop (cfg);
4629 #ifndef DISABLE_SSA
4630 mono_ssa_compute (cfg);
4631 #endif
4633 #else
4634 if (cfg->opt & MONO_OPT_SSA) {
4635 if (!(cfg->comp_done & MONO_COMP_SSA) && !cfg->disable_ssa) {
4636 #ifndef DISABLE_SSA
4637 mono_ssa_compute (cfg);
4638 #endif
4640 if (cfg->verbose_level >= 2) {
4641 print_dfn (cfg);
4645 #endif
4647 /* after SSA translation */
4648 if (parts == 2) {
4649 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4650 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
4651 return cfg;
4654 if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
4655 if (cfg->comp_done & MONO_COMP_SSA && !COMPILE_LLVM (cfg)) {
4656 #ifndef DISABLE_SSA
4657 mono_ssa_cprop (cfg);
4658 #endif
4662 #ifndef DISABLE_SSA
4663 if (cfg->comp_done & MONO_COMP_SSA && !COMPILE_LLVM (cfg)) {
4664 //mono_ssa_strength_reduction (cfg);
4666 if (cfg->opt & MONO_OPT_SSAPRE) {
4667 mono_perform_ssapre (cfg);
4668 //mono_local_cprop (cfg);
4671 if (cfg->opt & MONO_OPT_DEADCE) {
4672 mono_ssa_deadce (cfg);
4673 deadce_has_run = TRUE;
4676 if ((cfg->flags & (MONO_CFG_HAS_LDELEMA|MONO_CFG_HAS_CHECK_THIS)) && (cfg->opt & MONO_OPT_ABCREM))
4677 mono_perform_abc_removal (cfg);
4679 mono_ssa_remove (cfg);
4680 mono_local_cprop (cfg);
4681 mono_handle_global_vregs (cfg);
4682 if (cfg->opt & MONO_OPT_DEADCE)
4683 mono_local_deadce (cfg);
4685 if (cfg->opt & MONO_OPT_BRANCH) {
4686 MonoBasicBlock *bb;
4688 mono_optimize_branches (cfg);
4690 /* Have to recompute cfg->bblocks and bb->dfn */
4691 if (cfg->globalra) {
4692 mono_remove_critical_edges (cfg);
4694 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4695 bb->dfn = 0;
4697 /* Depth-first ordering on basic blocks */
4698 cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
4700 dfn = 0;
4701 df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
4702 cfg->num_bblocks = dfn + 1;
4706 #endif
4708 if (cfg->comp_done & MONO_COMP_SSA && COMPILE_LLVM (cfg)) {
4709 /* This removes MONO_INST_FAULT flags too so perform it unconditionally */
4710 if (cfg->opt & MONO_OPT_ABCREM)
4711 mono_perform_abc_removal (cfg);
4714 /* after SSA removal */
4715 if (parts == 3) {
4716 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4717 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
4718 return cfg;
4721 #ifdef MONO_ARCH_SOFT_FLOAT
4722 if (!COMPILE_LLVM (cfg))
4723 mono_decompose_soft_float (cfg);
4724 #endif
4725 if (!COMPILE_LLVM (cfg))
4726 mono_decompose_vtype_opts (cfg);
4727 if (cfg->flags & MONO_CFG_HAS_ARRAY_ACCESS)
4728 mono_decompose_array_access_opts (cfg);
4730 if (cfg->got_var) {
4731 #ifndef MONO_ARCH_GOT_REG
4732 GList *regs;
4733 #endif
4734 int got_reg;
4736 g_assert (cfg->got_var_allocated);
4739 * Allways allocate the GOT var to a register, because keeping it
4740 * in memory will increase the number of live temporaries in some
4741 * code created by inssel.brg, leading to the well known spills+
4742 * branches problem. Testcase: mcs crash in
4743 * System.MonoCustomAttrs:GetCustomAttributes.
4745 #ifdef MONO_ARCH_GOT_REG
4746 got_reg = MONO_ARCH_GOT_REG;
4747 #else
4748 regs = mono_arch_get_global_int_regs (cfg);
4749 g_assert (regs);
4750 got_reg = GPOINTER_TO_INT (regs->data);
4751 g_list_free (regs);
4752 #endif
4753 cfg->got_var->opcode = OP_REGVAR;
4754 cfg->got_var->dreg = got_reg;
4755 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
4759 * Have to call this again to process variables added since the first call.
4761 mono_liveness_handle_exception_clauses (cfg);
4763 if (cfg->globalra) {
4764 MonoBasicBlock *bb;
4766 /* Have to do this before regalloc since it can create vregs */
4767 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
4768 mono_arch_lowering_pass (cfg, bb);
4770 mono_global_regalloc (cfg);
4773 if ((cfg->opt & MONO_OPT_LINEARS) && !cfg->globalra) {
4774 GList *vars, *regs, *l;
4776 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
4777 cfg->comp_done &= ~MONO_COMP_LIVENESS;
4778 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
4779 mono_analyze_liveness (cfg);
4781 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
4782 regs = mono_arch_get_global_int_regs (cfg);
4783 /* Remove the reg reserved for holding the GOT address */
4784 if (cfg->got_var) {
4785 for (l = regs; l; l = l->next) {
4786 if (GPOINTER_TO_UINT (l->data) == cfg->got_var->dreg) {
4787 regs = g_list_delete_link (regs, l);
4788 break;
4792 mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
4796 //mono_print_code (cfg, "");
4798 //print_dfn (cfg);
4800 /* variables are allocated after decompose, since decompose could create temps */
4801 if (!cfg->globalra && !COMPILE_LLVM (cfg)) {
4802 mono_arch_allocate_vars (cfg);
4803 if (cfg->exception_type)
4804 return cfg;
4808 MonoBasicBlock *bb;
4809 gboolean need_local_opts;
4811 if (!cfg->globalra && !COMPILE_LLVM (cfg)) {
4812 mono_spill_global_vars (cfg, &need_local_opts);
4814 if (need_local_opts || cfg->compile_aot) {
4815 /* To optimize code created by spill_global_vars */
4816 mono_local_cprop (cfg);
4817 if (cfg->opt & MONO_OPT_DEADCE)
4818 mono_local_deadce (cfg);
4822 /* Add branches between non-consecutive bblocks */
4823 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4824 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
4825 bb->last_ins->inst_false_bb && bb->next_bb != bb->last_ins->inst_false_bb) {
4826 /* we are careful when inverting, since bugs like #59580
4827 * could show up when dealing with NaNs.
4829 if (MONO_IS_COND_BRANCH_NOFP(bb->last_ins) && bb->next_bb == bb->last_ins->inst_true_bb) {
4830 MonoBasicBlock *tmp = bb->last_ins->inst_true_bb;
4831 bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb;
4832 bb->last_ins->inst_false_bb = tmp;
4834 bb->last_ins->opcode = mono_reverse_branch_op (bb->last_ins->opcode);
4835 } else {
4836 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
4837 inst->opcode = OP_BR;
4838 inst->inst_target_bb = bb->last_ins->inst_false_bb;
4839 mono_bblock_add_inst (bb, inst);
4844 if (cfg->verbose_level >= 4 && !cfg->globalra) {
4845 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4846 MonoInst *tree = bb->code;
4847 g_print ("DUMP BLOCK %d:\n", bb->block_num);
4848 if (!tree)
4849 continue;
4850 for (; tree; tree = tree->next) {
4851 mono_print_ins_index (-1, tree);
4856 /* FIXME: */
4857 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
4858 bb->max_vreg = cfg->next_vreg;
4862 if (COMPILE_LLVM (cfg)) {
4863 #ifdef ENABLE_LLVM
4864 char *nm;
4866 /* The IR has to be in SSA form for LLVM */
4867 if (!(cfg->comp_done & MONO_COMP_SSA)) {
4868 cfg->exception_message = g_strdup ("SSA disabled.");
4869 cfg->disable_llvm = TRUE;
4872 if (cfg->flags & MONO_CFG_HAS_ARRAY_ACCESS)
4873 mono_decompose_array_access_opts (cfg);
4875 if (!cfg->disable_llvm)
4876 mono_llvm_emit_method (cfg);
4877 if (cfg->disable_llvm) {
4878 if (cfg->verbose_level >= 1) {
4879 //nm = mono_method_full_name (cfg->method, TRUE);
4880 printf ("LLVM failed for '%s': %s\n", method->name, cfg->exception_message);
4881 //g_free (nm);
4883 mono_destroy_compile (cfg);
4884 try_llvm = FALSE;
4885 goto restart_compile;
4888 if (cfg->verbose_level > 0 && !cfg->compile_aot) {
4889 nm = mono_method_full_name (cfg->method, TRUE);
4890 g_print ("LLVM Method %s emitted at %p to %p (code length %d) [%s]\n",
4891 nm,
4892 cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
4893 g_free (nm);
4895 #endif
4896 } else {
4897 mono_codegen (cfg);
4900 if (COMPILE_LLVM (cfg))
4901 InterlockedIncrement (&mono_jit_stats.methods_with_llvm);
4902 else
4903 InterlockedIncrement (&mono_jit_stats.methods_without_llvm);
4905 cfg->jit_info = create_jit_info (cfg, method_to_compile);
4907 #ifdef MONO_ARCH_HAVE_LIVERANGE_OPS
4908 if (cfg->extend_live_ranges) {
4909 /* Extend live ranges to cover the whole method */
4910 for (i = 0; i < cfg->num_varinfo; ++i)
4911 MONO_VARINFO (cfg, i)->live_range_end = cfg->code_len;
4913 #endif
4915 if (!cfg->compile_aot)
4916 mono_save_xdebug_info (cfg);
4918 mini_gc_create_gc_map (cfg);
4920 mono_save_seq_point_info (cfg);
4922 if (cfg->verbose_level >= 2) {
4923 char *id = mono_method_full_name (cfg->method, FALSE);
4924 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
4925 g_free (id);
4928 if (!cfg->compile_aot) {
4929 mono_domain_lock (cfg->domain);
4930 mono_jit_info_table_add (cfg->domain, cfg->jit_info);
4932 if (cfg->method->dynamic)
4933 mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = cfg->jit_info;
4934 mono_domain_unlock (cfg->domain);
4937 /* collect statistics */
4938 mono_perfcounters->jit_methods++;
4939 mono_perfcounters->jit_bytes += header->code_size;
4940 mono_jit_stats.allocated_code_size += cfg->code_len;
4941 code_size_ratio = cfg->code_len;
4942 if (code_size_ratio > mono_jit_stats.biggest_method_size && mono_jit_stats.enabled) {
4943 mono_jit_stats.biggest_method_size = code_size_ratio;
4944 g_free (mono_jit_stats.biggest_method);
4945 mono_jit_stats.biggest_method = g_strdup_printf ("%s::%s)", method->klass->name, method->name);
4947 code_size_ratio = (code_size_ratio * 100) / header->code_size;
4948 if (code_size_ratio > mono_jit_stats.max_code_size_ratio && mono_jit_stats.enabled) {
4949 mono_jit_stats.max_code_size_ratio = code_size_ratio;
4950 g_free (mono_jit_stats.max_ratio_method);
4951 mono_jit_stats.max_ratio_method = g_strdup_printf ("%s::%s)", method->klass->name, method->name);
4953 mono_jit_stats.native_code_size += cfg->code_len;
4955 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
4956 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
4958 return cfg;
4961 #else
4963 MonoCompile*
4964 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
4966 g_assert_not_reached ();
4967 return NULL;
4970 #endif /* DISABLE_JIT */
4972 MonoJitInfo*
4973 mono_domain_lookup_shared_generic (MonoDomain *domain, MonoMethod *method)
4975 static gboolean inited = FALSE;
4976 static int lookups = 0;
4977 static int failed_lookups = 0;
4978 MonoJitInfo *ji;
4980 ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, mini_get_shared_method (method));
4981 if (ji && !ji->has_generic_jit_info)
4982 ji = NULL;
4984 if (!inited) {
4985 mono_counters_register ("Shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &lookups);
4986 mono_counters_register ("Failed shared generic lookups", MONO_COUNTER_INT|MONO_COUNTER_GENERICS, &failed_lookups);
4987 inited = TRUE;
4990 ++lookups;
4991 if (!ji)
4992 ++failed_lookups;
4994 return ji;
4998 * LOCKING: Assumes domain->jit_code_hash_lock is held.
5000 static MonoJitInfo*
5001 lookup_method_inner (MonoDomain *domain, MonoMethod *method)
5003 MonoJitInfo *ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, method);
5005 if (ji)
5006 return ji;
5008 if (!mono_method_is_generic_sharable_impl (method, FALSE))
5009 return NULL;
5010 return mono_domain_lookup_shared_generic (domain, method);
5013 static MonoJitInfo*
5014 lookup_method (MonoDomain *domain, MonoMethod *method)
5016 MonoJitInfo *info;
5018 mono_loader_lock (); /*FIXME lookup_method_inner acquired it*/
5019 mono_domain_jit_code_hash_lock (domain);
5020 info = lookup_method_inner (domain, method);
5021 mono_domain_jit_code_hash_unlock (domain);
5022 mono_loader_unlock ();
5024 return info;
5027 #if ENABLE_JIT_MAP
5028 static FILE* perf_map_file = NULL;
5030 void
5031 mono_enable_jit_map (void)
5033 if (!perf_map_file) {
5034 char name [64];
5035 g_snprintf (name, sizeof (name), "/tmp/perf-%d.map", getpid ());
5036 unlink (name);
5037 perf_map_file = fopen (name, "w");
5041 void
5042 mono_emit_jit_tramp (void *start, int size, const char *desc)
5044 if (perf_map_file)
5045 fprintf (perf_map_file, "%llx %x %s\n", (long long unsigned int)(gsize)start, size, desc);
5048 void
5049 mono_emit_jit_map (MonoJitInfo *jinfo)
5051 if (perf_map_file) {
5052 char *name = mono_method_full_name (jinfo->method, TRUE);
5053 mono_emit_jit_tramp (jinfo->code_start, jinfo->code_size, name);
5054 g_free (name);
5058 gboolean
5059 mono_jit_map_is_enabled (void)
5061 return perf_map_file != NULL;
5064 #endif
5066 static gpointer
5067 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt, MonoException **jit_ex)
5069 MonoCompile *cfg;
5070 gpointer code = NULL;
5071 MonoJitInfo *jinfo, *info;
5072 MonoVTable *vtable;
5073 MonoException *ex = NULL;
5074 guint32 prof_options;
5075 GTimer *jit_timer;
5076 MonoMethod *prof_method;
5078 #ifdef MONO_USE_AOT_COMPILER
5079 if (opt & MONO_OPT_AOT) {
5080 MonoDomain *domain = mono_domain_get ();
5082 mono_class_init (method->klass);
5084 if ((code = mono_aot_get_method (domain, method))) {
5085 vtable = mono_class_vtable (domain, method->klass);
5086 g_assert (vtable);
5087 mono_runtime_class_init (vtable);
5089 return code;
5092 #endif
5094 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
5095 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5096 MonoMethod *nm;
5097 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
5099 if (!piinfo->addr) {
5100 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
5101 piinfo->addr = mono_lookup_internal_call (method);
5102 else if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
5103 #ifdef HOST_WIN32
5104 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);
5105 #else
5106 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);
5107 #endif
5108 else
5109 mono_lookup_pinvoke_call (method, NULL, NULL);
5111 nm = mono_marshal_get_native_wrapper (method, check_for_pending_exc, FALSE);
5112 code = mono_get_addr_from_ftnptr (mono_compile_method (nm));
5113 jinfo = mono_jit_info_table_find (target_domain, code);
5114 if (!jinfo)
5115 jinfo = mono_jit_info_table_find (mono_domain_get (), code);
5116 if (jinfo)
5117 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
5118 return code;
5120 //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE)
5121 //mono_debug_add_wrapper (method, nm);
5122 } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
5123 const char *name = method->name;
5124 char *full_name, *msg;
5125 MonoMethod *nm;
5127 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
5128 if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
5129 MonoJitICallInfo *mi = mono_find_jit_icall_by_name ("mono_delegate_ctor");
5130 g_assert (mi);
5132 * We need to make sure this wrapper
5133 * is compiled because it might end up
5134 * in an (M)RGCTX if generic sharing
5135 * is enabled, and would be called
5136 * indirectly. If it were a
5137 * trampoline we'd try to patch that
5138 * indirect call, which is not
5139 * possible.
5141 return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper_full (mi, TRUE));
5142 } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
5143 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
5144 return mono_create_delegate_trampoline (target_domain, method->klass);
5145 #else
5146 nm = mono_marshal_get_delegate_invoke (method, NULL);
5147 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
5148 #endif
5149 } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
5150 nm = mono_marshal_get_delegate_begin_invoke (method);
5151 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
5152 } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
5153 nm = mono_marshal_get_delegate_end_invoke (method);
5154 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
5158 full_name = mono_method_full_name (method, TRUE);
5159 msg = g_strdup_printf ("Unrecognizable runtime implemented method '%s'", full_name);
5160 *jit_ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", msg);
5161 g_free (full_name);
5162 g_free (msg);
5163 return NULL;
5166 if (mono_aot_only) {
5167 char *fullname = mono_method_full_name (method, TRUE);
5168 char *msg = g_strdup_printf ("Attempting to JIT compile method '%s' while running with --aot-only.\n", fullname);
5170 *jit_ex = mono_get_exception_execution_engine (msg);
5171 g_free (fullname);
5172 g_free (msg);
5174 return NULL;
5177 jit_timer = g_timer_new ();
5179 cfg = mini_method_compile (method, opt, target_domain, TRUE, FALSE, 0);
5180 prof_method = cfg->method;
5182 g_timer_stop (jit_timer);
5183 mono_jit_stats.jit_time += g_timer_elapsed (jit_timer, NULL);
5184 g_timer_destroy (jit_timer);
5186 switch (cfg->exception_type) {
5187 case MONO_EXCEPTION_NONE:
5188 break;
5189 case MONO_EXCEPTION_TYPE_LOAD:
5190 case MONO_EXCEPTION_MISSING_FIELD:
5191 case MONO_EXCEPTION_MISSING_METHOD:
5192 case MONO_EXCEPTION_FILE_NOT_FOUND:
5193 case MONO_EXCEPTION_BAD_IMAGE: {
5194 /* Throw a type load exception if needed */
5195 MonoLoaderError *error = mono_loader_get_last_error ();
5197 if (error) {
5198 ex = mono_loader_error_prepare_exception (error);
5199 } else {
5200 if (cfg->exception_ptr) {
5201 ex = mono_class_get_exception_for_failure (cfg->exception_ptr);
5202 } else {
5203 if (cfg->exception_type == MONO_EXCEPTION_MISSING_FIELD)
5204 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingFieldException", cfg->exception_message);
5205 else if (cfg->exception_type == MONO_EXCEPTION_MISSING_METHOD)
5206 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingMethodException", cfg->exception_message);
5207 else if (cfg->exception_type == MONO_EXCEPTION_TYPE_LOAD)
5208 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "TypeLoadException", cfg->exception_message);
5209 else if (cfg->exception_type == MONO_EXCEPTION_FILE_NOT_FOUND)
5210 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FileNotFoundException", cfg->exception_message);
5211 else if (cfg->exception_type == MONO_EXCEPTION_BAD_IMAGE)
5212 ex = mono_get_exception_bad_image_format (cfg->exception_message);
5213 else
5214 g_assert_not_reached ();
5217 break;
5219 case MONO_EXCEPTION_INVALID_PROGRAM:
5220 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", cfg->exception_message);
5221 break;
5222 case MONO_EXCEPTION_UNVERIFIABLE_IL:
5223 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.Security", "VerificationException", cfg->exception_message);
5224 break;
5225 case MONO_EXCEPTION_METHOD_ACCESS:
5226 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MethodAccessException", cfg->exception_message);
5227 break;
5228 case MONO_EXCEPTION_FIELD_ACCESS:
5229 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FieldAccessException", cfg->exception_message);
5230 break;
5231 /* this can only be set if the security manager is active */
5232 case MONO_EXCEPTION_SECURITY_LINKDEMAND: {
5233 MonoSecurityManager* secman = mono_security_manager_get_methods ();
5234 MonoObject *exc = NULL;
5235 gpointer args [2];
5237 args [0] = &cfg->exception_data;
5238 args [1] = &method;
5239 mono_runtime_invoke (secman->linkdemandsecurityexception, NULL, args, &exc);
5241 ex = (MonoException*)exc;
5242 break;
5244 case MONO_EXCEPTION_OBJECT_SUPPLIED: {
5245 MonoException *exp = cfg->exception_ptr;
5246 MONO_GC_UNREGISTER_ROOT (cfg->exception_ptr);
5248 ex = exp;
5249 break;
5251 case MONO_EXCEPTION_OUT_OF_MEMORY:
5252 ex = mono_domain_get ()->out_of_memory_ex;
5253 break;
5254 default:
5255 g_assert_not_reached ();
5258 if (ex) {
5259 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
5260 mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
5262 mono_destroy_compile (cfg);
5263 *jit_ex = ex;
5265 return NULL;
5268 mono_loader_lock (); /*FIXME lookup_method_inner requires the loader lock*/
5269 mono_domain_lock (target_domain);
5271 /* Check if some other thread already did the job. In this case, we can
5272 discard the code this thread generated. */
5274 mono_domain_jit_code_hash_lock (target_domain);
5276 info = lookup_method_inner (target_domain, method);
5277 if (info) {
5278 /* We can't use a domain specific method in another domain */
5279 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
5280 code = info->code_start;
5281 // printf("Discarding code for method %s\n", method->name);
5285 if (code == NULL) {
5286 mono_internal_hash_table_insert (&target_domain->jit_code_hash, cfg->jit_info->method, cfg->jit_info);
5287 mono_domain_jit_code_hash_unlock (target_domain);
5288 code = cfg->native_code;
5290 if (cfg->generic_sharing_context && mono_method_is_generic_sharable_impl (method, FALSE))
5291 mono_stats.generics_shared_methods++;
5292 } else {
5293 mono_domain_jit_code_hash_unlock (target_domain);
5296 jinfo = cfg->jit_info;
5298 prof_options = cfg->prof_options;
5301 * Update global stats while holding a lock, instead of doing many
5302 * InterlockedIncrement operations during JITting.
5304 mono_jit_stats.allocate_var += cfg->stat_allocate_var;
5305 mono_jit_stats.locals_stack_size += cfg->stat_locals_stack_size;
5306 mono_jit_stats.basic_blocks += cfg->stat_basic_blocks;
5307 mono_jit_stats.max_basic_blocks = MAX (cfg->stat_basic_blocks, mono_jit_stats.max_basic_blocks);
5308 mono_jit_stats.cil_code_size += cfg->stat_cil_code_size;
5309 mono_jit_stats.regvars += cfg->stat_n_regvars;
5310 mono_jit_stats.inlineable_methods += cfg->stat_inlineable_methods;
5311 mono_jit_stats.inlined_methods += cfg->stat_inlined_methods;
5312 mono_jit_stats.cas_demand_generation += cfg->stat_cas_demand_generation;
5313 mono_jit_stats.code_reallocs += cfg->stat_code_reallocs;
5315 mono_destroy_compile (cfg);
5317 #ifndef DISABLE_JIT
5318 if (domain_jit_info (target_domain)->jump_target_hash) {
5319 MonoJumpInfo patch_info;
5320 MonoJumpList *jlist;
5321 GSList *tmp;
5322 jlist = g_hash_table_lookup (domain_jit_info (target_domain)->jump_target_hash, method);
5323 if (jlist) {
5324 patch_info.next = NULL;
5325 patch_info.ip.i = 0;
5326 patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
5327 patch_info.data.method = method;
5328 g_hash_table_remove (domain_jit_info (target_domain)->jump_target_hash, method);
5330 for (tmp = jlist->list; tmp; tmp = tmp->next)
5331 mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info, NULL, TRUE);
5335 mono_emit_jit_map (jinfo);
5336 #endif
5337 mono_domain_unlock (target_domain);
5338 mono_loader_unlock ();
5340 vtable = mono_class_vtable (target_domain, method->klass);
5341 if (!vtable) {
5342 ex = mono_class_get_exception_for_failure (method->klass);
5343 g_assert (ex);
5344 *jit_ex = ex;
5345 return NULL;
5348 if (prof_options & MONO_PROFILE_JIT_COMPILATION) {
5349 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
5350 if (mono_marshal_method_from_wrapper (method)) {
5351 /* Native func wrappers have no method */
5352 /* The profiler doesn't know about wrappers, so pass the original icall method */
5353 mono_profiler_method_end_jit (mono_marshal_method_from_wrapper (method), jinfo, MONO_PROFILE_OK);
5356 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
5357 if (prof_method != method) {
5358 mono_profiler_method_end_jit (prof_method, jinfo, MONO_PROFILE_OK);
5362 ex = mono_runtime_class_init_full (vtable, FALSE);
5363 if (ex) {
5364 *jit_ex = ex;
5365 return NULL;
5367 return code;
5370 static gpointer
5371 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt, MonoException **ex)
5373 MonoDomain *target_domain, *domain = mono_domain_get ();
5374 MonoJitInfo *info;
5375 gpointer code, p;
5376 MonoJitICallInfo *callinfo = NULL;
5379 * ICALL wrappers are handled specially, since there is only one copy of them
5380 * shared by all appdomains.
5382 if ((method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (strstr (method->name, "__icall_wrapper_") == method->name)) {
5383 const char *icall_name;
5385 icall_name = method->name + strlen ("__icall_wrapper_");
5386 g_assert (icall_name);
5387 callinfo = mono_find_jit_icall_by_name (icall_name);
5388 g_assert (callinfo);
5390 /* Must be domain neutral since there is only one copy */
5391 opt |= MONO_OPT_SHARED;
5394 if (method->dynamic)
5395 opt &= ~MONO_OPT_SHARED;
5397 /* These methods can become invalid when a domain is unloaded */
5398 if (method->klass->image != mono_get_corlib () || method->is_inflated)
5399 opt &= ~MONO_OPT_SHARED;
5401 if (opt & MONO_OPT_SHARED)
5402 target_domain = mono_get_root_domain ();
5403 else
5404 target_domain = domain;
5406 info = lookup_method (target_domain, method);
5407 if (info) {
5408 /* We can't use a domain specific method in another domain */
5409 if (! ((domain != target_domain) && !info->domain_neutral)) {
5410 MonoVTable *vtable;
5411 MonoException *tmpEx;
5413 mono_jit_stats.methods_lookups++;
5414 vtable = mono_class_vtable (domain, method->klass);
5415 g_assert (vtable);
5416 tmpEx = mono_runtime_class_init_full (vtable, ex == NULL);
5417 if (tmpEx) {
5418 *ex = tmpEx;
5419 return NULL;
5421 return mono_create_ftnptr (target_domain, info->code_start);
5425 code = mono_jit_compile_method_inner (method, target_domain, opt, ex);
5426 if (!code)
5427 return NULL;
5429 p = mono_create_ftnptr (target_domain, code);
5431 if (callinfo) {
5432 /*mono_register_jit_icall_wrapper takes the loader lock, so we take it on the outside. */
5433 mono_loader_lock ();
5434 mono_jit_lock ();
5435 if (!callinfo->wrapper) {
5436 callinfo->wrapper = p;
5437 mono_register_jit_icall_wrapper (callinfo, p);
5438 mono_debug_add_icall_wrapper (method, callinfo);
5440 mono_jit_unlock ();
5441 mono_loader_unlock ();
5444 return p;
5447 gpointer
5448 mono_jit_compile_method (MonoMethod *method)
5450 MonoException *ex = NULL;
5451 gpointer code;
5453 code = mono_jit_compile_method_with_opt (method, default_opt, &ex);
5454 if (!code) {
5455 g_assert (ex);
5456 mono_raise_exception (ex);
5459 return code;
5462 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
5463 static void
5464 invalidated_delegate_trampoline (char *desc)
5466 g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
5467 "See http://www.go-mono.com/delegate.html for an explanation and ways to fix this.",
5468 desc);
5470 #endif
5473 * mono_jit_free_method:
5475 * Free all memory allocated by the JIT for METHOD.
5477 static void
5478 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
5480 MonoJitDynamicMethodInfo *ji;
5481 gboolean destroy = TRUE;
5482 GHashTableIter iter;
5483 MonoJumpList *jlist;
5485 g_assert (method->dynamic);
5487 mono_domain_lock (domain);
5488 ji = mono_dynamic_code_hash_lookup (domain, method);
5489 mono_domain_unlock (domain);
5491 if (!ji)
5492 return;
5494 mono_debug_remove_method (method, domain);
5496 mono_domain_lock (domain);
5497 g_hash_table_remove (domain_jit_info (domain)->dynamic_code_hash, method);
5498 mono_internal_hash_table_remove (&domain->jit_code_hash, method);
5499 g_hash_table_remove (domain_jit_info (domain)->jump_trampoline_hash, method);
5500 g_hash_table_remove (domain_jit_info (domain)->runtime_invoke_hash, method);
5502 /* Remove jump targets in this method */
5503 g_hash_table_iter_init (&iter, domain_jit_info (domain)->jump_target_hash);
5504 while (g_hash_table_iter_next (&iter, NULL, (void**)&jlist)) {
5505 GSList *tmp, *remove;
5507 remove = NULL;
5508 for (tmp = jlist->list; tmp; tmp = tmp->next) {
5509 guint8 *ip = tmp->data;
5511 if (ip >= (guint8*)ji->ji->code_start && ip < (guint8*)ji->ji->code_start + ji->ji->code_size)
5512 remove = g_slist_prepend (remove, tmp);
5514 for (tmp = remove; tmp; tmp = tmp->next) {
5515 jlist->list = g_slist_delete_link (jlist->list, tmp->data);
5517 g_slist_free (remove);
5520 mono_domain_unlock (domain);
5522 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
5523 if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
5525 * Instead of freeing the code, change it to call an error routine
5526 * so people can fix their code.
5528 char *type = mono_type_full_name (&method->klass->byval_arg);
5529 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
5531 g_free (type);
5532 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
5533 destroy = FALSE;
5535 #endif
5538 * This needs to be done before freeing code_mp, since the code address is the
5539 * key in the table, so if we free the code_mp first, another thread can grab the
5540 * same code address and replace our entry in the table.
5542 mono_jit_info_table_remove (domain, ji->ji);
5544 if (destroy)
5545 mono_code_manager_destroy (ji->code_mp);
5546 g_free (ji);
5549 gpointer
5550 mono_jit_find_compiled_method_with_jit_info (MonoDomain *domain, MonoMethod *method, MonoJitInfo **ji)
5552 MonoDomain *target_domain;
5553 MonoJitInfo *info;
5555 if (default_opt & MONO_OPT_SHARED)
5556 target_domain = mono_get_root_domain ();
5557 else
5558 target_domain = domain;
5560 info = lookup_method (target_domain, method);
5561 if (info) {
5562 /* We can't use a domain specific method in another domain */
5563 if (! ((domain != target_domain) && !info->domain_neutral)) {
5564 mono_jit_stats.methods_lookups++;
5565 if (ji)
5566 *ji = info;
5567 return info->code_start;
5571 if (ji)
5572 *ji = NULL;
5573 return NULL;
5576 gpointer
5577 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
5579 return mono_jit_find_compiled_method_with_jit_info (domain, method, NULL);
5582 typedef struct {
5583 MonoMethod *method;
5584 gpointer compiled_method;
5585 gpointer runtime_invoke;
5586 MonoVTable *vtable;
5587 MonoDynCallInfo *dyn_call_info;
5588 MonoClass *ret_box_class;
5589 } RuntimeInvokeInfo;
5592 * mono_jit_runtime_invoke:
5593 * @method: the method to invoke
5594 * @obj: this pointer
5595 * @params: array of parameter values.
5596 * @exc: used to catch exceptions objects
5598 static MonoObject*
5599 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
5601 MonoMethod *invoke;
5602 MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
5603 MonoDomain *domain = mono_domain_get ();
5604 MonoJitDomainInfo *domain_info;
5605 RuntimeInvokeInfo *info, *info2;
5607 if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
5608 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
5609 return NULL;
5612 domain_info = domain_jit_info (domain);
5614 mono_domain_lock (domain);
5615 info = g_hash_table_lookup (domain_info->runtime_invoke_hash, method);
5616 mono_domain_unlock (domain);
5618 if (!info) {
5619 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
5621 * This might be redundant since mono_class_vtable () already does this,
5622 * but keep it just in case for moonlight.
5624 mono_class_setup_vtable (method->klass);
5625 if (method->klass->exception_type != MONO_EXCEPTION_NONE) {
5626 if (exc)
5627 *exc = (MonoObject*)mono_class_get_exception_for_failure (method->klass);
5628 else
5629 mono_raise_exception (mono_class_get_exception_for_failure (method->klass));
5630 return NULL;
5634 info = g_new0 (RuntimeInvokeInfo, 1);
5636 invoke = mono_marshal_get_runtime_invoke (method, FALSE);
5637 info->vtable = mono_class_vtable_full (domain, method->klass, TRUE);
5638 g_assert (info->vtable);
5640 if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
5641 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
5643 * Array Get/Set/Address methods. The JIT implements them using inline code
5644 * inside the runtime invoke wrappers, so no need to compile them.
5646 info->compiled_method = NULL;
5647 } else {
5648 MonoException *jit_ex = NULL;
5650 info->compiled_method = mono_jit_compile_method_with_opt (method, default_opt, &jit_ex);
5651 if (!info->compiled_method) {
5652 g_free (info);
5653 g_assert (jit_ex);
5654 if (exc) {
5655 *exc = (MonoObject*)jit_ex;
5656 return NULL;
5657 } else {
5658 mono_raise_exception (jit_ex);
5662 if (mono_method_needs_static_rgctx_invoke (method, FALSE))
5663 info->compiled_method = mono_create_static_rgctx_trampoline (method, info->compiled_method);
5667 * We want to avoid AOTing 1000s of runtime-invoke wrappers when running
5668 * in full-aot mode, so we use a slower, but more generic wrapper if
5669 * possible, built on top of the OP_DYN_CALL opcode provided by the JIT.
5671 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
5672 if (mono_aot_only || debug_options.dyn_runtime_invoke) {
5673 MonoMethodSignature *sig = mono_method_signature (method);
5674 gboolean supported = TRUE;
5675 int i;
5677 if (method->string_ctor)
5678 sig = mono_marshal_get_string_ctor_signature (method);
5680 for (i = 0; i < sig->param_count; ++i) {
5681 MonoType *t = sig->params [i];
5683 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t)))
5684 supported = FALSE;
5687 if (method->klass->contextbound || !info->compiled_method)
5688 supported = FALSE;
5690 if (supported)
5691 info->dyn_call_info = mono_arch_dyn_call_prepare (sig);
5693 if (info->dyn_call_info) {
5694 switch (sig->ret->type) {
5695 case MONO_TYPE_VOID:
5696 break;
5697 case MONO_TYPE_I1:
5698 case MONO_TYPE_U1:
5699 case MONO_TYPE_I2:
5700 case MONO_TYPE_U2:
5701 case MONO_TYPE_I4:
5702 case MONO_TYPE_U4:
5703 case MONO_TYPE_I:
5704 case MONO_TYPE_U:
5705 case MONO_TYPE_I8:
5706 case MONO_TYPE_U8:
5707 case MONO_TYPE_BOOLEAN:
5708 case MONO_TYPE_CHAR:
5709 case MONO_TYPE_R4:
5710 case MONO_TYPE_R8:
5711 info->ret_box_class = mono_class_from_mono_type (sig->ret);
5712 break;
5713 case MONO_TYPE_PTR:
5714 info->ret_box_class = mono_defaults.int_class;
5715 break;
5716 case MONO_TYPE_STRING:
5717 case MONO_TYPE_CLASS:
5718 case MONO_TYPE_ARRAY:
5719 case MONO_TYPE_SZARRAY:
5720 case MONO_TYPE_OBJECT:
5721 break;
5722 case MONO_TYPE_GENERICINST:
5723 if (!MONO_TYPE_IS_REFERENCE (sig->ret))
5724 info->ret_box_class = mono_class_from_mono_type (sig->ret);
5725 break;
5726 case MONO_TYPE_VALUETYPE:
5727 info->ret_box_class = mono_class_from_mono_type (sig->ret);
5728 break;
5729 default:
5730 g_assert_not_reached ();
5731 break;
5735 #endif
5737 if (!info->dyn_call_info)
5738 info->runtime_invoke = mono_jit_compile_method (invoke);
5740 mono_domain_lock (domain);
5741 info2 = g_hash_table_lookup (domain_info->runtime_invoke_hash, method);
5742 if (info2) {
5743 g_free (info);
5744 info = info2;
5745 } else {
5746 g_hash_table_insert (domain_info->runtime_invoke_hash, method, info);
5748 mono_domain_unlock (domain);
5751 runtime_invoke = info->runtime_invoke;
5754 * We need this here because mono_marshal_get_runtime_invoke can place
5755 * the helper method in System.Object and not the target class.
5757 if (exc) {
5758 *exc = (MonoObject*)mono_runtime_class_init_full (info->vtable, FALSE);
5759 if (*exc)
5760 return NULL;
5761 } else {
5762 mono_runtime_class_init (info->vtable);
5765 /* The wrappers expect this to be initialized to NULL */
5766 if (exc)
5767 *exc = NULL;
5769 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
5770 if (info->dyn_call_info) {
5771 MonoMethodSignature *sig = mono_method_signature (method);
5772 gpointer *args;
5773 static RuntimeInvokeDynamicFunction dyn_runtime_invoke;
5774 int i, pindex;
5775 guint8 buf [128];
5776 guint8 retval [128];
5778 if (!dyn_runtime_invoke) {
5779 invoke = mono_marshal_get_runtime_invoke_dynamic ();
5780 dyn_runtime_invoke = mono_jit_compile_method (invoke);
5783 /* Convert the arguments to the format expected by start_dyn_call () */
5784 args = g_alloca ((sig->param_count + sig->hasthis) * sizeof (gpointer));
5785 pindex = 0;
5786 if (sig->hasthis)
5787 args [pindex ++] = &obj;
5788 for (i = 0; i < sig->param_count; ++i) {
5789 MonoType *t = sig->params [i];
5791 if (t->byref) {
5792 args [pindex ++] = &params [i];
5793 } else if (MONO_TYPE_IS_REFERENCE (t) || t->type == MONO_TYPE_PTR) {
5794 args [pindex ++] = &params [i];
5795 } else {
5796 args [pindex ++] = params [i];
5800 //printf ("M: %s\n", mono_method_full_name (method, TRUE));
5802 mono_arch_start_dyn_call (info->dyn_call_info, (gpointer**)args, retval, buf, sizeof (buf));
5804 dyn_runtime_invoke (buf, exc, info->compiled_method);
5806 mono_arch_finish_dyn_call (info->dyn_call_info, buf);
5808 if (info->ret_box_class)
5809 return mono_value_box (domain, info->ret_box_class, retval);
5810 else
5811 return *(MonoObject**)retval;
5813 #endif
5815 return runtime_invoke (obj, params, exc, info->compiled_method);
5818 void
5819 SIG_HANDLER_SIGNATURE (mono_sigfpe_signal_handler)
5821 MonoException *exc = NULL;
5822 MonoJitInfo *ji;
5823 #if !(defined(MONO_ARCH_USE_SIGACTION) || defined(HOST_WIN32))
5824 void *info = NULL;
5825 #endif
5826 GET_CONTEXT;
5828 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (ctx));
5830 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
5831 if (mono_arch_is_int_overflow (ctx, info))
5833 * The spec says this throws ArithmeticException, but MS throws the derived
5834 * OverflowException.
5836 exc = mono_get_exception_overflow ();
5837 else
5838 exc = mono_get_exception_divide_by_zero ();
5839 #else
5840 exc = mono_get_exception_divide_by_zero ();
5841 #endif
5843 if (!ji) {
5844 if (mono_chain_signal (SIG_HANDLER_PARAMS))
5845 return;
5847 mono_handle_native_sigsegv (SIGSEGV, ctx);
5850 mono_arch_handle_exception (ctx, exc);
5853 void
5854 SIG_HANDLER_SIGNATURE (mono_sigill_signal_handler)
5856 MonoException *exc;
5857 GET_CONTEXT;
5859 exc = mono_get_exception_execution_engine ("SIGILL");
5861 mono_arch_handle_exception (ctx, exc);
5864 #if defined(MONO_ARCH_USE_SIGACTION) || defined(HOST_WIN32)
5865 #define HAVE_SIG_INFO
5866 #endif
5868 void
5869 SIG_HANDLER_SIGNATURE (mono_sigsegv_signal_handler)
5871 MonoJitInfo *ji;
5872 MonoJitTlsData *jit_tls = mono_native_tls_get_value (mono_jit_tls_id);
5873 gpointer fault_addr = NULL;
5875 GET_CONTEXT;
5877 #if defined(MONO_ARCH_SOFT_DEBUG_SUPPORTED) && defined(HAVE_SIG_INFO)
5878 if (mono_arch_is_single_step_event (info, ctx)) {
5879 mono_debugger_agent_single_step_event (ctx);
5880 return;
5881 } else if (mono_arch_is_breakpoint_event (info, ctx)) {
5882 mono_debugger_agent_breakpoint_hit (ctx);
5883 return;
5885 #endif
5887 #if !defined(HOST_WIN32) && defined(HAVE_SIG_INFO)
5888 fault_addr = info->si_addr;
5889 if (mono_aot_is_pagefault (info->si_addr)) {
5890 mono_aot_handle_pagefault (info->si_addr);
5891 return;
5893 #endif
5895 /* The thread might no be registered with the runtime */
5896 if (!mono_domain_get () || !jit_tls) {
5897 if (mono_chain_signal (SIG_HANDLER_PARAMS))
5898 return;
5899 mono_handle_native_sigsegv (SIGSEGV, ctx);
5902 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (ctx));
5904 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
5905 if (mono_handle_soft_stack_ovf (jit_tls, ji, ctx, (guint8*)info->si_addr))
5906 return;
5908 #ifdef MONO_ARCH_HAVE_SIGCTX_TO_MONOCTX
5909 /* info->si_addr seems to be NULL on some kernels when handling stack overflows */
5910 fault_addr = info->si_addr;
5911 if (fault_addr == NULL) {
5912 MonoContext mctx;
5914 mono_arch_sigctx_to_monoctx (ctx, &mctx);
5916 fault_addr = MONO_CONTEXT_GET_SP (&mctx);
5918 #endif
5920 if (jit_tls->stack_size &&
5921 ABS ((guint8*)fault_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 8192 * sizeof (gpointer)) {
5923 * The hard-guard page has been hit: there is not much we can do anymore
5924 * Print a hopefully clear message and abort.
5926 mono_handle_hard_stack_ovf (jit_tls, ji, ctx, (guint8*)info->si_addr);
5927 g_assert_not_reached ();
5928 } else {
5929 /* The original handler might not like that it is executed on an altstack... */
5930 if (!ji && mono_chain_signal (SIG_HANDLER_PARAMS))
5931 return;
5933 mono_arch_handle_altstack_exception (ctx, info->si_addr, FALSE);
5935 #else
5937 if (!ji) {
5938 if (mono_chain_signal (SIG_HANDLER_PARAMS))
5939 return;
5941 mono_handle_native_sigsegv (SIGSEGV, ctx);
5944 mono_arch_handle_exception (ctx, NULL);
5945 #endif
5948 void
5949 SIG_HANDLER_SIGNATURE (mono_sigint_signal_handler)
5951 MonoException *exc;
5952 GET_CONTEXT;
5954 exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
5956 mono_arch_handle_exception (ctx, exc);
5959 /* mono_jit_create_remoting_trampoline:
5960 * @method: pointer to the method info
5962 * Creates a trampoline which calls the remoting functions. This
5963 * is used in the vtable of transparent proxies.
5965 * Returns: a pointer to the newly created code
5967 static gpointer
5968 mono_jit_create_remoting_trampoline (MonoDomain *domain, MonoMethod *method, MonoRemotingTarget target)
5970 MonoMethod *nm;
5971 guint8 *addr = NULL;
5973 if ((method->flags & METHOD_ATTRIBUTE_VIRTUAL) && mono_method_signature (method)->generic_param_count) {
5974 return mono_create_specific_trampoline (method, MONO_TRAMPOLINE_GENERIC_VIRTUAL_REMOTING,
5975 domain, NULL);
5978 if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
5979 (mono_method_signature (method)->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
5980 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
5981 addr = mono_compile_method (nm);
5982 } else {
5983 addr = mono_compile_method (method);
5985 return mono_get_addr_from_ftnptr (addr);
5988 static gpointer *vtable_trampolines;
5989 static int vtable_trampolines_size;
5991 gpointer
5992 mini_get_vtable_trampoline (int slot_index)
5994 int index = slot_index + MONO_IMT_SIZE;
5996 g_assert (slot_index >= - MONO_IMT_SIZE);
5997 if (!vtable_trampolines || slot_index + MONO_IMT_SIZE >= vtable_trampolines_size) {
5998 mono_jit_lock ();
5999 if (!vtable_trampolines || index >= vtable_trampolines_size) {
6000 int new_size;
6001 gpointer new_table;
6003 new_size = vtable_trampolines_size ? vtable_trampolines_size * 2 : 128;
6004 while (new_size <= index)
6005 new_size *= 2;
6006 new_table = g_new0 (gpointer, new_size);
6008 if (vtable_trampolines)
6009 memcpy (new_table, vtable_trampolines, vtable_trampolines_size * sizeof (gpointer));
6010 g_free (vtable_trampolines);
6011 mono_memory_barrier ();
6012 vtable_trampolines = new_table;
6013 vtable_trampolines_size = new_size;
6015 mono_jit_unlock ();
6018 if (!vtable_trampolines [index])
6019 vtable_trampolines [index] = mono_create_specific_trampoline (GUINT_TO_POINTER (slot_index), MONO_TRAMPOLINE_VCALL, mono_get_root_domain (), NULL);
6020 return vtable_trampolines [index];
6023 static gpointer
6024 mini_get_imt_trampoline (int slot_index)
6026 return mini_get_vtable_trampoline (slot_index - MONO_IMT_SIZE);
6029 static void
6030 mini_parse_debug_options (void)
6032 char *options = getenv ("MONO_DEBUG");
6033 gchar **args, **ptr;
6035 if (!options)
6036 return;
6038 args = g_strsplit (options, ",", -1);
6040 for (ptr = args; ptr && *ptr; ptr++) {
6041 const char *arg = *ptr;
6043 if (!strcmp (arg, "handle-sigint"))
6044 debug_options.handle_sigint = TRUE;
6045 else if (!strcmp (arg, "keep-delegates"))
6046 debug_options.keep_delegates = TRUE;
6047 else if (!strcmp (arg, "reverse-pinvoke-exceptions"))
6048 debug_options.reverse_pinvoke_exceptions = TRUE;
6049 else if (!strcmp (arg, "collect-pagefault-stats"))
6050 debug_options.collect_pagefault_stats = TRUE;
6051 else if (!strcmp (arg, "break-on-unverified"))
6052 debug_options.break_on_unverified = TRUE;
6053 else if (!strcmp (arg, "no-gdb-backtrace"))
6054 debug_options.no_gdb_backtrace = TRUE;
6055 else if (!strcmp (arg, "suspend-on-sigsegv"))
6056 debug_options.suspend_on_sigsegv = TRUE;
6057 else if (!strcmp (arg, "suspend-on-unhandled"))
6058 debug_options.suspend_on_unhandled = TRUE;
6059 else if (!strcmp (arg, "dont-free-domains"))
6060 mono_dont_free_domains = TRUE;
6061 else if (!strcmp (arg, "dyn-runtime-invoke"))
6062 debug_options.dyn_runtime_invoke = TRUE;
6063 else if (!strcmp (arg, "gdb"))
6064 debug_options.gdb = TRUE;
6065 else if (!strcmp (arg, "explicit-null-checks"))
6066 debug_options.explicit_null_checks = TRUE;
6067 else if (!strcmp (arg, "gen-seq-points"))
6068 debug_options.gen_seq_points = TRUE;
6069 else if (!strcmp (arg, "init-stacks"))
6070 debug_options.init_stacks = TRUE;
6071 else if (!strcmp (arg, "casts"))
6072 debug_options.better_cast_details = TRUE;
6073 else if (!strcmp (arg, "soft-breakpoints"))
6074 debug_options.soft_breakpoints = TRUE;
6075 else {
6076 fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
6077 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', 'suspend-on-unhandled', 'dyn-runtime-invoke', 'gdb', 'explicit-null-checks', 'init-stacks'\n");
6078 exit (1);
6082 g_strfreev (args);
6085 MonoDebugOptions *
6086 mini_get_debug_options (void)
6088 return &debug_options;
6091 static gpointer
6092 mini_create_ftnptr (MonoDomain *domain, gpointer addr)
6094 #if !defined(__ia64__) && !defined(__ppc64__) && !defined(__powerpc64__)
6095 return addr;
6096 #else
6098 gpointer* desc = NULL;
6100 if ((desc = g_hash_table_lookup (domain->ftnptrs_hash, addr)))
6101 return desc;
6102 # ifdef __ia64__
6103 desc = mono_domain_code_reserve (domain, 2 * sizeof (gpointer));
6105 desc [0] = addr;
6106 desc [1] = NULL;
6107 # elif defined(__ppc64__) || defined(__powerpc64__)
6108 gpointer *desc;
6110 desc = mono_domain_alloc0 (domain, 3 * sizeof (gpointer));
6112 desc [0] = addr;
6113 desc [1] = NULL;
6114 desc [2] = NULL;
6115 # endif
6116 g_hash_table_insert (domain->ftnptrs_hash, addr, desc);
6117 return desc;
6118 #endif
6121 static gpointer
6122 mini_get_addr_from_ftnptr (gpointer descr)
6124 #if defined(__ia64__) || defined(__ppc64__) || defined(__powerpc64__)
6125 return *(gpointer*)descr;
6126 #else
6127 return descr;
6128 #endif
6131 static void
6132 register_jit_stats (void)
6134 mono_counters_register ("Compiled methods", MONO_COUNTER_JIT | MONO_COUNTER_WORD, &mono_jit_stats.methods_compiled);
6135 mono_counters_register ("Methods from AOT", MONO_COUNTER_JIT | MONO_COUNTER_WORD, &mono_jit_stats.methods_aot);
6136 mono_counters_register ("Methods JITted using mono JIT", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_without_llvm);
6137 mono_counters_register ("Methods JITted using LLVM", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_with_llvm);
6138 mono_counters_register ("Total time spent JITting (sec)", MONO_COUNTER_JIT | MONO_COUNTER_DOUBLE, &mono_jit_stats.jit_time);
6139 mono_counters_register ("Basic blocks", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.basic_blocks);
6140 mono_counters_register ("Max basic blocks", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.max_basic_blocks);
6141 mono_counters_register ("Allocated vars", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.allocate_var);
6142 mono_counters_register ("Code reallocs", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.code_reallocs);
6143 mono_counters_register ("Allocated code size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.allocated_code_size);
6144 mono_counters_register ("Inlineable methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.inlineable_methods);
6145 mono_counters_register ("Inlined methods", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.inlined_methods);
6146 mono_counters_register ("Regvars", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.regvars);
6147 mono_counters_register ("Locals stack size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.locals_stack_size);
6148 mono_counters_register ("Method cache lookups", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.methods_lookups);
6149 mono_counters_register ("Compiled CIL code size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.cil_code_size);
6150 mono_counters_register ("Native code size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &mono_jit_stats.native_code_size);
6153 static void runtime_invoke_info_free (gpointer value);
6155 static void
6156 mini_create_jit_domain_info (MonoDomain *domain)
6158 MonoJitDomainInfo *info = g_new0 (MonoJitDomainInfo, 1);
6160 info->class_init_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
6161 info->jump_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
6162 info->jit_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
6163 info->delegate_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
6164 info->llvm_vcall_trampoline_hash = g_hash_table_new (mono_aligned_addr_hash, NULL);
6165 info->runtime_invoke_hash = g_hash_table_new_full (mono_aligned_addr_hash, NULL, NULL, runtime_invoke_info_free);
6166 info->seq_points = g_hash_table_new_full (mono_aligned_addr_hash, NULL, NULL, g_free);
6167 info->arch_seq_points = g_hash_table_new (mono_aligned_addr_hash, NULL);
6168 info->jump_target_hash = g_hash_table_new (NULL, NULL);
6170 domain->runtime_info = info;
6173 static void
6174 delete_jump_list (gpointer key, gpointer value, gpointer user_data)
6176 MonoJumpList *jlist = value;
6177 g_slist_free (jlist->list);
6180 static void
6181 dynamic_method_info_free (gpointer key, gpointer value, gpointer user_data)
6183 MonoJitDynamicMethodInfo *di = value;
6184 mono_code_manager_destroy (di->code_mp);
6185 g_free (di);
6188 static void
6189 runtime_invoke_info_free (gpointer value)
6191 RuntimeInvokeInfo *info = (RuntimeInvokeInfo*)value;
6193 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
6194 if (info->dyn_call_info)
6195 mono_arch_dyn_call_free (info->dyn_call_info);
6196 #endif
6197 g_free (info);
6200 static void
6201 mini_free_jit_domain_info (MonoDomain *domain)
6203 MonoJitDomainInfo *info = domain_jit_info (domain);
6205 g_hash_table_foreach (info->jump_target_hash, delete_jump_list, NULL);
6206 g_hash_table_destroy (info->jump_target_hash);
6207 if (info->jump_target_got_slot_hash) {
6208 g_hash_table_foreach (info->jump_target_got_slot_hash, delete_jump_list, NULL);
6209 g_hash_table_destroy (info->jump_target_got_slot_hash);
6211 if (info->dynamic_code_hash) {
6212 g_hash_table_foreach (info->dynamic_code_hash, dynamic_method_info_free, NULL);
6213 g_hash_table_destroy (info->dynamic_code_hash);
6215 if (info->method_code_hash)
6216 g_hash_table_destroy (info->method_code_hash);
6217 g_hash_table_destroy (info->class_init_trampoline_hash);
6218 g_hash_table_destroy (info->jump_trampoline_hash);
6219 g_hash_table_destroy (info->jit_trampoline_hash);
6220 g_hash_table_destroy (info->delegate_trampoline_hash);
6221 if (info->static_rgctx_trampoline_hash)
6222 g_hash_table_destroy (info->static_rgctx_trampoline_hash);
6223 g_hash_table_destroy (info->llvm_vcall_trampoline_hash);
6224 g_hash_table_destroy (info->runtime_invoke_hash);
6225 g_hash_table_destroy (info->seq_points);
6226 g_hash_table_destroy (info->arch_seq_points);
6228 if (info->agent_info)
6229 mono_debugger_agent_free_domain_info (domain);
6231 g_free (domain->runtime_info);
6232 domain->runtime_info = NULL;
6235 MonoDomain *
6236 mini_init (const char *filename, const char *runtime_version)
6238 MonoDomain *domain;
6239 MonoRuntimeCallbacks callbacks;
6240 MonoThreadInfoRuntimeCallbacks ticallbacks;
6242 MONO_PROBE_VES_INIT_BEGIN ();
6244 #if defined(__linux__) && !defined(__native_client__)
6245 if (access ("/proc/self/maps", F_OK) != 0) {
6246 g_print ("Mono requires /proc to be mounted.\n");
6247 exit (1);
6249 #endif
6251 /* Happens when using the embedding interface */
6252 if (!default_opt_set)
6253 default_opt = mono_parse_default_optimizations (NULL);
6255 InitializeCriticalSection (&jit_mutex);
6257 #ifdef MONO_DEBUGGER_SUPPORTED
6258 if (mini_debug_running_inside_mdb ())
6259 mini_debugger_init ();
6260 #endif
6262 #ifdef MONO_HAVE_FAST_TLS
6263 MONO_FAST_TLS_INIT (mono_jit_tls);
6264 MONO_FAST_TLS_INIT (mono_lmf_addr);
6265 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
6266 MONO_FAST_TLS_INIT (mono_lmf);
6267 #endif
6268 #endif
6270 #ifdef MONO_ARCH_HAVE_TLS_GET
6271 mono_runtime_set_has_tls_get (MONO_ARCH_HAVE_TLS_GET);
6272 #else
6273 mono_runtime_set_has_tls_get (FALSE);
6274 #endif
6276 if (!global_codeman)
6277 global_codeman = mono_code_manager_new ();
6278 jit_icall_name_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6280 memset (&callbacks, 0, sizeof (callbacks));
6281 callbacks.create_ftnptr = mini_create_ftnptr;
6282 callbacks.get_addr_from_ftnptr = mini_get_addr_from_ftnptr;
6283 callbacks.get_runtime_build_info = mono_get_runtime_build_info;
6284 callbacks.set_cast_details = mono_set_cast_details;
6285 callbacks.debug_log = mono_debugger_agent_debug_log;
6286 callbacks.debug_log_is_enabled = mono_debugger_agent_debug_log_is_enabled;
6288 #ifdef MONO_ARCH_HAVE_IMT
6289 if (mono_use_imt) {
6290 callbacks.get_vtable_trampoline = mini_get_vtable_trampoline;
6291 callbacks.get_imt_trampoline = mini_get_imt_trampoline;
6293 #endif
6295 mono_install_callbacks (&callbacks);
6297 memset (&ticallbacks, 0, sizeof (ticallbacks));
6298 ticallbacks.setup_async_callback = mono_setup_async_callback;
6299 ticallbacks.thread_state_init_from_sigctx = mono_thread_state_init_from_sigctx;
6300 ticallbacks.thread_state_init_from_handle = mono_thread_state_init_from_handle;
6302 mono_threads_runtime_init (&ticallbacks);
6305 if (getenv ("MONO_DEBUG") != NULL)
6306 mini_parse_debug_options ();
6308 mono_arch_cpu_init ();
6310 mono_arch_init ();
6312 mono_unwind_init ();
6314 if (getenv ("MONO_XDEBUG")) {
6315 char *xdebug_opts = getenv ("MONO_XDEBUG");
6316 mono_xdebug_init (xdebug_opts);
6317 /* So methods for multiple domains don't have the same address */
6318 mono_dont_free_domains = TRUE;
6319 mono_using_xdebug = TRUE;
6320 } else if (mini_get_debug_options ()->gdb) {
6321 mono_xdebug_init ((char*)"gdb");
6322 mono_dont_free_domains = TRUE;
6323 mono_using_xdebug = TRUE;
6326 #ifdef ENABLE_LLVM
6327 if (mono_use_llvm) {
6328 if (!mono_llvm_load (NULL)) {
6329 mono_use_llvm = FALSE;
6330 fprintf (stderr, "Mono Warning: llvm support could not be loaded.\n");
6333 if (mono_use_llvm)
6334 mono_llvm_init ();
6335 #endif
6337 mono_trampolines_init ();
6339 if (!g_thread_supported ())
6340 g_thread_init (NULL);
6342 mono_native_tls_alloc (&mono_jit_tls_id, NULL);
6343 setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
6345 if (default_opt & MONO_OPT_AOT)
6346 mono_aot_init ();
6348 mono_debugger_agent_init ();
6350 #ifdef MONO_ARCH_GSHARED_SUPPORTED
6351 mono_set_generic_sharing_supported (TRUE);
6352 #endif
6354 #ifndef MONO_CROSS_COMPILE
6355 mono_runtime_install_handlers ();
6356 #endif
6357 mono_threads_install_cleanup (mini_thread_cleanup);
6359 #ifdef MONO_ARCH_HAVE_NOTIFY_PENDING_EXC
6360 // This is experimental code so provide an env var to switch it off
6361 if (getenv ("MONO_DISABLE_PENDING_EXCEPTIONS")) {
6362 printf ("MONO_DISABLE_PENDING_EXCEPTIONS env var set.\n");
6363 } else {
6364 check_for_pending_exc = FALSE;
6365 mono_threads_install_notify_pending_exc (mono_arch_notify_pending_exc);
6367 #endif
6369 #define JIT_TRAMPOLINES_WORK
6370 #ifdef JIT_TRAMPOLINES_WORK
6371 mono_install_compile_method (mono_jit_compile_method);
6372 mono_install_free_method (mono_jit_free_method);
6373 mono_install_trampoline (mono_create_jit_trampoline);
6374 mono_install_jump_trampoline (mono_create_jump_trampoline);
6375 mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
6376 mono_install_delegate_trampoline (mono_create_delegate_trampoline);
6377 mono_install_create_domain_hook (mini_create_jit_domain_info);
6378 mono_install_free_domain_hook (mini_free_jit_domain_info);
6379 #endif
6380 #define JIT_INVOKE_WORKS
6381 #ifdef JIT_INVOKE_WORKS
6382 mono_install_runtime_invoke (mono_jit_runtime_invoke);
6383 #endif
6384 mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
6385 mono_install_get_class_from_name (mono_aot_get_class_from_name);
6386 mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
6388 if (debug_options.collect_pagefault_stats) {
6389 mono_aot_set_make_unreadable (TRUE);
6392 if (runtime_version)
6393 domain = mono_init_version (filename, runtime_version);
6394 else
6395 domain = mono_init_from_assembly (filename, filename);
6397 if (mono_aot_only) {
6398 /* This helps catch code allocation requests */
6399 mono_code_manager_set_read_only (domain->code_mp);
6402 #ifdef MONO_ARCH_HAVE_IMT
6403 if (mono_use_imt) {
6404 if (mono_aot_only)
6405 mono_install_imt_thunk_builder (mono_aot_get_imt_thunk);
6406 else
6407 mono_install_imt_thunk_builder (mono_arch_build_imt_thunk);
6409 #endif
6411 /* This must come after mono_init () in the aot-only case */
6412 mono_exceptions_init ();
6414 mono_icall_init ();
6416 /* This should come after mono_init () too */
6417 mini_gc_init ();
6419 mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info",
6420 ves_icall_get_frame_info);
6421 mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace",
6422 ves_icall_get_trace);
6423 mono_add_internal_call ("System.Exception::get_trace",
6424 ves_icall_System_Exception_get_trace);
6425 mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityFrame",
6426 ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
6427 mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityStack",
6428 ves_icall_System_Security_SecurityFrame_GetSecurityStack);
6429 mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers",
6430 mono_runtime_install_handlers);
6432 mono_create_helper_signatures ();
6434 register_jit_stats ();
6436 #define JIT_CALLS_WORK
6437 #ifdef JIT_CALLS_WORK
6438 /* Needs to be called here since register_jit_icall depends on it */
6439 mono_marshal_init ();
6441 mono_arch_register_lowlevel_calls ();
6442 register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
6443 register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
6444 register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
6445 register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
6446 register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
6447 register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "void", TRUE);
6448 register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
6450 register_icall (mono_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
6451 register_icall (mono_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
6452 register_icall (mono_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception",
6453 "void ptr", TRUE);
6454 register_icall (mono_thread_get_undeniable_exception, "mono_thread_get_undeniable_exception", "object", FALSE);
6455 register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "void", FALSE);
6456 register_icall (mono_thread_force_interruption_checkpoint, "mono_thread_force_interruption_checkpoint", "void", FALSE);
6457 register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
6458 register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
6460 #if defined(__native_client__) || defined(__native_client_codegen__)
6461 register_icall (mono_nacl_gc, "mono_nacl_gc", "void", TRUE);
6462 #endif
6464 * NOTE, NOTE, NOTE, NOTE:
6465 * when adding emulation for some opcodes, remember to also add a dummy
6466 * rule to the burg files, because we need the arity information to be correct.
6468 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
6469 mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, TRUE);
6470 mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, FALSE);
6471 mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, FALSE);
6472 mono_register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, FALSE);
6473 mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, FALSE);
6474 mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, FALSE);
6475 mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, FALSE);
6476 #endif
6478 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
6479 mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, TRUE);
6480 mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, TRUE);
6481 mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, TRUE);
6482 #endif
6484 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
6485 mono_register_opcode_emulation (OP_IDIV, "__emul_op_idiv", "int32 int32 int32", mono_idiv, FALSE);
6486 mono_register_opcode_emulation (OP_IDIV_UN, "__emul_op_idiv_un", "int32 int32 int32", mono_idiv_un, FALSE);
6487 mono_register_opcode_emulation (OP_IREM, "__emul_op_irem", "int32 int32 int32", mono_irem, FALSE);
6488 mono_register_opcode_emulation (OP_IREM_UN, "__emul_op_irem_un", "int32 int32 int32", mono_irem_un, FALSE);
6489 #endif
6491 #ifdef MONO_ARCH_EMULATE_MUL_DIV
6492 mono_register_opcode_emulation (OP_IMUL, "__emul_op_imul", "int32 int32 int32", mono_imul, TRUE);
6493 #endif
6495 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_MUL_OVF)
6496 mono_register_opcode_emulation (OP_IMUL_OVF, "__emul_op_imul_ovf", "int32 int32 int32", mono_imul_ovf, FALSE);
6497 mono_register_opcode_emulation (OP_IMUL_OVF_UN, "__emul_op_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, FALSE);
6498 #endif
6500 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_SOFT_FLOAT)
6501 mono_register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, FALSE);
6502 #endif
6504 mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, FALSE);
6505 mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, FALSE);
6506 mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, FALSE);
6507 mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, FALSE);
6509 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
6510 mono_register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, FALSE);
6511 #endif
6512 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
6513 mono_register_opcode_emulation (OP_ICONV_TO_R_UN, "__emul_iconv_to_r_un", "double int32", mono_conv_to_r8_un, FALSE);
6514 #endif
6515 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
6516 mono_register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, FALSE);
6517 #endif
6518 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
6519 mono_register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, FALSE);
6520 #endif
6521 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
6522 mono_register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", "double long", mono_lconv_to_r8_un, FALSE);
6523 #endif
6524 #ifdef MONO_ARCH_EMULATE_FREM
6525 #if defined(__default_codegen__)
6526 mono_register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, FALSE);
6527 #elif defined(__native_client_codegen__)
6528 mono_register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", mono_fmod, FALSE);
6529 #endif
6530 #endif
6532 #ifdef MONO_ARCH_SOFT_FLOAT
6533 mono_register_opcode_emulation (OP_FSUB, "__emul_fsub", "double double double", mono_fsub, FALSE);
6534 mono_register_opcode_emulation (OP_FADD, "__emul_fadd", "double double double", mono_fadd, FALSE);
6535 mono_register_opcode_emulation (OP_FMUL, "__emul_fmul", "double double double", mono_fmul, FALSE);
6536 mono_register_opcode_emulation (OP_FNEG, "__emul_fneg", "double double", mono_fneg, FALSE);
6537 mono_register_opcode_emulation (OP_ICONV_TO_R8, "__emul_iconv_to_r8", "double int32", mono_conv_to_r8, FALSE);
6538 mono_register_opcode_emulation (OP_ICONV_TO_R4, "__emul_iconv_to_r4", "double int32", mono_conv_to_r4, FALSE);
6539 mono_register_opcode_emulation (OP_FCONV_TO_R4, "__emul_fconv_to_r4", "double double", mono_fconv_r4, FALSE);
6540 mono_register_opcode_emulation (OP_FCONV_TO_I1, "__emul_fconv_to_i1", "int8 double", mono_fconv_i1, FALSE);
6541 mono_register_opcode_emulation (OP_FCONV_TO_I2, "__emul_fconv_to_i2", "int16 double", mono_fconv_i2, FALSE);
6542 mono_register_opcode_emulation (OP_FCONV_TO_I4, "__emul_fconv_to_i4", "int32 double", mono_fconv_i4, FALSE);
6543 mono_register_opcode_emulation (OP_FCONV_TO_U1, "__emul_fconv_to_u1", "uint8 double", mono_fconv_u1, FALSE);
6544 mono_register_opcode_emulation (OP_FCONV_TO_U2, "__emul_fconv_to_u2", "uint16 double", mono_fconv_u2, FALSE);
6545 #if SIZEOF_VOID_P == 4
6546 mono_register_opcode_emulation (OP_FCONV_TO_I, "__emul_fconv_to_i", "int32 double", mono_fconv_i4, FALSE);
6547 #endif
6549 mono_register_opcode_emulation (OP_FBEQ, "__emul_fcmp_eq", "uint32 double double", mono_fcmp_eq, FALSE);
6550 mono_register_opcode_emulation (OP_FBLT, "__emul_fcmp_lt", "uint32 double double", mono_fcmp_lt, FALSE);
6551 mono_register_opcode_emulation (OP_FBGT, "__emul_fcmp_gt", "uint32 double double", mono_fcmp_gt, FALSE);
6552 mono_register_opcode_emulation (OP_FBLE, "__emul_fcmp_le", "uint32 double double", mono_fcmp_le, FALSE);
6553 mono_register_opcode_emulation (OP_FBGE, "__emul_fcmp_ge", "uint32 double double", mono_fcmp_ge, FALSE);
6554 mono_register_opcode_emulation (OP_FBNE_UN, "__emul_fcmp_ne_un", "uint32 double double", mono_fcmp_ne_un, FALSE);
6555 mono_register_opcode_emulation (OP_FBLT_UN, "__emul_fcmp_lt_un", "uint32 double double", mono_fcmp_lt_un, FALSE);
6556 mono_register_opcode_emulation (OP_FBGT_UN, "__emul_fcmp_gt_un", "uint32 double double", mono_fcmp_gt_un, FALSE);
6557 mono_register_opcode_emulation (OP_FBLE_UN, "__emul_fcmp_le_un", "uint32 double double", mono_fcmp_le_un, FALSE);
6558 mono_register_opcode_emulation (OP_FBGE_UN, "__emul_fcmp_ge_un", "uint32 double double", mono_fcmp_ge_un, FALSE);
6560 mono_register_opcode_emulation (OP_FCEQ, "__emul_fcmp_ceq", "uint32 double double", mono_fceq, FALSE);
6561 mono_register_opcode_emulation (OP_FCGT, "__emul_fcmp_cgt", "uint32 double double", mono_fcgt, FALSE);
6562 mono_register_opcode_emulation (OP_FCGT_UN, "__emul_fcmp_cgt_un", "uint32 double double", mono_fcgt_un, FALSE);
6563 mono_register_opcode_emulation (OP_FCLT, "__emul_fcmp_clt", "uint32 double double", mono_fclt, FALSE);
6564 mono_register_opcode_emulation (OP_FCLT_UN, "__emul_fcmp_clt_un", "uint32 double double", mono_fclt_un, FALSE);
6566 register_icall (mono_fload_r4, "mono_fload_r4", "double ptr", FALSE);
6567 register_icall (mono_fstore_r4, "mono_fstore_r4", "void double ptr", FALSE);
6568 register_icall (mono_fload_r4_arg, "mono_fload_r4_arg", "uint32 double", FALSE);
6569 register_icall (mono_isfinite, "mono_isfinite", "uint32 double", FALSE);
6570 #endif
6572 #ifdef COMPRESSED_INTERFACE_BITMAP
6573 register_icall (mono_class_interface_match, "mono_class_interface_match", "uint32 ptr int32", TRUE);
6574 #endif
6576 #if SIZEOF_REGISTER == 4
6577 mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, TRUE);
6578 #endif
6580 /* other jit icalls */
6581 register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
6582 register_icall (mono_class_static_field_address , "mono_class_static_field_address",
6583 "ptr ptr ptr", FALSE);
6584 register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
6585 register_icall (mono_ldtoken_wrapper_generic_shared, "mono_ldtoken_wrapper_generic_shared",
6586 "ptr ptr ptr ptr", FALSE);
6587 register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
6588 register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
6589 register_icall (mono_helper_stelem_ref_check, "helper_stelem_ref_check", "void object object", FALSE);
6590 register_icall (mono_object_new, "mono_object_new", "object ptr ptr", FALSE);
6591 register_icall (mono_object_new_specific, "mono_object_new_specific", "object ptr", FALSE);
6592 register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
6593 register_icall (mono_array_new_specific, "mono_array_new_specific", "object ptr int32", FALSE);
6594 register_icall (mono_runtime_class_init, "mono_runtime_class_init", "void ptr", FALSE);
6595 register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
6596 register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
6597 register_icall (mono_ldvirtfn_gshared, "mono_ldvirtfn_gshared", "ptr object ptr", FALSE);
6598 register_icall (mono_helper_compile_generic_method, "compile_generic_method", "ptr object ptr ptr", FALSE);
6599 register_icall (mono_helper_ldstr, "helper_ldstr", "object ptr int", FALSE);
6600 register_icall (mono_helper_ldstr_mscorlib, "helper_ldstr_mscorlib", "object int", FALSE);
6601 register_icall (mono_helper_newobj_mscorlib, "helper_newobj_mscorlib", "object int", FALSE);
6602 register_icall (mono_value_copy, "mono_value_copy", "void ptr ptr ptr", FALSE);
6603 register_icall (mono_object_castclass, "mono_object_castclass", "object object ptr", FALSE);
6604 register_icall (mono_break, "mono_break", NULL, TRUE);
6605 register_icall (mono_create_corlib_exception_0, "mono_create_corlib_exception_0", "object int", TRUE);
6606 register_icall (mono_create_corlib_exception_1, "mono_create_corlib_exception_1", "object int object", TRUE);
6607 register_icall (mono_create_corlib_exception_2, "mono_create_corlib_exception_2", "object int object object", TRUE);
6608 register_icall (mono_array_new_1, "mono_array_new_1", "object ptr int", FALSE);
6609 register_icall (mono_array_new_2, "mono_array_new_2", "object ptr int int", FALSE);
6610 register_icall (mono_array_new_3, "mono_array_new_3", "object ptr int int int", FALSE);
6611 register_icall (mono_get_native_calli_wrapper, "mono_get_native_calli_wrapper", "ptr ptr ptr ptr", FALSE);
6612 register_icall (mono_resume_unwind, "mono_resume_unwind", "void", TRUE);
6614 register_icall (mono_gc_wbarrier_value_copy_bitmap, "mono_gc_wbarrier_value_copy_bitmap", "void ptr ptr int int", FALSE);
6616 register_icall (mono_object_castclass_with_cache, "mono_object_castclass_with_cache", "object object ptr ptr", FALSE);
6617 register_icall (mono_object_isinst_with_cache, "mono_object_isinst_with_cache", "object object ptr ptr", FALSE);
6619 register_icall (mono_debugger_agent_user_break, "mono_debugger_agent_user_break", "void", FALSE);
6621 #endif
6623 mono_generic_sharing_init ();
6625 #ifdef MONO_ARCH_SIMD_INTRINSICS
6626 mono_simd_intrinsics_init ();
6627 #endif
6629 #if MONO_SUPPORT_TASKLETS
6630 mono_tasklets_init ();
6631 #endif
6633 if (mono_compile_aot)
6635 * Avoid running managed code when AOT compiling, since the platform
6636 * might only support aot-only execution.
6638 mono_runtime_set_no_exec (TRUE);
6640 #define JIT_RUNTIME_WORKS
6641 #ifdef JIT_RUNTIME_WORKS
6642 mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
6643 mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
6644 mono_thread_attach (domain);
6645 #endif
6647 mono_profiler_runtime_initialized ();
6649 MONO_PROBE_VES_INIT_END ();
6651 return domain;
6654 MonoJitStats mono_jit_stats = {0};
6656 static void
6657 print_jit_stats (void)
6659 if (mono_jit_stats.enabled) {
6660 g_print ("Mono Jit statistics\n");
6661 g_print ("Max code size ratio: %.2f (%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
6662 mono_jit_stats.max_ratio_method);
6663 g_print ("Biggest method: %ld (%s)\n", mono_jit_stats.biggest_method_size,
6664 mono_jit_stats.biggest_method);
6666 g_print ("\nCreated object count: %ld\n", mono_stats.new_object_count);
6667 g_print ("Delegates created: %ld\n", mono_stats.delegate_creations);
6668 g_print ("Initialized classes: %ld\n", mono_stats.initialized_class_count);
6669 g_print ("Used classes: %ld\n", mono_stats.used_class_count);
6670 g_print ("Generic vtables: %ld\n", mono_stats.generic_vtable_count);
6671 g_print ("Methods: %ld\n", mono_stats.method_count);
6672 g_print ("Static data size: %ld\n", mono_stats.class_static_data_size);
6673 g_print ("VTable data size: %ld\n", mono_stats.class_vtable_size);
6674 g_print ("Mscorlib mempool size: %d\n", mono_mempool_get_allocated (mono_defaults.corlib->mempool));
6676 g_print ("\nInitialized classes: %ld\n", mono_stats.generic_class_count);
6677 g_print ("Inflated types: %ld\n", mono_stats.inflated_type_count);
6678 g_print ("Generics virtual invokes: %ld\n", mono_jit_stats.generic_virtual_invocations);
6680 g_print ("Sharable generic methods: %ld\n", mono_stats.generics_sharable_methods);
6681 g_print ("Unsharable generic methods: %ld\n", mono_stats.generics_unsharable_methods);
6682 g_print ("Shared generic methods: %ld\n", mono_stats.generics_shared_methods);
6684 g_print ("Dynamic code allocs: %ld\n", mono_stats.dynamic_code_alloc_count);
6685 g_print ("Dynamic code bytes: %ld\n", mono_stats.dynamic_code_bytes_count);
6686 g_print ("Dynamic code frees: %ld\n", mono_stats.dynamic_code_frees_count);
6688 g_print ("IMT tables size: %ld\n", mono_stats.imt_tables_size);
6689 g_print ("IMT number of tables: %ld\n", mono_stats.imt_number_of_tables);
6690 g_print ("IMT number of methods: %ld\n", mono_stats.imt_number_of_methods);
6691 g_print ("IMT used slots: %ld\n", mono_stats.imt_used_slots);
6692 g_print ("IMT colliding slots: %ld\n", mono_stats.imt_slots_with_collisions);
6693 g_print ("IMT max collisions: %ld\n", mono_stats.imt_max_collisions_in_slot);
6694 g_print ("IMT methods at max col: %ld\n", mono_stats.imt_method_count_when_max_collisions);
6695 g_print ("IMT thunks size: %ld\n", mono_stats.imt_thunks_size);
6697 g_print ("JIT info table inserts: %ld\n", mono_stats.jit_info_table_insert_count);
6698 g_print ("JIT info table removes: %ld\n", mono_stats.jit_info_table_remove_count);
6699 g_print ("JIT info table lookups: %ld\n", mono_stats.jit_info_table_lookup_count);
6701 g_print ("Hazardous pointers: %ld\n", mono_stats.hazardous_pointer_count);
6702 g_print ("Minor GC collections: %ld\n", mono_stats.minor_gc_count);
6703 g_print ("Major GC collections: %ld\n", mono_stats.major_gc_count);
6704 g_print ("Minor GC time in msecs: %lf\n", (double)mono_stats.minor_gc_time_usecs / 1000.0);
6705 g_print ("Major GC time in msecs: %lf\n", (double)mono_stats.major_gc_time_usecs / 1000.0);
6706 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
6707 g_print ("\nDecl security check : %ld\n", mono_jit_stats.cas_declsec_check);
6708 g_print ("LinkDemand (user) : %ld\n", mono_jit_stats.cas_linkdemand);
6709 g_print ("LinkDemand (icall) : %ld\n", mono_jit_stats.cas_linkdemand_icall);
6710 g_print ("LinkDemand (pinvoke) : %ld\n", mono_jit_stats.cas_linkdemand_pinvoke);
6711 g_print ("LinkDemand (aptc) : %ld\n", mono_jit_stats.cas_linkdemand_aptc);
6712 g_print ("Demand (code gen) : %ld\n", mono_jit_stats.cas_demand_generation);
6715 g_free (mono_jit_stats.max_ratio_method);
6716 mono_jit_stats.max_ratio_method = NULL;
6717 g_free (mono_jit_stats.biggest_method);
6718 mono_jit_stats.biggest_method = NULL;
6722 void
6723 mini_cleanup (MonoDomain *domain)
6725 mono_runtime_shutdown_stat_profiler ();
6727 #ifndef DISABLE_COM
6728 cominterop_release_all_rcws ();
6729 #endif
6731 #ifndef MONO_CROSS_COMPILE
6732 mono_runtime_shutdown ();
6734 * mono_runtime_cleanup() and mono_domain_finalize () need to
6735 * be called early since they need the execution engine still
6736 * fully working (mono_domain_finalize may invoke managed finalizers
6737 * and mono_runtime_cleanup will wait for other threads to finish).
6739 mono_domain_finalize (domain, 2000);
6740 #endif
6742 /* This accesses metadata so needs to be called before runtime shutdown */
6743 print_jit_stats ();
6745 mono_profiler_shutdown ();
6747 #ifndef MONO_CROSS_COMPILE
6748 mono_runtime_cleanup (domain);
6749 #endif
6751 free_jit_tls_data (mono_native_tls_get_value (mono_jit_tls_id));
6753 mono_icall_cleanup ();
6755 mono_runtime_cleanup_handlers ();
6757 mono_domain_free (domain, TRUE);
6759 mono_debugger_cleanup ();
6761 #ifdef ENABLE_LLVM
6762 if (mono_use_llvm)
6763 mono_llvm_cleanup ();
6764 #endif
6766 mono_aot_cleanup ();
6768 mono_trampolines_cleanup ();
6770 mono_unwind_cleanup ();
6772 if (!mono_dont_free_global_codeman)
6773 mono_code_manager_destroy (global_codeman);
6774 g_hash_table_destroy (jit_icall_name_hash);
6775 g_free (emul_opcode_map);
6776 g_free (emul_opcode_opcodes);
6777 g_free (vtable_trampolines);
6779 mono_arch_cleanup ();
6781 mono_generic_sharing_cleanup ();
6783 mono_cleanup ();
6785 mono_trace_cleanup ();
6787 mono_counters_dump (-1, stdout);
6789 if (mono_inject_async_exc_method)
6790 mono_method_desc_free (mono_inject_async_exc_method);
6792 mono_native_tls_free (mono_jit_tls_id);
6794 DeleteCriticalSection (&jit_mutex);
6796 DeleteCriticalSection (&mono_delegate_section);
6799 void
6800 mono_set_defaults (int verbose_level, guint32 opts)
6802 mini_verbose = verbose_level;
6803 default_opt = opts;
6804 default_opt_set = TRUE;
6807 void
6808 mono_disable_optimizations (guint32 opts)
6810 default_opt &= ~opts;
6813 void
6814 mono_set_optimizations (guint32 opts)
6816 default_opt = opts;
6817 default_opt_set = TRUE;
6820 void
6821 mono_set_verbose_level (guint32 level)
6823 mini_verbose = level;
6827 * mono_get_runtime_build_info:
6829 * Return the runtime version + build date in string format.
6830 * The returned string is owned by the caller.
6832 char*
6833 mono_get_runtime_build_info (void)
6835 if (mono_build_date)
6836 return g_strdup_printf ("%s (%s %s)", VERSION, FULL_VERSION, mono_build_date);
6837 else
6838 return g_strdup_printf ("%s (%s)", VERSION, FULL_VERSION);
6841 static void
6842 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
6844 GHashTable *assemblies = (GHashTable*)user_data;
6845 MonoImage *image = mono_assembly_get_image (ass);
6846 MonoMethod *method, *invoke;
6847 int i, count = 0;
6849 if (g_hash_table_lookup (assemblies, ass))
6850 return;
6852 g_hash_table_insert (assemblies, ass, ass);
6854 if (mini_verbose > 0)
6855 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
6857 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
6858 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
6859 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
6860 continue;
6862 count++;
6863 if (mini_verbose > 1) {
6864 char * desc = mono_method_full_name (method, TRUE);
6865 g_print ("Compiling %d %s\n", count, desc);
6866 g_free (desc);
6868 mono_compile_method (method);
6869 if (strcmp (method->name, "Finalize") == 0) {
6870 invoke = mono_marshal_get_runtime_invoke (method, FALSE);
6871 mono_compile_method (invoke);
6873 if (method->klass->marshalbyref && mono_method_signature (method)->hasthis) {
6874 invoke = mono_marshal_get_remoting_invoke_with_check (method);
6875 mono_compile_method (invoke);
6879 /* Load and precompile referenced assemblies as well */
6880 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
6881 mono_assembly_load_reference (image, i);
6882 if (image->references [i])
6883 mono_precompile_assembly (image->references [i], assemblies);
6887 void mono_precompile_assemblies ()
6889 GHashTable *assemblies = g_hash_table_new (NULL, NULL);
6891 mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
6893 g_hash_table_destroy (assemblies);
6896 #ifndef DISABLE_JIT
6898 void*
6899 mono_arch_instrument_epilog (MonoCompile *cfg, void *func, void *p, gboolean enable_arguments) {
6900 return mono_arch_instrument_epilog_full (cfg, func, p, enable_arguments, FALSE);
6903 void
6904 mono_cfg_add_try_hole (MonoCompile *cfg, MonoExceptionClause *clause, guint8 *start, MonoBasicBlock *bb)
6906 TryBlockHole *hole = mono_mempool_alloc (cfg->mempool, sizeof (TryBlockHole));
6907 hole->clause = clause;
6908 hole->start_offset = start - cfg->native_code;
6909 hole->basic_block = bb;
6911 cfg->try_block_holes = g_slist_append_mempool (cfg->mempool, cfg->try_block_holes, hole);
6914 void
6915 mono_cfg_set_exception (MonoCompile *cfg, int type)
6917 cfg->exception_type = type;
6920 #endif