2 * mini.c: The new Mono code generator.
5 * Paolo Molaro (lupus@ximian.com)
6 * Dietmar Maurer (dietmar@ximian.com)
8 * (C) 2002 Ximian, Inc.
17 #ifdef HAVE_SYS_TIME_H
21 #ifdef PLATFORM_MACOSX
22 #include <mach/mach.h>
23 #include <mach/mach_error.h>
24 #include <mach/exception.h>
25 #include <mach/task.h>
29 #ifdef HAVE_VALGRIND_MEMCHECK_H
30 #include <valgrind/memcheck.h>
33 #include <mono/metadata/assembly.h>
34 #include <mono/metadata/loader.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/class.h>
37 #include <mono/metadata/object.h>
38 #include <mono/metadata/exception.h>
39 #include <mono/metadata/opcodes.h>
40 #include <mono/metadata/mono-endian.h>
41 #include <mono/metadata/tokentype.h>
42 #include <mono/metadata/tabledefs.h>
43 #include <mono/metadata/threads.h>
44 #include <mono/metadata/marshal.h>
45 #include <mono/metadata/socket-io.h>
46 #include <mono/metadata/appdomain.h>
47 #include <mono/metadata/debug-helpers.h>
48 #include <mono/io-layer/io-layer.h>
49 #include "mono/metadata/profiler.h"
50 #include <mono/metadata/profiler-private.h>
51 #include <mono/metadata/mono-config.h>
52 #include <mono/metadata/environment.h>
53 #include <mono/metadata/mono-debug.h>
54 #include <mono/metadata/monitor.h>
55 #include <mono/metadata/gc-internal.h>
56 #include <mono/metadata/security-manager.h>
57 #include <mono/metadata/threads-types.h>
58 #include <mono/metadata/rawbuffer.h>
59 #include <mono/metadata/security-core-clr.h>
60 #include <mono/metadata/verify.h>
61 #include <mono/metadata/verify-internals.h>
62 #include <mono/utils/mono-math.h>
63 #include <mono/utils/mono-compiler.h>
64 #include <mono/utils/mono-counters.h>
65 #include <mono/utils/mono-logger.h>
66 #include <mono/utils/mono-mmap.h>
67 #include <mono/utils/dtrace.h>
75 #include "jit-icalls.h"
79 #include "debug-mini.h"
81 #define BRANCH_COST 100
82 #define INLINE_LENGTH_LIMIT 20
83 #define INLINE_FAILURE do {\
84 if ((cfg->method != method) && (method->wrapper_type == MONO_WRAPPER_NONE))\
87 #define CHECK_CFG_EXCEPTION do {\
88 if (cfg->exception_type != MONO_EXCEPTION_NONE)\
91 #define METHOD_ACCESS_FAILURE do { \
92 char *method_fname = mono_method_full_name (method, TRUE); \
93 char *cil_method_fname = mono_method_full_name (cil_method, TRUE); \
94 cfg->exception_type = MONO_EXCEPTION_METHOD_ACCESS; \
95 cfg->exception_message = g_strdup_printf ("Method `%s' is inaccessible from method `%s'\n", cil_method_fname, method_fname); \
96 g_free (method_fname); \
97 g_free (cil_method_fname); \
98 goto exception_exit; \
100 #define FIELD_ACCESS_FAILURE do { \
101 char *method_fname = mono_method_full_name (method, TRUE); \
102 char *field_fname = mono_field_full_name (field); \
103 cfg->exception_type = MONO_EXCEPTION_FIELD_ACCESS; \
104 cfg->exception_message = g_strdup_printf ("Field `%s' is inaccessible from method `%s'\n", field_fname, method_fname); \
105 g_free (method_fname); \
106 g_free (field_fname); \
107 goto exception_exit; \
109 #define GENERIC_SHARING_FAILURE(opcode) do { \
110 if (cfg->generic_sharing_context) { \
111 if (cfg->verbose_level > 1) \
112 printf ("sharing failed for method %s.%s.%s/%d opcode %s line %d\n", method->klass->name_space, method->klass->name, method->name, method->signature->param_count, mono_opcode_name ((opcode)), __LINE__); \
113 cfg->exception_type = MONO_EXCEPTION_GENERIC_SHARING_FAILED; \
114 goto exception_exit; \
117 #define GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD(opcode) do { \
118 if (method->klass->valuetype) \
119 GENERIC_SHARING_FAILURE ((opcode)); \
121 #define GET_RGCTX(rgctx) do { \
122 MonoInst *this = NULL; \
123 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD(*ip); \
124 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) \
125 NEW_ARGLOAD (cfg, this, 0); \
126 (rgctx) = get_runtime_generic_context (cfg, method, this, ip); \
129 #define MONO_CHECK_THIS(ins) (mono_method_signature (cfg->method)->hasthis && (ins)->ssa_op == MONO_SSA_LOAD && (ins)->inst_left->inst_c0 == 0)
131 static void setup_stat_profiler (void);
132 gboolean mono_arch_print_tree(MonoInst *tree, int arity);
133 static gpointer mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt);
134 static gpointer mono_jit_compile_method (MonoMethod *method);
135 inline static int mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip);
137 static void handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src,
138 const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native, gboolean write_barrier);
140 static void dec_foreach (MonoInst *tree, MonoCompile *cfg);
142 static int mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock,
143 int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args,
144 guint inline_offset, gboolean is_virtual_call);
146 #ifdef MONO_ARCH_SOFT_FLOAT
148 handle_store_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, MonoInst *val, const unsigned char *ip);
151 /* helper methods signature */
152 static MonoMethodSignature *helper_sig_class_init_trampoline = NULL;
153 static MonoMethodSignature *helper_sig_generic_class_init_trampoline = NULL;
154 static MonoMethodSignature *helper_sig_rgctx_lazy_fetch_trampoline = NULL;
155 static MonoMethodSignature *helper_sig_domain_get = NULL;
157 static guint32 default_opt = 0;
158 static gboolean default_opt_set = FALSE;
160 guint32 mono_jit_tls_id = -1;
162 #ifdef HAVE_KW_THREAD
163 static __thread gpointer mono_jit_tls MONO_TLS_FAST;
166 MonoTraceSpec *mono_jit_trace_calls = NULL;
167 gboolean mono_break_on_exc = FALSE;
169 gboolean mono_compile_aot = FALSE;
171 MonoMethodDesc *mono_inject_async_exc_method = NULL;
172 int mono_inject_async_exc_pos;
173 MonoMethodDesc *mono_break_at_bb_method = NULL;
174 int mono_break_at_bb_bb_num;
176 static int mini_verbose = 0;
178 #define mono_jit_lock() EnterCriticalSection (&jit_mutex)
179 #define mono_jit_unlock() LeaveCriticalSection (&jit_mutex)
180 static CRITICAL_SECTION jit_mutex;
182 static GHashTable *rgctx_lazy_fetch_trampoline_hash = NULL;
184 static MonoCodeManager *global_codeman = NULL;
186 static GHashTable *jit_icall_name_hash = NULL;
188 static MonoDebugOptions debug_options;
190 #ifdef VALGRIND_JIT_REGISTER_MAP
191 static int valgrind_register = 0;
195 * Table written to by the debugger with a 1-based index into the
196 * mono_breakpoint_info table, which contains changes made to
197 * the JIT instructions by the debugger.
200 mono_breakpoint_info_index [MONO_BREAKPOINT_ARRAY_SIZE];
202 /* Whenever to check for pending exceptions in managed-to-native wrappers */
203 gboolean check_for_pending_exc = TRUE;
206 mono_running_on_valgrind (void)
208 #ifdef HAVE_VALGRIND_MEMCHECK_H
209 if (RUNNING_ON_VALGRIND){
210 #ifdef VALGRIND_JIT_REGISTER_MAP
211 valgrind_register = TRUE;
227 find_tramp (gpointer key, gpointer value, gpointer user_data)
229 FindTrampUserData *ud = (FindTrampUserData*)user_data;
232 ud->method = (MonoMethod*)key;
236 G_GNUC_UNUSED static char*
237 get_method_from_ip (void *ip)
242 MonoDomain *domain = mono_domain_get ();
243 MonoDebugSourceLocation *location;
244 FindTrampUserData user_data;
246 ji = mono_jit_info_table_find (domain, ip);
249 user_data.method = NULL;
250 mono_domain_lock (domain);
251 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
252 mono_domain_unlock (domain);
253 if (user_data.method) {
254 char *mname = mono_method_full_name (user_data.method, TRUE);
255 res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
262 method = mono_method_full_name (ji->method, TRUE);
263 /* FIXME: unused ? */
264 location = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
266 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);
268 mono_debug_free_source_location (location);
276 * @ip: an instruction pointer address
278 * This method is used from a debugger to get the name of the
279 * method at address @ip. This routine is typically invoked from
280 * a debugger like this:
282 * (gdb) print mono_pmip ($pc)
284 * Returns: the name of the method at address @ip.
289 return get_method_from_ip (ip);
293 * mono_print_method_from_ip
294 * @ip: an instruction pointer address
296 * This method is used from a debugger to get the name of the
297 * method at address @ip.
299 * This prints the name of the method at address @ip in the standard
300 * output. Unlike mono_pmip which returns a string, this routine
301 * prints the value on the standard output.
304 mono_print_method_from_ip (void *ip)
308 MonoDebugSourceLocation *source;
309 MonoDomain *domain = mono_domain_get ();
310 FindTrampUserData user_data;
312 ji = mono_jit_info_table_find (domain, ip);
315 user_data.method = NULL;
316 mono_domain_lock (domain);
317 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
318 mono_domain_unlock (domain);
319 if (user_data.method) {
320 char *mname = mono_method_full_name (user_data.method, TRUE);
321 printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
325 g_print ("No method at %p\n", ip);
328 method = mono_method_full_name (ji->method, TRUE);
329 source = mono_debug_lookup_source_location (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), domain);
331 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, domain, domain->friendly_name);
334 g_print ("%s:%d\n", source->source_file, source->row);
336 mono_debug_free_source_location (source);
341 * mono_method_same_domain:
343 * Determine whenever two compiled methods are in the same domain, thus
344 * the address of the callee can be embedded in the caller.
346 gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
348 if (!caller || !callee)
352 * If the call was made from domain-neutral to domain-specific
353 * code, we can't patch the call site.
355 if (caller->domain_neutral && !callee->domain_neutral)
358 if ((caller->method->klass == mono_defaults.appdomain_class) &&
359 (strstr (caller->method->name, "InvokeInDomain"))) {
360 /* The InvokeInDomain methods change the current appdomain */
368 * mono_global_codeman_reserve:
370 * Allocate code memory from the global code manager.
372 void *mono_global_codeman_reserve (int size)
376 if (!global_codeman) {
377 /* This can happen during startup */
378 global_codeman = mono_code_manager_new ();
379 return mono_code_manager_reserve (global_codeman, size);
383 ptr = mono_code_manager_reserve (global_codeman, size);
390 mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
392 MonoJumpInfoToken *res = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
399 #define MONO_INIT_VARINFO(vi,id) do { \
400 (vi)->range.first_use.pos.bid = 0xffff; \
405 //#define UNVERIFIED do { G_BREAKPOINT (); goto unverified; } while (0)
406 #define UNVERIFIED do { if (debug_options.break_on_unverified) G_BREAKPOINT (); else goto unverified; } while (0)
409 * Basic blocks have two numeric identifiers:
410 * dfn: Depth First Number
411 * block_num: unique ID assigned at bblock creation
413 #define NEW_BBLOCK(cfg,new_bb) do { \
414 new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock)); \
415 MONO_INST_LIST_INIT (&new_bb->ins_list); \
418 #define ADD_BBLOCK(cfg,b) do { \
419 cfg->cil_offset_to_bb [(b)->cil_code - cfg->cil_start] = (b); \
420 (b)->block_num = cfg->num_bblocks++; \
421 (b)->real_offset = real_offset; \
424 #define GET_BBLOCK(cfg,tblock,ip) do { \
425 (tblock) = cfg->cil_offset_to_bb [(ip) - cfg->cil_start]; \
427 if ((ip) >= end || (ip) < header->code) UNVERIFIED; \
428 NEW_BBLOCK (cfg, (tblock)); \
429 (tblock)->cil_code = (ip); \
430 ADD_BBLOCK (cfg, (tblock)); \
434 #define CHECK_BBLOCK(target,ip,tblock) do { \
435 if ((target) < (ip) && \
436 MONO_INST_LIST_EMPTY (&(tblock)->ins_list)) { \
437 bb_recheck = g_list_prepend (bb_recheck, (tblock)); \
438 if (cfg->verbose_level > 2) \
439 g_print ("queued block %d for check at IL%04x from IL%04x\n", (tblock)->block_num, (int)((target) - header->code), (int)((ip) - header->code)); \
443 #define NEW_ICONST(cfg,dest,val) do { \
444 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
445 (dest)->opcode = OP_ICONST; \
446 (dest)->inst_c0 = (val); \
447 (dest)->type = STACK_I4; \
450 #define NEW_PCONST(cfg,dest,val) do { \
451 MONO_INST_NEW ((cfg), (dest), OP_PCONST); \
452 (dest)->inst_p0 = (val); \
453 (dest)->type = STACK_PTR; \
457 #ifdef MONO_ARCH_NEED_GOT_VAR
459 #define NEW_PATCH_INFO(cfg,dest,el1,el2) do { \
460 MONO_INST_NEW ((cfg), (dest), OP_PATCH_INFO); \
461 (dest)->inst_left = (gpointer)(el1); \
462 (dest)->inst_right = (gpointer)(el2); \
465 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do { \
466 MONO_INST_NEW ((cfg), (dest), OP_NOP); \
467 (dest)->opcode = cfg->compile_aot ? OP_GOT_ENTRY : OP_PCONST; \
468 if (cfg->compile_aot) { \
469 MonoInst *group, *got_var, *got_loc; \
470 got_loc = mono_get_got_var (cfg); \
471 NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0); \
472 NEW_PATCH_INFO ((cfg), group, cons, patch_type); \
473 (dest)->inst_p0 = got_var; \
474 (dest)->inst_p1 = group; \
476 (dest)->inst_p0 = (cons); \
477 (dest)->inst_i1 = (gpointer)(patch_type); \
479 (dest)->type = STACK_PTR; \
482 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type,stack_class) do { \
483 MonoInst *group, *got_var, *got_loc; \
484 MONO_INST_NEW ((cfg), (dest), OP_GOT_ENTRY); \
485 got_loc = mono_get_got_var (cfg); \
486 NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0); \
487 NEW_PATCH_INFO ((cfg), group, NULL, patch_type); \
488 group->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token)); \
489 (dest)->inst_p0 = got_var; \
490 (dest)->inst_p1 = group; \
491 (dest)->type = (stack_type); \
492 (dest)->klass = (stack_class); \
497 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do { \
498 MONO_INST_NEW ((cfg), (dest), OP_NOP); \
499 (dest)->opcode = cfg->compile_aot ? OP_AOTCONST : OP_PCONST; \
500 (dest)->inst_p0 = (cons); \
501 (dest)->inst_i1 = (gpointer)(patch_type); \
502 (dest)->type = STACK_PTR; \
505 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type,stack_class) do { \
506 MONO_INST_NEW ((cfg), (dest), OP_AOTCONST); \
507 (dest)->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token)); \
508 (dest)->inst_p1 = (gpointer)(patch_type); \
509 (dest)->type = (stack_type); \
510 (dest)->klass = (stack_class); \
515 #define NEW_CLASSCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_CLASS, (val))
517 #define NEW_IMAGECONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_IMAGE, (val))
519 #define NEW_FIELDCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_FIELD, (val))
521 #define NEW_METHODCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_METHODCONST, (val))
523 #define NEW_VTABLECONST(cfg,dest,vtable) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_VTABLE, cfg->compile_aot ? (gpointer)((vtable)->klass) : (vtable))
525 #define NEW_SFLDACONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_SFLDA, (val))
527 #define NEW_LDSTRCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDSTR, (image), (token), STACK_OBJ, mono_defaults.string_class)
529 #define NEW_TYPE_FROM_HANDLE_CONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_TYPE_FROM_HANDLE, (image), (token), STACK_OBJ, mono_defaults.monotype_class)
531 #define NEW_LDTOKENCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDTOKEN, (image), (token), STACK_PTR, NULL)
533 #define NEW_DECLSECCONST(cfg,dest,image,entry) do { \
534 if (cfg->compile_aot) { \
535 NEW_AOTCONST_TOKEN (cfg, dest, MONO_PATCH_INFO_DECLSEC, image, (entry).index, STACK_OBJ, NULL); \
537 NEW_PCONST (cfg, args [0], (entry).blob); \
541 #define NEW_DOMAINCONST(cfg,dest) do { \
542 if (cfg->opt & MONO_OPT_SHARED) { \
543 /* avoid depending on undefined C behavior in sequence points */ \
544 MonoInst* __domain_var = mono_get_domainvar (cfg); \
545 NEW_TEMPLOAD (cfg, dest, __domain_var->inst_c0); \
547 NEW_PCONST (cfg, dest, (cfg)->domain); \
551 #define GET_VARINFO_INST(cfg,num) ((cfg)->varinfo [(num)]->inst)
553 #define NEW_ARGLOAD(cfg,dest,num) do { \
554 if (arg_array [(num)]->opcode == OP_ICONST) (dest) = arg_array [(num)]; else { \
555 MONO_INST_NEW ((cfg), (dest), OP_NOP); \
556 (dest)->ssa_op = MONO_SSA_LOAD; \
557 (dest)->inst_i0 = arg_array [(num)]; \
558 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
559 type_to_eval_stack_type ((cfg), param_types [(num)], (dest)); \
560 (dest)->klass = (dest)->inst_i0->klass; \
563 #define NEW_LOCLOAD(cfg,dest,num) do { \
564 MONO_INST_NEW ((cfg), (dest), OP_NOP); \
565 (dest)->ssa_op = MONO_SSA_LOAD; \
566 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)]; \
567 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
568 type_to_eval_stack_type ((cfg), header->locals [(num)], (dest)); \
569 (dest)->klass = (dest)->inst_i0->klass; \
572 #define NEW_LOCLOADA(cfg,dest,num) do { \
573 MONO_INST_NEW ((cfg), (dest), OP_LDADDR); \
574 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN; \
575 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)]; \
576 (dest)->inst_i0->flags |= MONO_INST_INDIRECT; \
577 (dest)->type = STACK_MP; \
578 (dest)->klass = (dest)->inst_i0->klass; \
579 if (!MONO_TYPE_ISSTRUCT (header->locals [(num)])) \
580 (cfg)->disable_ssa = TRUE; \
583 #define NEW_RETLOADA(cfg,dest) do { \
584 if (cfg->vret_addr) { \
585 MONO_INST_NEW ((cfg), (dest), OP_NOP); \
586 (dest)->ssa_op = MONO_SSA_LOAD; \
587 (dest)->inst_i0 = cfg->vret_addr; \
588 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
589 (dest)->type = STACK_MP; \
590 (dest)->klass = (dest)->inst_i0->klass; \
592 MONO_INST_NEW ((cfg), (dest), OP_NOP); \
593 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN; \
594 (dest)->inst_i0 = (cfg)->ret; \
595 (dest)->inst_i0->flags |= MONO_INST_INDIRECT; \
596 (dest)->opcode = cfg->ret_var_is_local ? OP_LDADDR : CEE_LDIND_I; \
597 (dest)->type = STACK_MP; \
598 (dest)->klass = (dest)->inst_i0->klass; \
599 (cfg)->disable_ssa = TRUE; \
603 #define NEW_ARGLOADA(cfg,dest,num) do { \
604 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
605 MONO_INST_NEW ((cfg), (dest), OP_LDADDR); \
606 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN; \
607 (dest)->inst_i0 = arg_array [(num)]; \
608 (dest)->inst_i0->flags |= MONO_INST_INDIRECT; \
609 (dest)->type = STACK_MP; \
610 (dest)->klass = (dest)->inst_i0->klass; \
611 (cfg)->disable_ssa = TRUE; \
614 #define NEW_TEMPLOAD(cfg,dest,num) do { \
615 MONO_INST_NEW ((cfg), (dest), OP_NOP); \
616 (dest)->ssa_op = MONO_SSA_LOAD; \
617 (dest)->inst_i0 = (cfg)->varinfo [(num)]; \
618 (dest)->opcode = mini_type_to_ldind ((cfg), (dest)->inst_i0->inst_vtype); \
619 type_to_eval_stack_type ((cfg), (dest)->inst_i0->inst_vtype, (dest)); \
620 (dest)->klass = (dest)->inst_i0->klass; \
623 #define NEW_TEMPLOADA(cfg,dest,num) do { \
624 MONO_INST_NEW ((cfg), (dest), OP_LDADDR); \
625 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN; \
626 (dest)->inst_i0 = (cfg)->varinfo [(num)]; \
627 (dest)->inst_i0->flags |= MONO_INST_INDIRECT; \
628 (dest)->type = STACK_MP; \
629 (dest)->klass = (dest)->inst_i0->klass; \
630 if (!MONO_TYPE_ISSTRUCT (cfg->varinfo [(num)]->inst_vtype)) \
631 (cfg)->disable_ssa = TRUE; \
635 #define NEW_INDLOAD(cfg,dest,addr,vtype) do { \
636 MONO_INST_NEW ((cfg), (dest), OP_NOP); \
637 (dest)->inst_left = addr; \
638 (dest)->opcode = mini_type_to_ldind ((cfg), vtype); \
639 type_to_eval_stack_type ((cfg), vtype, (dest)); \
640 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/ \
643 #define NEW_INDSTORE(cfg,dest,addr,value,vtype) do { \
644 MONO_INST_NEW ((cfg), (dest), OP_NOP); \
645 (dest)->inst_i0 = addr; \
646 (dest)->opcode = mini_type_to_stind ((cfg), vtype); \
647 (dest)->inst_i1 = (value); \
648 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/ \
651 #define NEW_TEMPSTORE(cfg,dest,num,inst) do { \
652 MONO_INST_NEW ((cfg), (dest), OP_NOP); \
653 (dest)->ssa_op = MONO_SSA_STORE; \
654 (dest)->inst_i0 = (cfg)->varinfo [(num)]; \
655 (dest)->opcode = mini_type_to_stind ((cfg), (dest)->inst_i0->inst_vtype); \
656 (dest)->inst_i1 = (inst); \
657 (dest)->klass = (dest)->inst_i0->klass; \
660 #define NEW_LOCSTORE(cfg,dest,num,inst) do { \
661 MONO_INST_NEW ((cfg), (dest), OP_NOP); \
662 (dest)->opcode = mini_type_to_stind ((cfg), header->locals [(num)]); \
663 (dest)->ssa_op = MONO_SSA_STORE; \
664 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)]; \
665 (dest)->inst_i1 = (inst); \
666 (dest)->klass = (dest)->inst_i0->klass; \
669 #define NEW_ARGSTORE(cfg,dest,num,inst) do { \
670 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
671 MONO_INST_NEW ((cfg), (dest), OP_NOP); \
672 (dest)->opcode = mini_type_to_stind ((cfg), param_types [(num)]); \
673 (dest)->ssa_op = MONO_SSA_STORE; \
674 (dest)->inst_i0 = arg_array [(num)]; \
675 (dest)->inst_i1 = (inst); \
676 (dest)->klass = (dest)->inst_i0->klass; \
679 #define NEW_MEMCPY(cfg,dest,dst,src,memcpy_size,memcpy_align) do { \
680 MONO_INST_NEW (cfg, dest, OP_MEMCPY); \
681 (dest)->inst_left = (dst); \
682 (dest)->inst_right = (src); \
683 (dest)->backend.memcpy_args = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoMemcpyArgs)); \
684 (dest)->backend.memcpy_args->size = (memcpy_size); \
685 (dest)->backend.memcpy_args->align = (memcpy_align); \
688 #define NEW_MEMSET(cfg,dest,dst,imm,memcpy_size,memcpy_align) do { \
689 MONO_INST_NEW (cfg, dest, OP_MEMSET); \
690 (dest)->inst_left = (dst); \
691 (dest)->inst_imm = (imm); \
692 (dest)->backend.memcpy_args = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoMemcpyArgs)); \
693 (dest)->backend.memcpy_args->size = (memcpy_size); \
694 (dest)->backend.memcpy_args->align = (memcpy_align); \
697 #define NEW_DUMMY_USE(cfg,dest,load) do { \
698 MONO_INST_NEW ((cfg), (dest), OP_DUMMY_USE); \
699 (dest)->inst_left = (load); \
702 #define NEW_DUMMY_STORE(cfg,dest,num) do { \
703 MONO_INST_NEW ((cfg), (dest), OP_DUMMY_STORE); \
704 (dest)->inst_i0 = (cfg)->varinfo [(num)]; \
705 (dest)->klass = (dest)->inst_i0->klass; \
708 #define ADD_BINOP(op) do { \
709 MONO_INST_NEW (cfg, ins, (op)); \
711 ins->inst_i0 = sp [0]; \
712 ins->inst_i1 = sp [1]; \
714 type_from_op (ins); \
718 #define ADD_UNOP(op) do { \
719 MONO_INST_NEW (cfg, ins, (op)); \
721 ins->inst_i0 = sp [0]; \
723 type_from_op (ins); \
727 #define ADD_BINCOND(next_block) do { \
730 MONO_INST_NEW(cfg, cmp, OP_COMPARE); \
731 cmp->inst_i0 = sp [0]; \
732 cmp->inst_i1 = sp [1]; \
733 cmp->cil_code = ins->cil_code; \
734 type_from_op (cmp); \
736 ins->inst_i0 = cmp; \
737 MONO_ADD_INS (bblock, ins); \
738 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2); \
739 GET_BBLOCK (cfg, tblock, target); \
740 link_bblock (cfg, bblock, tblock); \
741 ins->inst_true_bb = tblock; \
742 CHECK_BBLOCK (target, ip, tblock); \
743 if ((next_block)) { \
744 link_bblock (cfg, bblock, (next_block)); \
745 ins->inst_false_bb = (next_block); \
746 start_new_bblock = 1; \
748 GET_BBLOCK (cfg, tblock, ip); \
749 link_bblock (cfg, bblock, tblock); \
750 ins->inst_false_bb = tblock; \
751 start_new_bblock = 2; \
755 /* FIXME: handle float, long ... */
756 #define ADD_UNCOND(istrue) do { \
759 MONO_INST_NEW(cfg, cmp, OP_COMPARE); \
760 cmp->inst_i0 = sp [0]; \
761 switch (cmp->inst_i0->type) { \
763 cmp->inst_i1 = zero_int64; break; \
765 cmp->inst_i1 = zero_r8; break; \
768 cmp->inst_i1 = zero_ptr; break; \
770 cmp->inst_i1 = zero_obj; break; \
772 cmp->inst_i1 = zero_int32; \
774 cmp->cil_code = ins->cil_code; \
775 type_from_op (cmp); \
777 ins->inst_i0 = cmp; \
778 ins->opcode = (istrue)? CEE_BNE_UN: CEE_BEQ; \
779 MONO_ADD_INS (bblock, ins); \
780 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2); \
781 GET_BBLOCK (cfg, tblock, target); \
782 link_bblock (cfg, bblock, tblock); \
783 ins->inst_true_bb = tblock; \
784 CHECK_BBLOCK (target, ip, tblock); \
785 GET_BBLOCK (cfg, tblock, ip); \
786 link_bblock (cfg, bblock, tblock); \
787 ins->inst_false_bb = tblock; \
788 start_new_bblock = 2; \
791 #define NEW_LDELEMA(cfg,dest,sp,k) do { \
792 MONO_INST_NEW ((cfg), (dest), CEE_LDELEMA); \
793 (dest)->inst_left = (sp) [0]; \
794 (dest)->inst_right = (sp) [1]; \
795 (dest)->type = STACK_MP; \
796 (dest)->klass = (k); \
797 (cfg)->flags |= MONO_CFG_HAS_LDELEMA; \
800 #define NEW_GROUP(cfg,dest,el1,el2) do { \
801 MONO_INST_NEW ((cfg), (dest), OP_GROUP); \
802 (dest)->inst_left = (el1); \
803 (dest)->inst_right = (el2); \
808 compare_bblock (gconstpointer a, gconstpointer b)
810 const MonoBasicBlock *b1 = a;
811 const MonoBasicBlock *b2 = b;
813 return b2->cil_code - b1->cil_code;
818 * link_bblock: Links two basic blocks
820 * links two basic blocks in the control flow graph, the 'from'
821 * argument is the starting block and the 'to' argument is the block
822 * the control flow ends to after 'from'.
825 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
827 MonoBasicBlock **newa;
831 if (from->cil_code) {
833 g_print ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
835 g_print ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
838 g_print ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
840 g_print ("edge from entry to exit\n");
844 for (i = 0; i < from->out_count; ++i) {
845 if (to == from->out_bb [i]) {
851 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
852 for (i = 0; i < from->out_count; ++i) {
853 newa [i] = from->out_bb [i];
861 for (i = 0; i < to->in_count; ++i) {
862 if (from == to->in_bb [i]) {
868 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
869 for (i = 0; i < to->in_count; ++i) {
870 newa [i] = to->in_bb [i];
879 * mono_unlink_bblock:
881 * Unlink two basic blocks.
884 mono_unlink_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
890 for (i = 0; i < from->out_count; ++i) {
891 if (to == from->out_bb [i]) {
898 for (i = 0; i < from->out_count; ++i) {
899 if (from->out_bb [i] != to)
900 from->out_bb [pos ++] = from->out_bb [i];
902 g_assert (pos == from->out_count - 1);
907 for (i = 0; i < to->in_count; ++i) {
908 if (from == to->in_bb [i]) {
915 for (i = 0; i < to->in_count; ++i) {
916 if (to->in_bb [i] != from)
917 to->in_bb [pos ++] = to->in_bb [i];
919 g_assert (pos == to->in_count - 1);
925 * mono_find_block_region:
927 * We mark each basic block with a region ID. We use that to avoid BB
928 * optimizations when blocks are in different regions.
931 * A region token that encodes where this region is, and information
932 * about the clause owner for this block.
934 * The region encodes the try/catch/filter clause that owns this block
935 * as well as the type. -1 is a special value that represents a block
936 * that is in none of try/catch/filter.
939 mono_find_block_region (MonoCompile *cfg, int offset)
941 MonoMethod *method = cfg->method;
942 MonoMethodHeader *header = mono_method_get_header (method);
943 MonoExceptionClause *clause;
946 /* first search for handlers and filters */
947 for (i = 0; i < header->num_clauses; ++i) {
948 clause = &header->clauses [i];
949 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
950 (offset < (clause->handler_offset)))
951 return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
953 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
954 if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
955 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
956 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
957 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
958 else if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
959 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
963 /* search the try blocks */
964 for (i = 0; i < header->num_clauses; ++i) {
965 clause = &header->clauses [i];
966 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
967 return ((i + 1) << 8) | clause->flags;
974 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
976 MonoMethod *method = cfg->method;
977 MonoMethodHeader *header = mono_method_get_header (method);
978 MonoExceptionClause *clause;
979 MonoBasicBlock *handler;
983 for (i = 0; i < header->num_clauses; ++i) {
984 clause = &header->clauses [i];
985 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) &&
986 (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
987 if (clause->flags == type) {
988 handler = cfg->cil_offset_to_bb [clause->handler_offset];
990 res = g_list_append (res, handler);
998 mono_find_spvar_for_region (MonoCompile *cfg, int region)
1000 return g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
1004 mono_create_spvar_for_region (MonoCompile *cfg, int region)
1008 var = g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
1012 var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1013 /* prevent it from being register allocated */
1014 var->flags |= MONO_INST_INDIRECT;
1016 g_hash_table_insert (cfg->spvars, GINT_TO_POINTER (region), var);
1020 mono_find_exvar_for_offset (MonoCompile *cfg, int offset)
1022 return g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
1026 mono_create_exvar_for_offset (MonoCompile *cfg, int offset)
1030 var = g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
1034 var = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
1035 /* prevent it from being register allocated */
1036 var->flags |= MONO_INST_INDIRECT;
1038 g_hash_table_insert (cfg->exvars, GINT_TO_POINTER (offset), var);
1044 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
1048 array [*dfn] = start;
1049 /*g_print ("visit %d at %p (BB%ld)\n", *dfn, start->cil_code, start->block_num);*/
1050 for (i = 0; i < start->out_count; ++i) {
1051 if (start->out_bb [i]->dfn)
1054 start->out_bb [i]->dfn = *dfn;
1055 start->out_bb [i]->df_parent = start;
1056 array [*dfn] = start->out_bb [i];
1057 df_visit (start->out_bb [i], dfn, array);
1061 static MonoBasicBlock*
1062 find_previous (MonoBasicBlock **bblocks, guint32 n_bblocks, MonoBasicBlock *start, const guchar *code)
1064 MonoBasicBlock *best = start;
1067 for (i = 0; i < n_bblocks; ++i) {
1069 MonoBasicBlock *bb = bblocks [i];
1071 if (bb->cil_code && bb->cil_code < code && bb->cil_code > best->cil_code)
1080 split_bblock (MonoCompile *cfg, MonoBasicBlock *first, MonoBasicBlock *second) {
1085 if (!MONO_INST_LIST_EMPTY (&second->ins_list))
1089 * FIXME: take into account all the details:
1090 * second may have been the target of more than one bblock
1092 second->out_count = first->out_count;
1093 second->out_bb = first->out_bb;
1095 for (i = 0; i < first->out_count; ++i) {
1096 bb = first->out_bb [i];
1097 for (j = 0; j < bb->in_count; ++j) {
1098 if (bb->in_bb [j] == first)
1099 bb->in_bb [j] = second;
1103 first->out_count = 0;
1104 first->out_bb = NULL;
1105 link_bblock (cfg, first, second);
1107 /*g_print ("start search at %p for %p\n", first->cil_code, second->cil_code);*/
1108 MONO_BB_FOR_EACH_INS (first, inst) {
1109 MonoInst *inst_next;
1111 /*char *code = mono_disasm_code_one (NULL, cfg->method, inst->next->cil_code, NULL);
1112 g_print ("found %p: %s", inst->next->cil_code, code);
1114 if (inst->cil_code >= second->cil_code)
1117 inst_next = mono_inst_list_next (&inst->node, &first->ins_list);
1121 if (inst_next->cil_code < second->cil_code)
1124 second->ins_list.next = inst->node.next;
1125 second->ins_list.prev = first->ins_list.prev;
1126 inst->node.next = &first->ins_list;
1127 first->ins_list.prev = &inst->node;
1129 second->next_bb = first->next_bb;
1130 first->next_bb = second;
1133 if (MONO_INST_LIST_EMPTY (&second->ins_list)) {
1134 g_warning ("bblock split failed in %s::%s\n", cfg->method->klass->name, cfg->method->name);
1140 reverse_branch_op (guint32 opcode)
1142 static const int reverse_map [] = {
1143 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
1144 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
1146 static const int reverse_fmap [] = {
1147 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
1148 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
1150 static const int reverse_lmap [] = {
1151 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
1152 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
1154 static const int reverse_imap [] = {
1155 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
1156 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
1159 if (opcode >= CEE_BEQ && opcode <= CEE_BLT_UN) {
1160 opcode = reverse_map [opcode - CEE_BEQ];
1161 } else if (opcode >= OP_FBEQ && opcode <= OP_FBLT_UN) {
1162 opcode = reverse_fmap [opcode - OP_FBEQ];
1163 } else if (opcode >= OP_LBEQ && opcode <= OP_LBLT_UN) {
1164 opcode = reverse_lmap [opcode - OP_LBEQ];
1165 } else if (opcode >= OP_IBEQ && opcode <= OP_IBLT_UN) {
1166 opcode = reverse_imap [opcode - OP_IBEQ];
1168 g_assert_not_reached ();
1173 #ifdef MONO_ARCH_SOFT_FLOAT
1175 condbr_to_fp_br (int opcode)
1178 case CEE_BEQ: return OP_FBEQ;
1179 case CEE_BGE: return OP_FBGE;
1180 case CEE_BGT: return OP_FBGT;
1181 case CEE_BLE: return OP_FBLE;
1182 case CEE_BLT: return OP_FBLT;
1183 case CEE_BNE_UN: return OP_FBNE_UN;
1184 case CEE_BGE_UN: return OP_FBGE_UN;
1185 case CEE_BGT_UN: return OP_FBGT_UN;
1186 case CEE_BLE_UN: return OP_FBLE_UN;
1187 case CEE_BLT_UN: return OP_FBLT_UN;
1189 g_assert_not_reached ();
1195 * Returns the type used in the eval stack when @type is loaded.
1196 * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
1199 type_to_eval_stack_type (MonoCompile *cfg, MonoType *type, MonoInst *inst)
1203 inst->klass = klass = mono_class_from_mono_type (type);
1205 inst->type = STACK_MP;
1210 switch (type->type) {
1211 case MONO_TYPE_VOID:
1212 inst->type = STACK_INV;
1216 case MONO_TYPE_BOOLEAN:
1219 case MONO_TYPE_CHAR:
1222 inst->type = STACK_I4;
1227 case MONO_TYPE_FNPTR:
1228 inst->type = STACK_PTR;
1230 case MONO_TYPE_CLASS:
1231 case MONO_TYPE_STRING:
1232 case MONO_TYPE_OBJECT:
1233 case MONO_TYPE_SZARRAY:
1234 case MONO_TYPE_ARRAY:
1235 inst->type = STACK_OBJ;
1239 inst->type = STACK_I8;
1243 inst->type = STACK_R8;
1245 case MONO_TYPE_VALUETYPE:
1246 if (type->data.klass->enumtype) {
1247 type = type->data.klass->enum_basetype;
1250 inst->klass = klass;
1251 inst->type = STACK_VTYPE;
1254 case MONO_TYPE_TYPEDBYREF:
1255 inst->klass = mono_defaults.typed_reference_class;
1256 inst->type = STACK_VTYPE;
1258 case MONO_TYPE_GENERICINST:
1259 type = &type->data.generic_class->container_class->byval_arg;
1261 case MONO_TYPE_VAR :
1262 case MONO_TYPE_MVAR :
1263 /* FIXME: all the arguments must be references for now,
1264 * later look inside cfg and see if the arg num is
1265 * really a reference
1267 g_assert (cfg->generic_sharing_context);
1268 inst->type = STACK_OBJ;
1271 g_error ("unknown type 0x%02x in eval stack type", type->type);
1276 * The following tables are used to quickly validate the IL code in type_from_op ().
1279 bin_num_table [STACK_MAX] [STACK_MAX] = {
1280 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1281 {STACK_INV, STACK_I4, STACK_INV, STACK_PTR, STACK_INV, STACK_MP, STACK_INV, STACK_INV},
1282 {STACK_INV, STACK_INV, STACK_I8, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1283 {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP, STACK_INV, STACK_INV},
1284 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8, STACK_INV, STACK_INV, STACK_INV},
1285 {STACK_INV, STACK_MP, STACK_INV, STACK_MP, STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
1286 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1287 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1292 STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV
1295 /* reduce the size of this table */
1297 bin_int_table [STACK_MAX] [STACK_MAX] = {
1298 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1299 {STACK_INV, STACK_I4, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1300 {STACK_INV, STACK_INV, STACK_I8, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1301 {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1302 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1303 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1304 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1305 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1309 bin_comp_table [STACK_MAX] [STACK_MAX] = {
1310 /* Inv i L p F & O vt */
1312 {0, 1, 0, 1, 0, 0, 0, 0}, /* i, int32 */
1313 {0, 0, 1, 0, 0, 0, 0, 0}, /* L, int64 */
1314 {0, 1, 0, 1, 0, 2, 4, 0}, /* p, ptr */
1315 {0, 0, 0, 0, 1, 0, 0, 0}, /* F, R8 */
1316 {0, 0, 0, 2, 0, 1, 0, 0}, /* &, managed pointer */
1317 {0, 0, 0, 4, 0, 0, 3, 0}, /* O, reference */
1318 {0, 0, 0, 0, 0, 0, 0, 0}, /* vt value type */
1321 /* reduce the size of this table */
1323 shift_table [STACK_MAX] [STACK_MAX] = {
1324 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1325 {STACK_INV, STACK_I4, STACK_INV, STACK_I4, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1326 {STACK_INV, STACK_I8, STACK_INV, STACK_I8, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1327 {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1328 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1329 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1330 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1331 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1335 * Tables to map from the non-specific opcode to the matching
1336 * type-specific opcode.
1338 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
1339 static const guint16
1340 binops_op_map [STACK_MAX] = {
1341 0, 0, OP_LADD-CEE_ADD, OP_PADD-CEE_ADD, OP_FADD-CEE_ADD, OP_PADD-CEE_ADD
1344 /* handles from CEE_NEG to CEE_CONV_U8 */
1345 static const guint16
1346 unops_op_map [STACK_MAX] = {
1347 0, 0, OP_LNEG-CEE_NEG, OP_PNEG-CEE_NEG, OP_FNEG-CEE_NEG, OP_PNEG-CEE_NEG
1350 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
1351 static const guint16
1352 ovfops_op_map [STACK_MAX] = {
1353 0, 0, OP_LCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, OP_FCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2, OP_PCONV_TO_U2-CEE_CONV_U2
1356 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
1357 static const guint16
1358 ovf2ops_op_map [STACK_MAX] = {
1359 0, 0, OP_LCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_PCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_FCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN, OP_PCONV_TO_OVF_I1_UN-CEE_CONV_OVF_I1_UN
1362 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
1363 static const guint16
1364 ovf3ops_op_map [STACK_MAX] = {
1365 0, 0, OP_LCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_PCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_FCONV_TO_OVF_I1-CEE_CONV_OVF_I1, OP_PCONV_TO_OVF_I1-CEE_CONV_OVF_I1
1368 /* handles from CEE_CEQ to CEE_CLT_UN */
1369 static const guint16
1370 ceqops_op_map [STACK_MAX] = {
1371 0, 0, OP_LCEQ-OP_CEQ, OP_PCEQ-OP_CEQ, OP_FCEQ-OP_CEQ, OP_LCEQ-OP_CEQ
1375 * Sets ins->type (the type on the eval stack) according to the
1376 * type of the opcode and the arguments to it.
1377 * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
1379 * FIXME: this function sets ins->type unconditionally in some cases, but
1380 * it should set it to invalid for some types (a conv.x on an object)
1383 type_from_op (MonoInst *ins) {
1384 switch (ins->opcode) {
1391 /* FIXME: check unverifiable args for STACK_MP */
1392 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1393 ins->opcode += binops_op_map [ins->type];
1400 ins->type = bin_int_table [ins->inst_i0->type] [ins->inst_i1->type];
1401 ins->opcode += binops_op_map [ins->type];
1406 ins->type = shift_table [ins->inst_i0->type] [ins->inst_i1->type];
1407 ins->opcode += binops_op_map [ins->type];
1411 /* FIXME: handle some specifics with ins->next->type */
1412 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1413 if ((ins->inst_i0->type == STACK_I8) || ((sizeof (gpointer) == 8) && ((ins->inst_i0->type == STACK_PTR) || (ins->inst_i0->type == STACK_OBJ) || (ins->inst_i0->type == STACK_MP))))
1414 ins->opcode = OP_LCOMPARE;
1417 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1418 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1425 ins->type = (bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] & 1) ? STACK_I4: STACK_INV;
1426 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1430 ins->type = neg_table [ins->inst_i0->type];
1431 ins->opcode += unops_op_map [ins->type];
1434 if (ins->inst_i0->type >= STACK_I4 && ins->inst_i0->type <= STACK_PTR)
1435 ins->type = ins->inst_i0->type;
1437 ins->type = STACK_INV;
1438 ins->opcode += unops_op_map [ins->type];
1444 ins->type = STACK_I4;
1445 ins->opcode += unops_op_map [ins->inst_i0->type];
1448 ins->type = STACK_R8;
1449 switch (ins->inst_i0->type) {
1454 ins->opcode = OP_LCONV_TO_R_UN;
1458 case CEE_CONV_OVF_I1:
1459 case CEE_CONV_OVF_U1:
1460 case CEE_CONV_OVF_I2:
1461 case CEE_CONV_OVF_U2:
1462 case CEE_CONV_OVF_I4:
1463 case CEE_CONV_OVF_U4:
1464 ins->type = STACK_I4;
1465 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1467 case CEE_CONV_OVF_I_UN:
1468 case CEE_CONV_OVF_U_UN:
1469 ins->type = STACK_PTR;
1470 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1472 case CEE_CONV_OVF_I1_UN:
1473 case CEE_CONV_OVF_I2_UN:
1474 case CEE_CONV_OVF_I4_UN:
1475 case CEE_CONV_OVF_U1_UN:
1476 case CEE_CONV_OVF_U2_UN:
1477 case CEE_CONV_OVF_U4_UN:
1478 ins->type = STACK_I4;
1479 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1482 ins->type = STACK_PTR;
1483 switch (ins->inst_i0->type) {
1488 #if SIZEOF_VOID_P == 8
1489 ins->opcode = OP_LCONV_TO_U;
1493 ins->opcode = OP_LCONV_TO_U;
1496 ins->opcode = OP_FCONV_TO_U;
1502 ins->type = STACK_I8;
1503 ins->opcode += unops_op_map [ins->inst_i0->type];
1505 case CEE_CONV_OVF_I8:
1506 case CEE_CONV_OVF_U8:
1507 ins->type = STACK_I8;
1508 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1510 case CEE_CONV_OVF_U8_UN:
1511 case CEE_CONV_OVF_I8_UN:
1512 ins->type = STACK_I8;
1513 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1517 ins->type = STACK_R8;
1518 ins->opcode += unops_op_map [ins->inst_i0->type];
1521 ins->type = STACK_R8;
1525 ins->type = STACK_I4;
1526 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1529 case CEE_CONV_OVF_I:
1530 case CEE_CONV_OVF_U:
1531 ins->type = STACK_PTR;
1532 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1535 case CEE_ADD_OVF_UN:
1537 case CEE_MUL_OVF_UN:
1539 case CEE_SUB_OVF_UN:
1540 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1541 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1542 if (ins->type == STACK_R8)
1543 ins->type = STACK_INV;
1546 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1553 STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_R8, STACK_OBJ
1556 /* map ldelem.x to the matching ldind.x opcode */
1558 ldelem_to_ldind [] = {
1572 /* map stelem.x to the matching stind.x opcode */
1574 stelem_to_stind [] = {
1588 param_table [STACK_MAX] [STACK_MAX] = {
1593 check_values_to_signature (MonoInst *args, MonoType *this, MonoMethodSignature *sig)
1598 switch (args->type) {
1608 for (i = 0; i < sig->param_count; ++i) {
1609 switch (args [i].type) {
1613 if (!sig->params [i]->byref)
1617 if (sig->params [i]->byref)
1619 switch (sig->params [i]->type) {
1620 case MONO_TYPE_CLASS:
1621 case MONO_TYPE_STRING:
1622 case MONO_TYPE_OBJECT:
1623 case MONO_TYPE_SZARRAY:
1624 case MONO_TYPE_ARRAY:
1631 if (sig->params [i]->byref)
1633 if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1642 /*if (!param_table [args [i].type] [sig->params [i]->type])
1650 mini_type_to_ldind (MonoCompile* cfg, MonoType *type)
1652 if (cfg->generic_sharing_context && !type->byref) {
1653 /* FIXME: all the arguments must be references for now,
1654 * later look inside cfg and see if the arg num is
1655 * really a reference
1657 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
1658 return CEE_LDIND_REF;
1660 return mono_type_to_ldind (type);
1664 mini_type_to_stind (MonoCompile* cfg, MonoType *type)
1666 if (cfg->generic_sharing_context && !type->byref) {
1667 /* FIXME: all the arguments must be references for now,
1668 * later look inside cfg and see if the arg num is
1669 * really a reference
1671 if (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)
1672 return CEE_STIND_REF;
1674 return mono_type_to_stind (type);
1678 mono_op_imm_to_op (int opcode)
1692 #if SIZEOF_VOID_P == 4
1717 case OP_ISHR_UN_IMM:
1719 case OP_LSHR_UN_IMM:
1723 case OP_IDIV_UN_IMM:
1725 case OP_IREM_UN_IMM:
1730 #if SIZEOF_VOID_P == 4
1736 #if SIZEOF_VOID_P == 4
1753 case OP_COMPARE_IMM:
1755 case OP_ICOMPARE_IMM:
1758 printf ("%s\n", mono_inst_name (opcode));
1759 g_assert_not_reached ();
1764 * mono_decompose_op_imm:
1766 * Replace the OP_.._IMM INS with its non IMM variant.
1769 mono_decompose_op_imm (MonoCompile *cfg, MonoInst *ins)
1773 MONO_INST_NEW (cfg, temp, OP_ICONST);
1774 temp->inst_c0 = ins->inst_imm;
1775 temp->dreg = mono_regstate_next_int (cfg->rs);
1776 MONO_INST_LIST_ADD_TAIL (&(temp)->node, &(ins)->node);
1777 ins->opcode = mono_op_imm_to_op (ins->opcode);
1778 ins->sreg2 = temp->dreg;
1782 * When we need a pointer to the current domain many times in a method, we
1783 * call mono_domain_get() once and we store the result in a local variable.
1784 * This function returns the variable that represents the MonoDomain*.
1786 inline static MonoInst *
1787 mono_get_domainvar (MonoCompile *cfg)
1789 if (!cfg->domainvar)
1790 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1791 return cfg->domainvar;
1795 * The got_var contains the address of the Global Offset Table when AOT
1798 inline static MonoInst *
1799 mono_get_got_var (MonoCompile *cfg)
1801 #ifdef MONO_ARCH_NEED_GOT_VAR
1802 if (!cfg->compile_aot)
1804 if (!cfg->got_var) {
1805 cfg->got_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1807 return cfg->got_var;
1814 mono_get_vtable_var (MonoCompile *cfg)
1816 g_assert (cfg->generic_sharing_context);
1818 if (!cfg->rgctx_var) {
1819 cfg->rgctx_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1820 /* force the var to be stack allocated */
1821 cfg->rgctx_var->flags |= MONO_INST_INDIRECT;
1824 return cfg->rgctx_var;
1828 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1831 int num = cfg->num_varinfo;
1833 if ((num + 1) >= cfg->varinfo_count) {
1834 int orig_count = cfg->varinfo_count;
1835 cfg->varinfo_count = (cfg->varinfo_count + 2) * 2;
1836 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
1837 cfg->vars = (MonoMethodVar *)g_realloc (cfg->vars, sizeof (MonoMethodVar) * cfg->varinfo_count);
1838 memset (&cfg->vars [orig_count], 0, (cfg->varinfo_count - orig_count) * sizeof (MonoMethodVar));
1841 /*g_print ("created temp %d of type 0x%x\n", num, type->type);*/
1842 mono_jit_stats.allocate_var++;
1844 MONO_INST_NEW (cfg, inst, opcode);
1845 inst->inst_c0 = num;
1846 inst->inst_vtype = type;
1847 inst->klass = mono_class_from_mono_type (type);
1848 /* if set to 1 the variable is native */
1849 inst->backend.is_pinvoke = 0;
1851 cfg->varinfo [num] = inst;
1853 MONO_INIT_VARINFO (&cfg->vars [num], num);
1856 if (cfg->verbose_level > 2)
1857 g_print ("created temp %d of type %s\n", num, mono_type_get_name (type));
1862 * Transform a MonoInst into a load from the variable of index var_index.
1865 mono_compile_make_var_load (MonoCompile *cfg, MonoInst *dest, gssize var_index) {
1866 memset (dest, 0, sizeof (MonoInst));
1867 dest->ssa_op = MONO_SSA_LOAD;
1868 dest->inst_i0 = cfg->varinfo [var_index];
1869 dest->opcode = mini_type_to_ldind (cfg, dest->inst_i0->inst_vtype);
1870 type_to_eval_stack_type (cfg, dest->inst_i0->inst_vtype, dest);
1871 dest->klass = dest->inst_i0->klass;
1875 * Create a MonoInst that is a load from the variable of index var_index.
1878 mono_compile_create_var_load (MonoCompile *cfg, gssize var_index) {
1880 NEW_TEMPLOAD (cfg,dest,var_index);
1885 * Create a MonoInst that is a store of the given value into the variable of index var_index.
1888 mono_compile_create_var_store (MonoCompile *cfg, gssize var_index, MonoInst *value) {
1890 NEW_TEMPSTORE (cfg, dest, var_index, value);
1895 type_from_stack_type (MonoInst *ins) {
1896 switch (ins->type) {
1897 case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1898 case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1899 case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1900 case STACK_R8: return &mono_defaults.double_class->byval_arg;
1903 * this if used to be commented without any specific reason, but
1904 * it breaks #80235 when commented
1907 return &ins->klass->this_arg;
1909 return &mono_defaults.object_class->this_arg;
1911 /* ins->klass may not be set for ldnull.
1912 * Also, if we have a boxed valuetype, we want an object lass,
1913 * not the valuetype class
1915 if (ins->klass && !ins->klass->valuetype)
1916 return &ins->klass->byval_arg;
1917 return &mono_defaults.object_class->byval_arg;
1918 case STACK_VTYPE: return &ins->klass->byval_arg;
1920 g_error ("stack type %d to montype not handled\n", ins->type);
1926 mono_type_from_stack_type (MonoInst *ins) {
1927 return type_from_stack_type (ins);
1931 array_access_to_klass (int opcode, MonoInst *array_obj)
1935 return mono_defaults.byte_class;
1937 return mono_defaults.uint16_class;
1940 return mono_defaults.int_class;
1943 return mono_defaults.sbyte_class;
1946 return mono_defaults.int16_class;
1949 return mono_defaults.int32_class;
1951 return mono_defaults.uint32_class;
1954 return mono_defaults.int64_class;
1957 return mono_defaults.single_class;
1960 return mono_defaults.double_class;
1961 case CEE_LDELEM_REF:
1962 case CEE_STELEM_REF: {
1963 MonoClass *klass = array_obj->klass;
1964 /* FIXME: add assert */
1965 if (klass && klass->rank)
1966 return klass->element_class;
1967 return mono_defaults.object_class;
1970 g_assert_not_reached ();
1976 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
1978 MonoInst *last = mono_inst_list_last (&bb->ins_list);
1980 if (last && ((last->opcode >= CEE_BEQ &&
1981 last->opcode <= CEE_BLT_UN) ||
1982 last->opcode == OP_BR ||
1983 last->opcode == OP_SWITCH)) {
1984 MONO_INST_LIST_ADD_TAIL (&inst->node, &last->node);
1986 MONO_ADD_INS (bb, inst);
1991 mono_add_varcopy_to_end (MonoCompile *cfg, MonoBasicBlock *bb, int src, int dest)
1993 MonoInst *inst, *load;
1995 NEW_TEMPLOAD (cfg, load, src);
1997 NEW_TEMPSTORE (cfg, inst, dest, load);
1998 /* FIXME: handle CEE_STIND_R4 */
1999 if (inst->opcode == CEE_STOBJ) {
2000 NEW_TEMPLOADA (cfg, inst, dest);
2001 handle_stobj (cfg, bb, inst, load, NULL, inst->klass, TRUE, FALSE, FALSE);
2003 inst->cil_code = NULL;
2004 mono_add_ins_to_end (bb, inst);
2009 * This function is called to handle items that are left on the evaluation stack
2010 * at basic block boundaries. What happens is that we save the values to local variables
2011 * and we reload them later when first entering the target basic block (with the
2012 * handle_loaded_temps () function).
2013 * It is also used to handle items on the stack in store opcodes, since it is
2014 * possible that the variable to be stored into is already on the stack, in
2015 * which case its old value should be used.
2016 * A single joint point will use the same variables (stored in the array bb->out_stack or
2017 * bb->in_stack, if the basic block is before or after the joint point).
2018 * If the stack merge fails at a join point, cfg->unverifiable is set.
2021 handle_stack_args (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **sp, int count)
2024 MonoBasicBlock *outb;
2025 MonoInst *inst, **locals;
2030 if (cfg->verbose_level > 3)
2031 g_print ("%d item(s) on exit from B%d\n", count, bb->block_num);
2033 if (!bb->out_scount) {
2034 bb->out_scount = count;
2035 //g_print ("bblock %d has out:", bb->block_num);
2037 for (i = 0; i < bb->out_count; ++i) {
2038 outb = bb->out_bb [i];
2039 /* exception handlers are linked, but they should not be considered for stack args */
2040 if (outb->flags & BB_EXCEPTION_HANDLER)
2042 //g_print (" %d", outb->block_num);
2043 if (outb->in_stack) {
2045 bb->out_stack = outb->in_stack;
2051 bb->out_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
2052 for (i = 0; i < count; ++i) {
2054 * try to reuse temps already allocated for this purpouse, if they occupy the same
2055 * stack slot and if they are of the same type.
2056 * This won't cause conflicts since if 'local' is used to
2057 * store one of the values in the in_stack of a bblock, then
2058 * the same variable will be used for the same outgoing stack
2060 * This doesn't work when inlining methods, since the bblocks
2061 * in the inlined methods do not inherit their in_stack from
2062 * the bblock they are inlined to. See bug #58863 for an
2064 * This hack is disabled since it also prevents proper tracking of types.
2067 bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
2069 if (cfg->inlined_method)
2070 bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
2072 bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
2078 for (i = 0; i < bb->out_count; ++i) {
2079 outb = bb->out_bb [i];
2080 /* exception handlers are linked, but they should not be considered for stack args */
2081 if (outb->flags & BB_EXCEPTION_HANDLER)
2083 if (outb->in_scount) {
2084 if (outb->in_scount != bb->out_scount) {
2085 cfg->unverifiable = TRUE;
2088 continue; /* check they are the same locals */
2090 outb->in_scount = count;
2091 outb->in_stack = bb->out_stack;
2094 locals = bb->out_stack;
2095 for (i = 0; i < count; ++i) {
2096 /* add store ops at the end of the bb, before the branch */
2097 NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
2098 if (inst->opcode == CEE_STOBJ) {
2099 NEW_TEMPLOADA (cfg, inst, locals [i]->inst_c0);
2100 handle_stobj (cfg, bb, inst, sp [i], sp [i]->cil_code, inst->klass, TRUE, FALSE, FALSE);
2102 inst->cil_code = sp [i]->cil_code;
2103 mono_add_ins_to_end (bb, inst);
2105 if (cfg->verbose_level > 3)
2106 g_print ("storing %d to temp %d\n", i, (int)locals [i]->inst_c0);
2110 * It is possible that the out bblocks already have in_stack assigned, and
2111 * the in_stacks differ. In this case, we will store to all the different
2118 /* Find a bblock which has a different in_stack */
2120 while (bindex < bb->out_count) {
2121 outb = bb->out_bb [bindex];
2122 /* exception handlers are linked, but they should not be considered for stack args */
2123 if (outb->flags & BB_EXCEPTION_HANDLER) {
2127 if (outb->in_stack != locals) {
2129 * Instead of storing sp [i] to locals [i], we need to store
2130 * locals [i] to <new locals>[i], since the sp [i] tree can't
2131 * be shared between trees.
2133 for (i = 0; i < count; ++i)
2134 mono_add_varcopy_to_end (cfg, bb, locals [i]->inst_c0, outb->in_stack [i]->inst_c0);
2135 locals = outb->in_stack;
2145 ret_type_to_call_opcode (MonoType *type, int calli, int virt, MonoGenericSharingContext *gsctx)
2148 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2151 type = mini_get_basic_type_from_generic (gsctx, type);
2152 switch (type->type) {
2153 case MONO_TYPE_VOID:
2154 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALLVIRT: OP_VOIDCALL;
2157 case MONO_TYPE_BOOLEAN:
2160 case MONO_TYPE_CHAR:
2163 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2167 case MONO_TYPE_FNPTR:
2168 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2169 case MONO_TYPE_CLASS:
2170 case MONO_TYPE_STRING:
2171 case MONO_TYPE_OBJECT:
2172 case MONO_TYPE_SZARRAY:
2173 case MONO_TYPE_ARRAY:
2174 return calli? OP_CALL_REG: virt? OP_CALLVIRT: OP_CALL;
2177 return calli? OP_LCALL_REG: virt? OP_LCALLVIRT: OP_LCALL;
2180 return calli? OP_FCALL_REG: virt? OP_FCALLVIRT: OP_FCALL;
2181 case MONO_TYPE_VALUETYPE:
2182 if (type->data.klass->enumtype) {
2183 type = type->data.klass->enum_basetype;
2186 return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
2187 case MONO_TYPE_TYPEDBYREF:
2188 return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
2189 case MONO_TYPE_GENERICINST:
2190 type = &type->data.generic_class->container_class->byval_arg;
2193 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
2199 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
2201 MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
2202 MonoJumpInfoBBTable *table;
2204 table = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
2206 table->table_size = num_blocks;
2208 ji->ip.label = label;
2209 ji->type = MONO_PATCH_INFO_SWITCH;
2210 ji->data.table = table;
2211 ji->next = cfg->patch_info;
2212 cfg->patch_info = ji;
2216 mono_save_token_info (MonoCompile *cfg, MonoImage *image, guint32 token, gpointer key)
2218 if (cfg->compile_aot) {
2219 MonoJumpInfoToken *jump_info_token = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfoToken));
2220 jump_info_token->image = image;
2221 jump_info_token->token = token;
2222 g_hash_table_insert (cfg->token_info_hash, key, jump_info_token);
2227 * When we add a tree of instructions, we need to ensure the instructions currently
2228 * on the stack are executed before (like, if we load a value from a local).
2229 * We ensure this by saving the currently loaded values to temps and rewriting the
2230 * instructions to load the values.
2231 * This is not done for opcodes that terminate a basic block (because it's handled already
2232 * by handle_stack_args ()) and for opcodes that can't change values, like POP.
2235 handle_loaded_temps (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst **stack, MonoInst **sp)
2237 MonoInst *load, *store, *temp, *ins;
2239 while (stack < sp) {
2241 /* handle also other constants */
2242 if ((ins->opcode != OP_ICONST) &&
2243 /* temps never get written to again, so we can safely avoid duplicating them */
2244 !(ins->ssa_op == MONO_SSA_LOAD && ins->inst_i0->opcode == OP_LOCAL && ins->inst_i0->flags & MONO_INST_IS_TEMP)) {
2245 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
2246 temp->flags |= MONO_INST_IS_TEMP;
2247 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2248 store->cil_code = ins->cil_code;
2249 if (store->opcode == CEE_STOBJ) {
2250 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2251 handle_stobj (cfg, bblock, store, ins, ins->cil_code, temp->klass, FALSE, FALSE, FALSE);
2253 MONO_ADD_INS (bblock, store);
2254 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2255 load->cil_code = ins->cil_code;
2263 * target_type_is_incompatible:
2264 * @cfg: MonoCompile context
2266 * Check that the item @arg on the evaluation stack can be stored
2267 * in the target type (can be a local, or field, etc).
2268 * The cfg arg can be used to check if we need verification or just
2271 * Returns: non-0 value if arg can't be stored on a target.
2274 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
2276 MonoType *simple_type;
2279 if (target->byref) {
2280 /* FIXME: check that the pointed to types match */
2281 if (arg->type == STACK_MP)
2282 return arg->klass != mono_class_from_mono_type (target);
2283 if (arg->type == STACK_PTR)
2287 simple_type = mono_type_get_underlying_type (target);
2288 switch (simple_type->type) {
2289 case MONO_TYPE_VOID:
2293 case MONO_TYPE_BOOLEAN:
2296 case MONO_TYPE_CHAR:
2299 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2303 /* STACK_MP is needed when setting pinned locals */
2304 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
2309 case MONO_TYPE_FNPTR:
2310 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2313 case MONO_TYPE_OBJECT:
2314 if (arg->type != STACK_OBJ)
2317 case MONO_TYPE_STRING:
2318 if (arg->type != STACK_OBJ)
2320 /* ldnull has arg->klass unset */
2321 /*if (arg->klass && arg->klass != mono_defaults.string_class) {
2326 case MONO_TYPE_CLASS:
2327 case MONO_TYPE_SZARRAY:
2328 case MONO_TYPE_ARRAY:
2329 if (arg->type != STACK_OBJ)
2331 /* FIXME: check type compatibility */
2335 if (arg->type != STACK_I8)
2340 if (arg->type != STACK_R8)
2343 case MONO_TYPE_VALUETYPE:
2344 if (arg->type != STACK_VTYPE)
2346 klass = mono_class_from_mono_type (simple_type);
2347 if (klass != arg->klass)
2350 case MONO_TYPE_TYPEDBYREF:
2351 if (arg->type != STACK_VTYPE)
2353 klass = mono_class_from_mono_type (simple_type);
2354 if (klass != arg->klass)
2357 case MONO_TYPE_GENERICINST:
2358 if (mono_type_generic_inst_is_valuetype (simple_type)) {
2359 klass = mono_class_from_mono_type (simple_type);
2360 if (klass->enumtype)
2361 return target_type_is_incompatible (cfg, klass->enum_basetype, arg);
2362 if (arg->type != STACK_VTYPE)
2364 if (klass != arg->klass)
2368 if (arg->type != STACK_OBJ)
2370 /* FIXME: check type compatibility */
2374 case MONO_TYPE_MVAR:
2375 /* FIXME: all the arguments must be references for now,
2376 * later look inside cfg and see if the arg num is
2377 * really a reference
2379 g_assert (cfg->generic_sharing_context);
2380 if (arg->type != STACK_OBJ)
2384 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
2390 * Prepare arguments for passing to a function call.
2391 * Return a non-zero value if the arguments can't be passed to the given
2393 * The type checks are not yet complete and some conversions may need
2394 * casts on 32 or 64 bit architectures.
2396 * FIXME: implement this using target_type_is_incompatible ()
2399 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
2401 MonoType *simple_type;
2405 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
2409 for (i = 0; i < sig->param_count; ++i) {
2410 if (sig->params [i]->byref) {
2411 if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
2415 simple_type = sig->params [i];
2416 simple_type = mini_get_basic_type_from_generic (cfg->generic_sharing_context, simple_type);
2418 switch (simple_type->type) {
2419 case MONO_TYPE_VOID:
2424 case MONO_TYPE_BOOLEAN:
2427 case MONO_TYPE_CHAR:
2430 if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2436 case MONO_TYPE_FNPTR:
2437 if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2440 case MONO_TYPE_CLASS:
2441 case MONO_TYPE_STRING:
2442 case MONO_TYPE_OBJECT:
2443 case MONO_TYPE_SZARRAY:
2444 case MONO_TYPE_ARRAY:
2445 if (args [i]->type != STACK_OBJ)
2450 if (args [i]->type != STACK_I8)
2455 if (args [i]->type != STACK_R8)
2458 case MONO_TYPE_VALUETYPE:
2459 if (simple_type->data.klass->enumtype) {
2460 simple_type = simple_type->data.klass->enum_basetype;
2463 if (args [i]->type != STACK_VTYPE)
2466 case MONO_TYPE_TYPEDBYREF:
2467 if (args [i]->type != STACK_VTYPE)
2470 case MONO_TYPE_GENERICINST:
2471 simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2475 g_error ("unknown type 0x%02x in check_call_signature",
2483 mono_spill_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoCallInst *call, MonoMethodSignature *sig, gboolean ret_object,
2484 const guint8 *ip, gboolean to_end)
2486 MonoInst *temp, *store, *ins = (MonoInst*)call;
2487 MonoType *ret = sig->ret;
2489 if (!MONO_TYPE_IS_VOID (ret) || ret_object) {
2491 call->inst.type = STACK_OBJ;
2492 call->inst.opcode = OP_CALL;
2493 temp = mono_compile_create_var (cfg, &mono_defaults.string_class->byval_arg, OP_LOCAL);
2495 type_to_eval_stack_type (cfg, ret, ins);
2496 temp = mono_compile_create_var (cfg, ret, OP_LOCAL);
2499 temp->flags |= MONO_INST_IS_TEMP;
2501 if (MONO_TYPE_ISSTRUCT (ret)) {
2502 MonoInst *loada, *dummy_store;
2505 * Emit a dummy store to the local holding the result so the
2506 * liveness info remains correct.
2508 NEW_DUMMY_STORE (cfg, dummy_store, temp->inst_c0);
2510 mono_add_ins_to_end (bblock, dummy_store);
2512 MONO_ADD_INS (bblock, dummy_store);
2514 /* we use this to allocate native sized structs */
2515 temp->backend.is_pinvoke = sig->pinvoke;
2517 NEW_TEMPLOADA (cfg, loada, temp->inst_c0);
2518 if (call->inst.opcode == OP_VCALL || call->inst.opcode == OP_VCALL_RGCTX)
2519 ins->inst_left = loada;
2521 ins->inst_right = loada; /* a virtual or indirect call */
2524 mono_add_ins_to_end (bblock, ins);
2526 MONO_ADD_INS (bblock, ins);
2528 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2529 store->cil_code = ip;
2531 #ifdef MONO_ARCH_SOFT_FLOAT
2532 if (store->opcode == CEE_STIND_R4) {
2533 /*FIXME implement proper support for to_end*/
2535 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2536 handle_store_float (cfg, bblock, store, ins, ip);
2540 mono_add_ins_to_end (bblock, store);
2542 MONO_ADD_INS (bblock, store);
2544 return temp->inst_c0;
2547 mono_add_ins_to_end (bblock, ins);
2549 MONO_ADD_INS (bblock, ins);
2554 inline static MonoCallInst *
2555 mono_emit_call_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2556 MonoInst **args, int calli, int virtual, const guint8 *ip, gboolean to_end)
2561 MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (sig->ret, calli, virtual, cfg->generic_sharing_context));
2563 #ifdef MONO_ARCH_SOFT_FLOAT
2564 /* we need to convert the r4 value to an int value */
2567 for (i = 0; i < sig->param_count; ++i) {
2568 if (!sig->params [i]->byref && sig->params [i]->type == MONO_TYPE_R4) {
2569 MonoInst *iargs [1];
2571 iargs [0] = args [i + sig->hasthis];
2573 temp = mono_emit_jit_icall (cfg, bblock, mono_fload_r4_arg, iargs, ip);
2574 NEW_TEMPLOAD (cfg, arg, temp);
2575 args [i + sig->hasthis] = arg;
2581 call->inst.cil_code = ip;
2583 call->signature = sig;
2584 call = mono_arch_call_opcode (cfg, bblock, call, virtual);
2585 type_to_eval_stack_type (cfg, sig->ret, &call->inst);
2587 MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (arg, n, &call->out_args, node) {
2591 mono_add_ins_to_end (bblock, arg);
2593 MONO_ADD_INS (bblock, arg);
2598 inline static MonoCallInst*
2599 mono_emit_calli (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2600 MonoInst **args, MonoInst *addr, const guint8 *ip)
2602 MonoCallInst *call = mono_emit_call_args (cfg, bblock, sig, args, TRUE, FALSE, ip, FALSE);
2604 call->inst.inst_i0 = addr;
2609 inline static MonoCallInst*
2610 mono_emit_rgctx_calli (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2611 MonoInst **args, MonoInst *addr, MonoInst *rgctx_arg, const guint8 *ip)
2613 MonoCallInst *call = mono_emit_calli (cfg, bblock, sig, args, addr, ip);
2616 switch (call->inst.opcode) {
2617 case OP_CALL_REG: call->inst.opcode = OP_CALL_REG_RGCTX; break;
2618 case OP_VOIDCALL_REG: call->inst.opcode = OP_VOIDCALL_REG_RGCTX; break;
2619 case OP_FCALL_REG: call->inst.opcode = OP_FCALL_REG_RGCTX; break;
2620 case OP_LCALL_REG: call->inst.opcode = OP_LCALL_REG_RGCTX; break;
2621 case OP_VCALL_REG: {
2624 NEW_GROUP (cfg, group, call->inst.inst_left, NULL);
2625 call->inst.inst_left = group;
2626 call->inst.opcode = OP_VCALL_REG_RGCTX;
2629 default: g_assert_not_reached ();
2632 if (call->inst.opcode != OP_VCALL_REG_RGCTX) {
2633 g_assert (!call->inst.inst_right);
2634 call->inst.inst_right = rgctx_arg;
2636 g_assert (!call->inst.inst_left->inst_right);
2637 call->inst.inst_left->inst_right = rgctx_arg;
2645 mono_emit_calli_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2646 MonoInst **args, MonoInst *addr, const guint8 *ip)
2648 MonoCallInst *call = mono_emit_calli (cfg, bblock, sig, args, addr, ip);
2650 return mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
2654 mono_emit_rgctx_calli_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2655 MonoInst **args, MonoInst *addr, MonoInst *rgctx_arg, const guint8 *ip)
2657 MonoCallInst *call = mono_emit_rgctx_calli (cfg, bblock, sig, args, addr, rgctx_arg, ip);
2659 return mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
2662 static MonoCallInst*
2663 mono_emit_method_call_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2664 MonoInst **args, const guint8 *ip, MonoInst *this, gboolean to_end)
2666 gboolean virtual = this != NULL;
2669 call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, virtual, ip, to_end);
2671 if (this && sig->hasthis &&
2672 (method->klass->marshalbyref || method->klass == mono_defaults.object_class) &&
2673 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !MONO_CHECK_THIS (this)) {
2674 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2676 call->method = method;
2678 call->inst.flags |= MONO_INST_HAS_METHOD;
2679 call->inst.inst_left = this;
2681 if (call->method->klass->flags & TYPE_ATTRIBUTE_INTERFACE)
2682 /* Needed by the code generated in inssel.brg */
2683 mono_get_got_var (cfg);
2688 static MonoCallInst*
2689 mono_emit_method_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2690 MonoInst **args, const guint8 *ip, MonoInst *this)
2692 return mono_emit_method_call_full (cfg, bblock, method, sig, args, ip, this, FALSE);
2696 mono_emit_method_call_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,
2697 MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this)
2699 MonoCallInst *call = mono_emit_method_call (cfg, bblock, method, signature, args, ip, this);
2701 return mono_spill_call (cfg, bblock, call, signature, method->string_ctor, ip, FALSE);
2705 mono_emit_method_call_spilled_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,
2706 MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this,
2707 gboolean ret_object, gboolean to_end)
2709 MonoCallInst *call = mono_emit_method_call_full (cfg, bblock, method, signature, args, ip, this, to_end);
2711 return mono_spill_call (cfg, bblock, call, signature, ret_object, ip, to_end);
2715 mono_emit_native_call (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoMethodSignature *sig,
2716 MonoInst **args, const guint8 *ip, gboolean ret_object, gboolean to_end)
2722 call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, FALSE, ip, to_end);
2725 return mono_spill_call (cfg, bblock, call, sig, ret_object, ip, to_end);
2729 mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip)
2731 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2734 g_warning ("unregistered JIT ICall");
2735 g_assert_not_reached ();
2738 return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, args, ip, FALSE, FALSE);
2741 static MonoCallInst*
2742 mono_emit_rgctx_method_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2743 MonoInst **args, MonoInst *rgctx_arg, const guint8 *ip, MonoInst *this)
2745 MonoCallInst *call = mono_emit_method_call_full (cfg, bblock, method, sig, args, ip, this, FALSE);
2748 switch (call->inst.opcode) {
2749 case OP_CALL: call->inst.opcode = OP_CALL_RGCTX; break;
2750 case OP_VOIDCALL: call->inst.opcode = OP_VOIDCALL_RGCTX; break;
2751 case OP_FCALL: call->inst.opcode = OP_FCALL_RGCTX; break;
2752 case OP_LCALL: call->inst.opcode = OP_LCALL_RGCTX; break;
2753 case OP_VCALL: call->inst.opcode = OP_VCALL_RGCTX; break;
2754 default: g_assert_not_reached ();
2757 if (call->inst.opcode != OP_VCALL_RGCTX) {
2758 g_assert (!call->inst.inst_left);
2759 call->inst.inst_left = rgctx_arg;
2761 g_assert (!call->inst.inst_right);
2762 call->inst.inst_right = rgctx_arg;
2770 mono_emit_rgctx_method_call_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,
2771 MonoMethodSignature *signature, MonoInst **args, MonoInst *rgctx_arg, const guint8 *ip,
2774 MonoCallInst *call = mono_emit_rgctx_method_call (cfg, bblock, method, signature, args, rgctx_arg, ip, this);
2776 return mono_spill_call (cfg, bblock, call, signature, method->string_ctor, ip, FALSE);
2780 mono_emulate_opcode (MonoCompile *cfg, MonoInst *tree, MonoInst **iargs, MonoJitICallInfo *info)
2782 MonoInst *ins, *temp = NULL, *store, *load;
2783 MonoInstList *head, *list;
2787 //g_print ("emulating: ");
2788 //mono_print_tree_nl (tree);
2789 MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (info->sig->ret, FALSE, FALSE, cfg->generic_sharing_context));
2790 ins = (MonoInst*)call;
2791 MONO_INST_LIST_INIT (&ins->node);
2793 call->inst.cil_code = tree->cil_code;
2795 call->signature = info->sig;
2797 call = mono_arch_call_opcode (cfg, cfg->cbb, call, FALSE);
2799 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2800 temp = mono_compile_create_var (cfg, info->sig->ret, OP_LOCAL);
2801 temp->flags |= MONO_INST_IS_TEMP;
2802 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2803 MONO_INST_LIST_INIT (&store->node);
2804 /* FIXME: handle CEE_STIND_R4 */
2805 store->cil_code = tree->cil_code;
2810 nargs = info->sig->param_count + info->sig->hasthis;
2813 MONO_INST_LIST_ADD_TAIL (&store->node,
2815 list = &call->out_args;
2817 list = &store->node;
2820 if (cfg->prev_ins) {
2822 * This assumes that that in a tree, emulate_opcode is called for a
2823 * node before it is called for its children. dec_foreach needs to
2824 * take this into account.
2826 head = &cfg->prev_ins->node;
2828 head = &cfg->cbb->ins_list;
2831 MONO_INST_LIST_SPLICE_INIT (list, head);
2833 call->fptr = mono_icall_get_wrapper (info);
2835 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2836 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2842 * This entry point could be used later for arbitrary method
2846 mini_redirect_call (int *temp, MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,
2847 MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this)
2850 if (method->klass == mono_defaults.string_class) {
2851 /* managed string allocation support */
2852 if (strcmp (method->name, "InternalAllocateStr") == 0) {
2853 MonoInst *iargs [2];
2854 MonoVTable *vtable = mono_class_vtable (cfg->domain, method->klass);
2855 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, FALSE);
2858 NEW_VTABLECONST (cfg, iargs [0], vtable);
2859 iargs [1] = args [0];
2860 *temp = mono_emit_method_call_spilled (cfg, bblock, managed_alloc, mono_method_signature (managed_alloc), iargs, ip, this);
2867 static MonoMethodSignature *
2868 mono_get_array_new_va_signature (int arity)
2870 static GHashTable *sighash = NULL;
2871 MonoMethodSignature *res;
2876 sighash = g_hash_table_new (NULL, NULL);
2878 else if ((res = g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
2883 res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
2886 #ifdef MONO_ARCH_VARARG_ICALLS
2887 /* Only set this only some archs since not all backends can handle varargs+pinvoke */
2888 res->call_convention = MONO_CALL_VARARG;
2891 #ifdef PLATFORM_WIN32
2892 res->call_convention = MONO_CALL_C;
2895 res->params [0] = &mono_defaults.int_class->byval_arg;
2896 for (i = 0; i < arity; i++)
2897 res->params [i + 1] = &mono_defaults.int_class->byval_arg;
2899 res->ret = &mono_defaults.int_class->byval_arg;
2901 g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
2907 #ifdef MONO_ARCH_SOFT_FLOAT
2909 handle_store_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, MonoInst *val, const unsigned char *ip)
2911 MonoInst *iargs [2];
2915 mono_emit_jit_icall (cfg, bblock, mono_fstore_r4, iargs, ip);
2919 handle_load_float (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ptr, const unsigned char *ip)
2921 MonoInst *iargs [1];
2924 return mono_emit_jit_icall (cfg, bblock, mono_fload_r4, iargs, ip);
2927 #define LDLOC_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2928 if (header->locals [(idx)]->type == MONO_TYPE_R4 && !header->locals [(idx)]->byref) { \
2930 NEW_LOCLOADA (cfg, (ins), (idx)); \
2931 temp = handle_load_float (cfg, bblock, (ins), (ip)); \
2932 NEW_TEMPLOAD (cfg, (ins), temp); \
2935 #define STLOC_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2936 if (header->locals [(idx)]->type == MONO_TYPE_R4 && !header->locals [(idx)]->byref) { \
2938 NEW_LOCLOADA (cfg, (ins), (idx)); \
2939 handle_store_float (cfg, bblock, (ins), *sp, (ip)); \
2940 MONO_INST_NEW (cfg, (ins), OP_NOP); \
2943 #define LDARG_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2944 if (param_types [(idx)]->type == MONO_TYPE_R4 && !param_types [(idx)]->byref) { \
2946 NEW_ARGLOADA (cfg, (ins), (idx)); \
2947 temp = handle_load_float (cfg, bblock, (ins), (ip)); \
2948 NEW_TEMPLOAD (cfg, (ins), temp); \
2951 #define STARG_SOFT_FLOAT(cfg,ins,idx,ip) do {\
2952 if (param_types [(idx)]->type == MONO_TYPE_R4 && !param_types [(idx)]->byref) { \
2954 NEW_ARGLOADA (cfg, (ins), (idx)); \
2955 handle_store_float (cfg, bblock, (ins), *sp, (ip)); \
2956 MONO_INST_NEW (cfg, (ins), OP_NOP); \
2960 #define LDLOC_SOFT_FLOAT(cfg,ins,idx,ip)
2961 #define STLOC_SOFT_FLOAT(cfg,ins,idx,ip)
2962 #define LDARG_SOFT_FLOAT(cfg,ins,idx,ip)
2963 #define STARG_SOFT_FLOAT(cfg,ins,idx,ip)
2967 get_memcpy_method (void)
2969 static MonoMethod *memcpy_method = NULL;
2970 if (!memcpy_method) {
2971 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
2973 g_error ("Old corlib found. Install a new one");
2975 return memcpy_method;
2979 handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native, gboolean write_barrier) {
2980 MonoInst *iargs [3];
2983 MonoMethod *memcpy_method;
2987 * This check breaks with spilled vars... need to handle it during verification anyway.
2988 * g_assert (klass && klass == src->klass && klass == dest->klass);
2992 n = mono_class_native_size (klass, &align);
2994 n = mono_class_value_size (klass, &align);
2996 #if HAVE_WRITE_BARRIERS
2997 /* if native is true there should be no references in the struct */
2998 if (write_barrier && klass->has_references && !native) {
3001 NEW_PCONST (cfg, iargs [2], klass);
3003 mono_emit_jit_icall (cfg, bblock, mono_value_copy, iargs, ip);
3008 /* FIXME: add write barrier handling */
3009 if ((cfg->opt & MONO_OPT_INTRINS) && !to_end && n <= sizeof (gpointer) * 5) {
3011 if (dest->opcode == OP_LDADDR) {
3012 /* Keep liveness info correct */
3013 NEW_DUMMY_STORE (cfg, inst, dest->inst_i0->inst_c0);
3014 MONO_ADD_INS (bblock, inst);
3016 NEW_MEMCPY (cfg, inst, dest, src, n, align);
3017 MONO_ADD_INS (bblock, inst);
3022 NEW_ICONST (cfg, iargs [2], n);
3024 memcpy_method = get_memcpy_method ();
3025 mono_emit_method_call_spilled_full (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL, FALSE, to_end);
3029 get_memset_method (void)
3031 static MonoMethod *memset_method = NULL;
3032 if (!memset_method) {
3033 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
3035 g_error ("Old corlib found. Install a new one");
3037 return memset_method;
3041 handle_initobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, const guchar *ip, MonoClass *klass, MonoInst **stack_start, MonoInst **sp)
3043 MonoInst *iargs [3];
3044 MonoInst *ins, *zero_int32;
3047 MonoMethod *memset_method;
3049 NEW_ICONST (cfg, zero_int32, 0);
3051 mono_class_init (klass);
3052 n = mono_class_value_size (klass, &align);
3053 MONO_INST_NEW (cfg, ins, 0);
3055 ins->inst_left = dest;
3056 ins->inst_right = zero_int32;
3058 ins->opcode = CEE_STIND_I1;
3059 MONO_ADD_INS (bblock, ins);
3060 } else if ((n == 2) && (align >= 2)) {
3061 ins->opcode = CEE_STIND_I2;
3062 MONO_ADD_INS (bblock, ins);
3063 } else if ((n == 2) && (align >= 4)) {
3064 ins->opcode = CEE_STIND_I4;
3065 MONO_ADD_INS (bblock, ins);
3066 } else if (n <= sizeof (gpointer) * 5) {
3067 NEW_MEMSET (cfg, ins, dest, 0, n, align);
3068 MONO_ADD_INS (bblock, ins);
3070 memset_method = get_memset_method ();
3071 handle_loaded_temps (cfg, bblock, stack_start, sp);
3073 NEW_ICONST (cfg, iargs [1], 0);
3074 NEW_ICONST (cfg, iargs [2], n);
3075 mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
3080 handle_alloc (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, gboolean for_box, const guchar *ip)
3082 MonoInst *iargs [2];
3085 if (cfg->opt & MONO_OPT_SHARED) {
3086 NEW_DOMAINCONST (cfg, iargs [0]);
3087 NEW_CLASSCONST (cfg, iargs [1], klass);
3089 alloc_ftn = mono_object_new;
3090 } else if (cfg->compile_aot && bblock->out_of_line && klass->type_token && klass->image == mono_defaults.corlib) {
3091 /* This happens often in argument checking code, eg. throw new FooException... */
3092 /* Avoid relocations by calling a helper function specialized to mscorlib */
3093 NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (klass->type_token));
3094 return mono_emit_jit_icall (cfg, bblock, mono_helper_newobj_mscorlib, iargs, ip);
3096 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3097 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, for_box);
3100 if (managed_alloc) {
3101 NEW_VTABLECONST (cfg, iargs [0], vtable);
3102 return mono_emit_method_call_spilled (cfg, bblock, managed_alloc, mono_method_signature (managed_alloc), iargs, ip, NULL);
3104 alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
3106 guint32 lw = vtable->klass->instance_size;
3107 lw = ((lw + (sizeof (gpointer) - 1)) & ~(sizeof (gpointer) - 1)) / sizeof (gpointer);
3108 NEW_ICONST (cfg, iargs [0], lw);
3109 NEW_VTABLECONST (cfg, iargs [1], vtable);
3112 NEW_VTABLECONST (cfg, iargs [0], vtable);
3115 return mono_emit_jit_icall (cfg, bblock, alloc_ftn, iargs, ip);
3119 handle_alloc_from_inst (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, MonoInst *data_inst,
3120 gboolean for_box, const guchar *ip)
3122 MonoInst *iargs [2];
3123 MonoMethod *managed_alloc = NULL;
3126 FIXME: we cannot get managed_alloc here because we can't get
3127 the class's vtable (because it's not a closed class)
3129 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
3130 MonoMethod *managed_alloc = mono_gc_get_managed_allocator (vtable, for_box);
3133 if (cfg->opt & MONO_OPT_SHARED) {
3134 NEW_DOMAINCONST (cfg, iargs [0]);
3135 iargs [1] = data_inst;
3136 alloc_ftn = mono_object_new;
3138 g_assert (!cfg->compile_aot);
3140 if (managed_alloc) {
3141 iargs [0] = data_inst;
3142 return mono_emit_method_call_spilled (cfg, bblock, managed_alloc,
3143 mono_method_signature (managed_alloc), iargs, ip, NULL);
3146 iargs [0] = data_inst;
3147 alloc_ftn = mono_object_new_specific;
3150 return mono_emit_jit_icall (cfg, bblock, alloc_ftn, iargs, ip);
3154 handle_box_copy (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *val, const guchar *ip, MonoClass *klass, int temp)
3156 MonoInst *dest, *vtoffset, *add, *vstore;
3158 NEW_TEMPLOAD (cfg, dest, temp);
3159 NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
3160 MONO_INST_NEW (cfg, add, OP_PADD);
3161 add->inst_left = dest;
3162 add->inst_right = vtoffset;
3165 MONO_INST_NEW (cfg, vstore, CEE_STIND_I);
3166 vstore->opcode = mini_type_to_stind (cfg, &klass->byval_arg);
3167 vstore->cil_code = ip;
3168 vstore->inst_left = add;
3169 vstore->inst_right = val;
3171 #ifdef MONO_ARCH_SOFT_FLOAT
3172 if (vstore->opcode == CEE_STIND_R4) {
3173 handle_store_float (cfg, bblock, add, val, ip);
3176 if (vstore->opcode == CEE_STOBJ) {
3177 handle_stobj (cfg, bblock, add, val, ip, klass, FALSE, FALSE, TRUE);
3179 MONO_ADD_INS (bblock, vstore);
3181 NEW_TEMPLOAD (cfg, dest, temp);
3186 handle_box (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *val, const guchar *ip, MonoClass *klass)
3191 if (mono_class_is_nullable (klass)) {
3192 MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
3193 temp = mono_emit_method_call_spilled (cfg, bblock, method, mono_method_signature (method), &val, ip, NULL);
3194 NEW_TEMPLOAD (cfg, dest, temp);
3198 temp = handle_alloc (cfg, bblock, klass, TRUE, ip);
3200 return handle_box_copy (cfg, bblock, val, ip, klass, temp);
3204 handle_box_from_inst (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *val, const guchar *ip,
3205 MonoClass *klass, MonoInst *data_inst)
3209 g_assert (!mono_class_is_nullable (klass));
3211 temp = handle_alloc_from_inst (cfg, bblock, klass, data_inst, TRUE, ip);
3213 return handle_box_copy (cfg, bblock, val, ip, klass, temp);
3217 handle_delegate_ctor (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, MonoInst *target, MonoMethod *method, unsigned char *ip)
3219 gpointer *trampoline;
3220 MonoInst *obj, *ins, *store, *offset_ins, *method_ins, *tramp_ins;
3223 temp = handle_alloc (cfg, bblock, klass, FALSE, ip);
3225 /* Inline the contents of mono_delegate_ctor */
3227 /* Set target field */
3228 /* Optimize away setting of NULL target */
3229 if (!(target->opcode == OP_PCONST && target->inst_p0 == 0)) {
3230 NEW_TEMPLOAD (cfg, obj, temp);
3231 NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, target));
3232 MONO_INST_NEW (cfg, ins, OP_PADD);
3233 ins->inst_left = obj;
3234 ins->inst_right = offset_ins;
3236 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
3237 store->inst_left = ins;
3238 store->inst_right = target;
3239 mono_bblock_add_inst (bblock, store);
3242 /* Set method field */
3243 NEW_TEMPLOAD (cfg, obj, temp);
3244 NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, method));
3245 MONO_INST_NEW (cfg, ins, OP_PADD);
3246 ins->inst_left = obj;
3247 ins->inst_right = offset_ins;
3249 NEW_METHODCONST (cfg, method_ins, method);
3251 MONO_INST_NEW (cfg, store, CEE_STIND_I);
3252 store->inst_left = ins;
3253 store->inst_right = method_ins;
3254 mono_bblock_add_inst (bblock, store);
3256 /* Set invoke_impl field */
3257 NEW_TEMPLOAD (cfg, obj, temp);
3258 NEW_ICONST (cfg, offset_ins, G_STRUCT_OFFSET (MonoDelegate, invoke_impl));
3259 MONO_INST_NEW (cfg, ins, OP_PADD);
3260 ins->inst_left = obj;
3261 ins->inst_right = offset_ins;
3263 trampoline = mono_create_delegate_trampoline (klass);
3264 NEW_AOTCONST (cfg, tramp_ins, MONO_PATCH_INFO_ABS, trampoline);
3266 MONO_INST_NEW (cfg, store, CEE_STIND_I);
3267 store->inst_left = ins;
3268 store->inst_right = tramp_ins;
3269 mono_bblock_add_inst (bblock, store);
3271 /* All the checks which are in mono_delegate_ctor () are done by the delegate trampoline */
3273 NEW_TEMPLOAD (cfg, obj, temp);
3279 handle_array_new (MonoCompile *cfg, MonoBasicBlock *bblock, int rank, MonoInst **sp, unsigned char *ip)
3281 MonoMethodSignature *esig;
3282 char icall_name [256];
3284 MonoJitICallInfo *info;
3286 /* Need to register the icall so it gets an icall wrapper */
3287 sprintf (icall_name, "ves_array_new_va_%d", rank);
3290 info = mono_find_jit_icall_by_name (icall_name);
3292 esig = mono_get_array_new_va_signature (rank);
3293 name = g_strdup (icall_name);
3294 info = mono_register_jit_icall (mono_array_new_va, name, esig, FALSE);
3296 g_hash_table_insert (jit_icall_name_hash, name, name);
3300 cfg->flags |= MONO_CFG_HAS_VARARGS;
3302 /* FIXME: This uses info->sig, but it should use the signature of the wrapper */
3303 return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, sp, ip, TRUE, FALSE);
3307 mono_emit_load_got_addr (MonoCompile *cfg)
3309 MonoInst *load, *store, *dummy_use;
3312 if (!cfg->got_var || cfg->got_var_allocated)
3315 MONO_INST_NEW (cfg, get_got, OP_LOAD_GOTADDR);
3316 NEW_TEMPSTORE (cfg, store, cfg->got_var->inst_c0, get_got);
3318 /* Add it to the start of the first bblock */
3319 MONO_INST_LIST_ADD (&store->node, &cfg->bb_entry->ins_list);
3321 cfg->got_var_allocated = TRUE;
3324 * Add a dummy use to keep the got_var alive, since real uses might
3325 * only be generated in the decompose or instruction selection phases.
3326 * Add it to end_bblock, so the variable's lifetime covers the whole
3329 NEW_TEMPLOAD (cfg, load, cfg->got_var->inst_c0);
3330 NEW_DUMMY_USE (cfg, dummy_use, load);
3331 MONO_ADD_INS (cfg->bb_exit, dummy_use);
3334 #define CODE_IS_STLOC(ip) (((ip) [0] >= CEE_STLOC_0 && (ip) [0] <= CEE_STLOC_3) || ((ip) [0] == CEE_STLOC_S))
3337 mini_class_is_system_array (MonoClass *klass)
3339 if (klass->parent == mono_defaults.array_class)
3346 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
3348 MonoMethodHeader *header = mono_method_get_header (method);
3349 MonoMethodSignature *signature = mono_method_signature (method);
3353 if (cfg->generic_sharing_context)
3356 if (method->inline_failure)
3359 #ifdef MONO_ARCH_HAVE_LMF_OPS
3360 if (((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3361 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) &&
3362 !MONO_TYPE_ISSTRUCT (signature->ret) && !mini_class_is_system_array (method->klass))
3366 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3367 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
3368 (method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
3369 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
3370 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3371 (method->klass->marshalbyref) ||
3372 !header || header->num_clauses ||
3373 /* fixme: why cant we inline valuetype returns? */
3374 MONO_TYPE_ISSTRUCT (signature->ret))
3377 #ifdef MONO_ARCH_SOFT_FLOAT
3378 /* this complicates things, fix later */
3379 if (signature->ret->type == MONO_TYPE_R4)
3382 /* its not worth to inline methods with valuetype arguments?? */
3383 for (i = 0; i < signature->param_count; i++) {
3384 if (MONO_TYPE_ISSTRUCT (signature->params [i])) {
3387 #ifdef MONO_ARCH_SOFT_FLOAT
3388 /* this complicates things, fix later */
3389 if (!signature->params [i]->byref && signature->params [i]->type == MONO_TYPE_R4)
3394 /* also consider num_locals? */
3395 /* Do the size check early to avoid creating vtables */
3396 if (getenv ("MONO_INLINELIMIT")) {
3397 if (header->code_size >= atoi (getenv ("MONO_INLINELIMIT"))) {
3400 } else if (header->code_size >= INLINE_LENGTH_LIMIT)
3404 * if we can initialize the class of the method right away, we do,
3405 * otherwise we don't allow inlining if the class needs initialization,
3406 * since it would mean inserting a call to mono_runtime_class_init()
3407 * inside the inlined code
3409 if (!(cfg->opt & MONO_OPT_SHARED)) {
3410 if (method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) {
3411 if (cfg->run_cctors && method->klass->has_cctor) {
3412 if (!method->klass->runtime_info)
3413 /* No vtable created yet */
3415 vtable = mono_class_vtable (cfg->domain, method->klass);
3418 /* This makes so that inline cannot trigger */
3419 /* .cctors: too many apps depend on them */
3420 /* running with a specific order... */
3421 if (! vtable->initialized)
3423 mono_runtime_class_init (vtable);
3425 } else if (mono_class_needs_cctor_run (method->klass, NULL)) {
3426 if (!method->klass->runtime_info)
3427 /* No vtable created yet */
3429 vtable = mono_class_vtable (cfg->domain, method->klass);
3432 if (!vtable->initialized)
3437 * If we're compiling for shared code
3438 * the cctor will need to be run at aot method load time, for example,
3439 * or at the end of the compilation of the inlining method.
3441 if (mono_class_needs_cctor_run (method->klass, NULL) && !((method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3444 //if (!MONO_TYPE_IS_VOID (signature->ret)) return FALSE;
3447 * CAS - do not inline methods with declarative security
3448 * Note: this has to be before any possible return TRUE;
3450 if (mono_method_has_declsec (method))
3457 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoVTable *vtable)
3459 if (vtable->initialized && !cfg->compile_aot)
3462 if (vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)
3465 if (!mono_class_needs_cctor_run (vtable->klass, method))
3468 if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (vtable->klass == method->klass))
3469 /* The initialization is already done before the method is called */
3476 mini_get_ldelema_ins (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
3480 MonoMethod *addr_method;
3483 rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
3486 MONO_INST_NEW (cfg, addr, CEE_LDELEMA);
3487 addr->inst_left = sp [0];
3488 addr->inst_right = sp [1];
3489 addr->type = STACK_MP;
3490 addr->klass = cmethod->klass->element_class;
3494 if (rank == 2 && (cfg->opt & MONO_OPT_INTRINS)) {
3495 #if defined(MONO_ARCH_EMULATE_MUL_DIV) && !defined(MONO_ARCH_NO_EMULATE_MUL)
3496 /* OP_LDELEMA2D depends on OP_LMUL */
3499 NEW_GROUP (cfg, indexes, sp [1], sp [2]);
3500 MONO_INST_NEW (cfg, addr, OP_LDELEMA2D);
3501 addr->inst_left = sp [0];
3502 addr->inst_right = indexes;
3503 addr->type = STACK_MP;
3504 addr->klass = cmethod->klass->element_class;
3509 element_size = mono_class_array_element_size (cmethod->klass->element_class);
3510 addr_method = mono_marshal_get_array_address (rank, element_size);
3511 temp = mono_emit_method_call_spilled (cfg, bblock, addr_method, addr_method->signature, sp, ip, NULL);
3512 NEW_TEMPLOAD (cfg, addr, temp);
3517 static MonoJitICallInfo **emul_opcode_map = NULL;
3520 mono_find_jit_opcode_emulation (int opcode)
3522 g_assert (opcode >= 0 && opcode <= OP_LAST);
3523 if (emul_opcode_map)
3524 return emul_opcode_map [opcode];
3530 is_unsigned_regsize_type (MonoType *type)
3532 switch (type->type) {
3536 #if SIZEOF_VOID_P == 8
3537 /*case MONO_TYPE_U8: this requires different opcodes in inssel.brg */
3546 mini_get_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
3548 MonoInst *ins = NULL;
3550 static MonoClass *runtime_helpers_class = NULL;
3551 if (! runtime_helpers_class)
3552 runtime_helpers_class = mono_class_from_name (mono_defaults.corlib,
3553 "System.Runtime.CompilerServices", "RuntimeHelpers");
3555 if (cmethod->klass == mono_defaults.string_class) {
3556 if (strcmp (cmethod->name, "get_Chars") == 0) {
3557 MONO_INST_NEW (cfg, ins, OP_GETCHR);
3558 ins->inst_i0 = args [0];
3559 ins->inst_i1 = args [1];
3561 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3562 MONO_INST_NEW (cfg, ins, OP_STRLEN);
3563 ins->inst_i0 = args [0];
3565 } else if (strcmp (cmethod->name, "InternalSetChar") == 0) {
3567 MONO_INST_NEW (cfg, get_addr, OP_STR_CHAR_ADDR);
3568 get_addr->inst_i0 = args [0];
3569 get_addr->inst_i1 = args [1];
3570 MONO_INST_NEW (cfg, ins, CEE_STIND_I2);
3571 ins->inst_i0 = get_addr;
3572 ins->inst_i1 = args [2];
3576 } else if (cmethod->klass == mono_defaults.object_class) {
3577 if (strcmp (cmethod->name, "GetType") == 0) {
3578 MONO_INST_NEW (cfg, ins, OP_GETTYPE);
3579 ins->inst_i0 = args [0];
3581 /* The OP_GETHASHCODE rule depends on OP_MUL */
3582 #if !defined(MONO_ARCH_EMULATE_MUL_DIV) && !defined(HAVE_MOVING_COLLECTOR)
3583 } else if (strcmp (cmethod->name, "InternalGetHashCode") == 0) {
3584 MONO_INST_NEW (cfg, ins, OP_GETHASHCODE);
3585 ins->inst_i0 = args [0];
3588 } else if (strcmp (cmethod->name, ".ctor") == 0) {
3589 MONO_INST_NEW (cfg, ins, OP_NOP);
3593 } else if (cmethod->klass == mono_defaults.array_class) {
3594 if (cmethod->name [0] != 'g')
3597 if (strcmp (cmethod->name, "get_Rank") == 0) {
3598 MONO_INST_NEW (cfg, ins, OP_ARRAY_RANK);
3599 ins->inst_i0 = args [0];
3601 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3602 MONO_INST_NEW (cfg, ins, CEE_LDLEN);
3603 ins->inst_i0 = args [0];
3607 } else if (cmethod->klass == runtime_helpers_class) {
3608 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0) {
3609 NEW_ICONST (cfg, ins, G_STRUCT_OFFSET (MonoString, chars));
3613 } else if (cmethod->klass == mono_defaults.thread_class) {
3614 if (strcmp (cmethod->name, "get_CurrentThread") == 0 && (ins = mono_arch_get_thread_intrinsic (cfg)))
3616 if (strcmp (cmethod->name, "MemoryBarrier") == 0) {
3617 MONO_INST_NEW (cfg, ins, OP_MEMORY_BARRIER);
3620 } else if (mini_class_is_system_array (cmethod->klass) &&
3621 strcmp (cmethod->name, "GetGenericValueImpl") == 0) {
3623 MonoInst *ldelem, *store, *load;
3624 MonoClass *eklass = mono_class_from_mono_type (fsig->params [1]);
3626 n = mini_type_to_stind (cfg, &eklass->byval_arg);
3631 NEW_LDELEMA (cfg, ldelem, sp, eklass);
3632 ldelem->flags |= MONO_INST_NORANGECHECK;
3633 MONO_INST_NEW (cfg, store, n);
3634 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, &eklass->byval_arg));
3635 type_to_eval_stack_type (cfg, &eklass->byval_arg, load);
3636 load->inst_left = ldelem;
3637 store->inst_left = args [2];
3638 store->inst_right = load;
3640 } else if (cmethod->klass == mono_defaults.math_class) {
3641 if (strcmp (cmethod->name, "Min") == 0) {
3642 if (is_unsigned_regsize_type (fsig->params [0])) {
3643 MONO_INST_NEW (cfg, ins, OP_MIN);
3644 ins->inst_i0 = args [0];
3645 ins->inst_i1 = args [1];
3648 } else if (strcmp (cmethod->name, "Max") == 0) {
3649 if (is_unsigned_regsize_type (fsig->params [0])) {
3650 MONO_INST_NEW (cfg, ins, OP_MAX);
3651 ins->inst_i0 = args [0];
3652 ins->inst_i1 = args [1];
3656 } else if (cmethod->klass->image == mono_defaults.corlib &&
3657 (strcmp (cmethod->klass->name_space, "System.Threading") == 0) &&
3658 (strcmp (cmethod->klass->name, "Interlocked") == 0)) {
3661 #if SIZEOF_VOID_P == 8
3662 if (strcmp (cmethod->name, "Read") == 0 && (fsig->params [0]->type == MONO_TYPE_I8)) {
3663 /* 64 bit reads are already atomic */
3664 MONO_INST_NEW (cfg, ins, CEE_LDIND_I8);
3665 ins->inst_i0 = args [0];
3669 #ifdef MONO_ARCH_HAVE_ATOMIC_ADD
3670 if (strcmp (cmethod->name, "Increment") == 0) {
3671 MonoInst *ins_iconst;
3674 if (fsig->params [0]->type == MONO_TYPE_I4)
3675 opcode = OP_ATOMIC_ADD_NEW_I4;
3676 else if (fsig->params [0]->type == MONO_TYPE_I8)
3677 opcode = OP_ATOMIC_ADD_NEW_I8;
3679 g_assert_not_reached ();
3681 #if SIZEOF_VOID_P == 4
3682 if (opcode == OP_ATOMIC_ADD_NEW_I8)
3686 MONO_INST_NEW (cfg, ins, opcode);
3687 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
3688 ins_iconst->inst_c0 = 1;
3690 ins->inst_i0 = args [0];
3691 ins->inst_i1 = ins_iconst;
3692 } else if (strcmp (cmethod->name, "Decrement") == 0) {
3693 MonoInst *ins_iconst;
3696 if (fsig->params [0]->type == MONO_TYPE_I4)
3697 opcode = OP_ATOMIC_ADD_NEW_I4;
3698 else if (fsig->params [0]->type == MONO_TYPE_I8)
3699 opcode = OP_ATOMIC_ADD_NEW_I8;
3701 g_assert_not_reached ();
3703 #if SIZEOF_VOID_P == 4
3704 if (opcode == OP_ATOMIC_ADD_NEW_I8)
3708 MONO_INST_NEW (cfg, ins, opcode);
3709 MONO_INST_NEW (cfg, ins_iconst, OP_ICONST);
3710 ins_iconst->inst_c0 = -1;
3712 ins->inst_i0 = args [0];
3713 ins->inst_i1 = ins_iconst;
3714 } else if (strcmp (cmethod->name, "Add") == 0) {
3717 if (fsig->params [0]->type == MONO_TYPE_I4)
3718 opcode = OP_ATOMIC_ADD_NEW_I4;
3719 else if (fsig->params [0]->type == MONO_TYPE_I8)
3720 opcode = OP_ATOMIC_ADD_NEW_I8;
3722 g_assert_not_reached ();
3724 #if SIZEOF_VOID_P == 4
3725 if (opcode == OP_ATOMIC_ADD_NEW_I8)
3729 MONO_INST_NEW (cfg, ins, opcode);
3731 ins->inst_i0 = args [0];
3732 ins->inst_i1 = args [1];
3734 #endif /* MONO_ARCH_HAVE_ATOMIC_ADD */
3736 #ifdef MONO_ARCH_HAVE_ATOMIC_EXCHANGE
3737 if (strcmp (cmethod->name, "Exchange") == 0) {
3740 if (fsig->params [0]->type == MONO_TYPE_I4)
3741 opcode = OP_ATOMIC_EXCHANGE_I4;
3742 #if SIZEOF_VOID_P == 8
3743 else if ((fsig->params [0]->type == MONO_TYPE_I8) ||
3744 (fsig->params [0]->type == MONO_TYPE_I) ||
3745 (fsig->params [0]->type == MONO_TYPE_OBJECT))
3746 opcode = OP_ATOMIC_EXCHANGE_I8;
3748 else if ((fsig->params [0]->type == MONO_TYPE_I) ||
3749 (fsig->params [0]->type == MONO_TYPE_OBJECT))
3750 opcode = OP_ATOMIC_EXCHANGE_I4;
3755 #if SIZEOF_VOID_P == 4
3756 if (opcode == OP_ATOMIC_EXCHANGE_I8)
3760 MONO_INST_NEW (cfg, ins, opcode);
3762 ins->inst_i0 = args [0];
3763 ins->inst_i1 = args [1];
3765 #endif /* MONO_ARCH_HAVE_ATOMIC_EXCHANGE */
3767 #ifdef MONO_ARCH_HAVE_ATOMIC_CAS_IMM
3769 * Can't implement CompareExchange methods this way since they have
3770 * three arguments. We can implement one of the common cases, where the new
3771 * value is a constant.
3773 if ((strcmp (cmethod->name, "CompareExchange") == 0)) {
3774 if (fsig->params [1]->type == MONO_TYPE_I4 && args [2]->opcode == OP_ICONST) {
3775 MONO_INST_NEW (cfg, ins, OP_ATOMIC_CAS_IMM_I4);
3776 ins->inst_i0 = args [0];
3777 ins->inst_i1 = args [1];
3778 ins->backend.data = GINT_TO_POINTER (args [2]->inst_c0);
3780 /* The I8 case is hard to detect, since the arg might be a conv.i8 (iconst) tree */
3782 #endif /* MONO_ARCH_HAVE_ATOMIC_CAS_IMM */
3786 } else if (cmethod->klass->image == mono_defaults.corlib) {
3787 if (cmethod->name [0] == 'B' && strcmp (cmethod->name, "Break") == 0
3788 && strcmp (cmethod->klass->name, "Debugger") == 0) {
3789 MONO_INST_NEW (cfg, ins, OP_BREAK);
3792 if (cmethod->name [0] == 'g' && strcmp (cmethod->name, "get_IsRunningOnWindows") == 0
3793 && strcmp (cmethod->klass->name, "Environment") == 0) {
3794 #ifdef PLATFORM_WIN32
3795 NEW_ICONST (cfg, ins, 1);
3797 NEW_ICONST (cfg, ins, 0);
3803 return mono_arch_get_inst_for_method (cfg, cmethod, fsig, args);
3807 mono_save_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, MonoInst **sp, MonoInst **args)
3809 MonoInst *store, *temp;
3812 g_assert (!MONO_TYPE_ISSTRUCT (sig->ret));
3814 if (!sig->hasthis && sig->param_count == 0)
3818 if (sp [0]->opcode == OP_ICONST) {
3821 temp = mono_compile_create_var (cfg, type_from_stack_type (*sp), OP_LOCAL);
3823 NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3824 /* FIXME: handle CEE_STIND_R4 */
3825 store->cil_code = sp [0]->cil_code;
3826 MONO_ADD_INS (bblock, store);
3831 for (i = 0; i < sig->param_count; ++i) {
3832 if (sp [0]->opcode == OP_ICONST) {
3835 temp = mono_compile_create_var (cfg, sig->params [i], OP_LOCAL);
3837 NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3838 store->cil_code = sp [0]->cil_code;
3839 /* FIXME: handle CEE_STIND_R4 */
3840 if (store->opcode == CEE_STOBJ) {
3841 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
3842 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, temp->klass, FALSE, FALSE, FALSE);
3843 #ifdef MONO_ARCH_SOFT_FLOAT
3844 } else if (store->opcode == CEE_STIND_R4) {
3845 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
3846 handle_store_float (cfg, bblock, store, *sp, sp [0]->cil_code);
3849 MONO_ADD_INS (bblock, store);
3855 #define MONO_INLINE_CALLED_LIMITED_METHODS 0
3856 #define MONO_INLINE_CALLER_LIMITED_METHODS 0
3858 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
3860 mono_inline_called_method_name_limit = NULL;
3861 static gboolean check_inline_called_method_name_limit (MonoMethod *called_method) {
3862 char *called_method_name = mono_method_full_name (called_method, TRUE);
3865 if (mono_inline_called_method_name_limit == NULL) {
3866 char *limit_string = getenv ("MONO_INLINE_CALLED_METHOD_NAME_LIMIT");
3867 if (limit_string != NULL) {
3868 mono_inline_called_method_name_limit = limit_string;
3870 mono_inline_called_method_name_limit = (char *) "";
3874 strncmp_result = strncmp (called_method_name, mono_inline_called_method_name_limit, strlen (mono_inline_called_method_name_limit));
3875 g_free (called_method_name);
3877 //return (strncmp_result <= 0);
3878 return (strncmp_result == 0);
3882 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
3884 mono_inline_caller_method_name_limit = NULL;
3885 static gboolean check_inline_caller_method_name_limit (MonoMethod *caller_method) {
3886 char *caller_method_name = mono_method_full_name (caller_method, TRUE);
3889 if (mono_inline_caller_method_name_limit == NULL) {
3890 char *limit_string = getenv ("MONO_INLINE_CALLER_METHOD_NAME_LIMIT");
3891 if (limit_string != NULL) {
3892 mono_inline_caller_method_name_limit = limit_string;
3894 mono_inline_caller_method_name_limit = (char *) "";
3898 strncmp_result = strncmp (caller_method_name, mono_inline_caller_method_name_limit, strlen (mono_inline_caller_method_name_limit));
3899 g_free (caller_method_name);
3901 //return (strncmp_result <= 0);
3902 return (strncmp_result == 0);
3907 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoBasicBlock *bblock, MonoInst **sp,
3908 guchar *ip, guint real_offset, GList *dont_inline, MonoBasicBlock **last_b, gboolean inline_allways)
3910 MonoInst *ins, *rvar = NULL;
3911 MonoMethodHeader *cheader;
3912 MonoBasicBlock *ebblock, *sbblock;
3913 int i, costs, new_locals_offset;
3914 MonoMethod *prev_inlined_method;
3915 MonoBasicBlock **prev_cil_offset_to_bb;
3916 unsigned char* prev_cil_start;
3917 guint32 prev_cil_offset_to_bb_len;
3919 g_assert (cfg->exception_type == MONO_EXCEPTION_NONE);
3921 #if (MONO_INLINE_CALLED_LIMITED_METHODS)
3922 if ((! inline_allways) && ! check_inline_called_method_name_limit (cmethod))
3925 #if (MONO_INLINE_CALLER_LIMITED_METHODS)
3926 if ((! inline_allways) && ! check_inline_caller_method_name_limit (cfg->method))
3930 if (bblock->out_of_line && !inline_allways)
3933 if (cfg->verbose_level > 2)
3934 g_print ("INLINE START %p %s -> %s\n", cmethod, mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
3936 if (!cmethod->inline_info) {
3937 mono_jit_stats.inlineable_methods++;
3938 cmethod->inline_info = 1;
3940 /* allocate space to store the return value */
3941 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
3942 rvar = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
3945 /* allocate local variables */
3946 cheader = mono_method_get_header (cmethod);
3947 new_locals_offset = cfg->num_varinfo;
3948 for (i = 0; i < cheader->num_locals; ++i)
3949 mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
3951 /* allocate starte and end blocks */
3952 NEW_BBLOCK (cfg, sbblock);
3953 sbblock->block_num = cfg->num_bblocks++;
3954 sbblock->real_offset = real_offset;
3956 NEW_BBLOCK (cfg, ebblock);
3957 ebblock->block_num = cfg->num_bblocks++;
3958 ebblock->real_offset = real_offset;
3960 prev_inlined_method = cfg->inlined_method;
3961 cfg->inlined_method = cmethod;
3962 prev_cil_offset_to_bb = cfg->cil_offset_to_bb;
3963 prev_cil_offset_to_bb_len = cfg->cil_offset_to_bb_len;
3964 prev_cil_start = cfg->cil_start;
3966 costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, new_locals_offset, rvar, dont_inline, sp, real_offset, *ip == CEE_CALLVIRT);
3968 cfg->inlined_method = prev_inlined_method;
3969 cfg->cil_offset_to_bb = prev_cil_offset_to_bb;
3970 cfg->cil_offset_to_bb_len = prev_cil_offset_to_bb_len;
3971 cfg->cil_start = prev_cil_start;
3973 if ((costs >= 0 && costs < 60) || inline_allways) {
3974 if (cfg->verbose_level > 2)
3975 g_print ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
3977 mono_jit_stats.inlined_methods++;
3979 /* always add some code to avoid block split failures */
3980 MONO_INST_NEW (cfg, ins, OP_NOP);
3981 MONO_ADD_INS (bblock, ins);
3984 bblock->next_bb = sbblock;
3985 link_bblock (cfg, bblock, sbblock);
3988 NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
3989 #ifdef MONO_ARCH_SOFT_FLOAT
3990 if (ins->opcode == CEE_LDIND_R4) {
3992 NEW_TEMPLOADA (cfg, ins, rvar->inst_c0);
3993 temp = handle_load_float (cfg, bblock, ins, ip);
3994 NEW_TEMPLOAD (cfg, ins, temp);
4002 if (cfg->verbose_level > 2)
4003 g_print ("INLINE ABORTED %s\n", mono_method_full_name (cmethod, TRUE));
4004 cfg->exception_type = MONO_EXCEPTION_NONE;
4005 mono_loader_clear_error ();
4006 cmethod->inline_failure = TRUE;
4012 * Some of these comments may well be out-of-date.
4013 * Design decisions: we do a single pass over the IL code (and we do bblock
4014 * splitting/merging in the few cases when it's required: a back jump to an IL
4015 * address that was not already seen as bblock starting point).
4016 * Code is validated as we go (full verification is still better left to metadata/verify.c).
4017 * Complex operations are decomposed in simpler ones right away. We need to let the
4018 * arch-specific code peek and poke inside this process somehow (except when the
4019 * optimizations can take advantage of the full semantic info of coarse opcodes).
4020 * All the opcodes of the form opcode.s are 'normalized' to opcode.
4021 * MonoInst->opcode initially is the IL opcode or some simplification of that
4022 * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific
4023 * opcode with value bigger than OP_LAST.
4024 * At this point the IR can be handed over to an interpreter, a dumb code generator
4025 * or to the optimizing code generator that will translate it to SSA form.
4027 * Profiling directed optimizations.
4028 * We may compile by default with few or no optimizations and instrument the code
4029 * or the user may indicate what methods to optimize the most either in a config file
4030 * or through repeated runs where the compiler applies offline the optimizations to
4031 * each method and then decides if it was worth it.
4035 #define CHECK_TYPE(ins) if (!(ins)->type) UNVERIFIED
4036 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) UNVERIFIED
4037 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) UNVERIFIED
4038 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) UNVERIFIED
4039 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) UNVERIFIED
4040 #define CHECK_OPSIZE(size) if (ip + size > end) UNVERIFIED
4041 #define CHECK_UNVERIFIABLE(cfg) if (cfg->unverifiable) UNVERIFIED
4042 #define CHECK_TYPELOAD(klass) if (!(klass) || (klass)->exception_type) {cfg->exception_ptr = klass; goto load_error;}
4044 /* offset from br.s -> br like opcodes */
4045 #define BIG_BRANCH_OFFSET 13
4047 static inline gboolean
4048 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
4050 MonoBasicBlock *b = cfg->cil_offset_to_bb [ip - cfg->cil_start];
4052 return b == NULL || b == bb;
4056 get_basic_blocks (MonoCompile *cfg, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
4058 unsigned char *ip = start;
4059 unsigned char *target;
4062 MonoBasicBlock *bblock;
4063 const MonoOpcode *opcode;
4066 cli_addr = ip - start;
4067 i = mono_opcode_value ((const guint8 **)&ip, end);
4070 opcode = &mono_opcodes [i];
4071 switch (opcode->argument) {
4072 case MonoInlineNone:
4075 case MonoInlineString:
4076 case MonoInlineType:
4077 case MonoInlineField:
4078 case MonoInlineMethod:
4081 case MonoShortInlineR:
4088 case MonoShortInlineVar:
4089 case MonoShortInlineI:
4092 case MonoShortInlineBrTarget:
4093 target = start + cli_addr + 2 + (signed char)ip [1];
4094 GET_BBLOCK (cfg, bblock, target);
4097 GET_BBLOCK (cfg, bblock, ip);
4099 case MonoInlineBrTarget:
4100 target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
4101 GET_BBLOCK (cfg, bblock, target);
4104 GET_BBLOCK (cfg, bblock, ip);
4106 case MonoInlineSwitch: {
4107 guint32 n = read32 (ip + 1);
4110 cli_addr += 5 + 4 * n;
4111 target = start + cli_addr;
4112 GET_BBLOCK (cfg, bblock, target);
4114 for (j = 0; j < n; ++j) {
4115 target = start + cli_addr + (gint32)read32 (ip);
4116 GET_BBLOCK (cfg, bblock, target);
4126 g_assert_not_reached ();
4129 if (i == CEE_THROW) {
4130 unsigned char *bb_start = ip - 1;
4132 /* Find the start of the bblock containing the throw */
4134 while ((bb_start >= start) && !bblock) {
4135 bblock = cfg->cil_offset_to_bb [(bb_start) - start];
4139 bblock->out_of_line = 1;
4149 emit_tree (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ins, const guint8* ip_next)
4151 MonoInst *store, *temp, *load;
4153 if (ip_in_bb (cfg, bblock, ip_next) &&
4154 (CODE_IS_STLOC (ip_next) || *ip_next == CEE_RET))
4157 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
4158 temp->flags |= MONO_INST_IS_TEMP;
4159 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
4160 /* FIXME: handle CEE_STIND_R4 */
4161 store->cil_code = ins->cil_code;
4162 MONO_ADD_INS (bblock, store);
4163 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
4164 load->cil_code = ins->cil_code;
4168 static inline MonoMethod *
4169 mini_get_method_allow_open (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
4173 if (m->wrapper_type != MONO_WRAPPER_NONE)
4174 return mono_method_get_wrapper_data (m, token);
4176 method = mono_get_method_full (m->klass->image, token, klass, context);
4181 static inline MonoMethod *
4182 mini_get_method (MonoCompile *cfg, MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
4184 MonoMethod *method = mini_get_method_allow_open (m, token, klass, context);
4186 if (method && cfg && !cfg->generic_sharing_context && mono_class_is_open_constructed_type (&method->klass->byval_arg))
4192 static inline MonoClass*
4193 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
4197 if (method->wrapper_type != MONO_WRAPPER_NONE)
4198 klass = mono_method_get_wrapper_data (method, token);
4200 klass = mono_class_get_full (method->klass->image, token, context);
4202 mono_class_init (klass);
4207 * Returns TRUE if the JIT should abort inlining because "callee"
4208 * is influenced by security attributes.
4211 gboolean check_linkdemand (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee, MonoBasicBlock *bblock, unsigned char *ip)
4215 if ((cfg->method != caller) && mono_method_has_declsec (callee)) {
4219 result = mono_declsec_linkdemand (cfg->domain, caller, callee);
4220 if (result == MONO_JIT_SECURITY_OK)
4223 if (result == MONO_JIT_LINKDEMAND_ECMA) {
4224 /* Generate code to throw a SecurityException before the actual call/link */
4225 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4228 NEW_ICONST (cfg, args [0], 4);
4229 NEW_METHODCONST (cfg, args [1], caller);
4230 mono_emit_method_call_spilled (cfg, bblock, secman->linkdemandsecurityexception, mono_method_signature (secman->linkdemandsecurityexception), args, ip, NULL);
4231 } else if (cfg->exception_type == MONO_EXCEPTION_NONE) {
4232 /* don't hide previous results */
4233 cfg->exception_type = MONO_EXCEPTION_SECURITY_LINKDEMAND;
4234 cfg->exception_data = result;
4242 method_access_exception (void)
4244 static MonoMethod *method = NULL;
4247 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4248 method = mono_class_get_method_from_name (secman->securitymanager,
4249 "MethodAccessException", 2);
4256 emit_throw_method_access_exception (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee,
4257 MonoBasicBlock *bblock, unsigned char *ip)
4259 MonoMethod *thrower = method_access_exception ();
4262 NEW_METHODCONST (cfg, args [0], caller);
4263 NEW_METHODCONST (cfg, args [1], callee);
4264 mono_emit_method_call_spilled (cfg, bblock, thrower,
4265 mono_method_signature (thrower), args, ip, NULL);
4269 verification_exception (void)
4271 static MonoMethod *method = NULL;
4274 MonoSecurityManager *secman = mono_security_manager_get_methods ();
4275 method = mono_class_get_method_from_name (secman->securitymanager,
4276 "VerificationException", 0);
4283 emit_throw_verification_exception (MonoCompile *cfg, MonoBasicBlock *bblock, unsigned char *ip)
4285 MonoMethod *thrower = verification_exception ();
4287 mono_emit_method_call_spilled (cfg, bblock, thrower,
4288 mono_method_signature (thrower),
4293 ensure_method_is_allowed_to_call_method (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee,
4294 MonoBasicBlock *bblock, unsigned char *ip)
4296 MonoSecurityCoreCLRLevel caller_level = mono_security_core_clr_method_level (caller, TRUE);
4297 MonoSecurityCoreCLRLevel callee_level = mono_security_core_clr_method_level (callee, TRUE);
4298 gboolean is_safe = TRUE;
4300 if (!(caller_level >= callee_level ||
4301 caller_level == MONO_SECURITY_CORE_CLR_SAFE_CRITICAL ||
4302 callee_level == MONO_SECURITY_CORE_CLR_SAFE_CRITICAL)) {
4307 emit_throw_method_access_exception (cfg, caller, callee, bblock, ip);
4311 method_is_safe (MonoMethod *method)
4314 if (strcmp (method->name, "unsafeMethod") == 0)
4321 * Check that the IL instructions at ip are the array initialization
4322 * sequence and return the pointer to the data and the size.
4325 initialize_array_data (MonoMethod *method, gboolean aot, unsigned char *ip, MonoInst *newarr, int *out_size)
4328 * newarr[System.Int32]
4330 * ldtoken field valuetype ...
4331 * call void class [mscorlib]System.Runtime.CompilerServices.RuntimeHelpers::InitializeArray(class [mscorlib]System.Array, valuetype [mscorlib]System.RuntimeFieldHandle)
4333 if (ip [0] == CEE_DUP && ip [1] == CEE_LDTOKEN && ip [5] == 0x4 && ip [6] == CEE_CALL) {
4334 MonoClass *klass = newarr->inst_newa_class;
4335 guint32 field_token = read32 (ip + 2);
4336 guint32 field_index = field_token & 0xffffff;
4337 guint32 token = read32 (ip + 7);
4339 const char *data_ptr;
4341 MonoMethod *cmethod;
4342 MonoClass *dummy_class;
4343 MonoClassField *field = mono_field_from_token (method->klass->image, field_token, &dummy_class, NULL);
4349 if (newarr->inst_newa_len->opcode != OP_ICONST)
4351 cmethod = mini_get_method (NULL, method, token, NULL, NULL);
4354 if (strcmp (cmethod->name, "InitializeArray") || strcmp (cmethod->klass->name, "RuntimeHelpers") || cmethod->klass->image != mono_defaults.corlib)
4356 switch (mono_type_get_underlying_type (&klass->byval_arg)->type) {
4357 case MONO_TYPE_BOOLEAN:
4361 /* we need to swap on big endian, so punt. Should we handle R4 and R8 as well? */
4362 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
4363 case MONO_TYPE_CHAR:
4373 return NULL; /* stupid ARM FP swapped format */
4382 size *= newarr->inst_newa_len->inst_c0;
4383 if (size > mono_type_size (field->type, &dummy_align))
4386 /*g_print ("optimized in %s: size: %d, numelems: %d\n", method->name, size, newarr->inst_newa_len->inst_c0);*/
4387 field_index = read32 (ip + 2) & 0xffffff;
4388 mono_metadata_field_info (method->klass->image, field_index - 1, NULL, &rva, NULL);
4389 data_ptr = mono_image_rva_map (method->klass->image, rva);
4390 /*g_print ("field: 0x%08x, rva: %d, rva_ptr: %p\n", read32 (ip + 2), rva, data_ptr);*/
4391 /* for aot code we do the lookup on load */
4392 if (aot && data_ptr)
4393 return GUINT_TO_POINTER (rva);
4400 set_exception_type_from_invalid_il (MonoCompile *cfg, MonoMethod *method, unsigned char *ip)
4402 char *method_fname = mono_method_full_name (method, TRUE);
4405 if (mono_method_get_header (method)->code_size == 0)
4406 method_code = g_strdup ("method body is empty.");
4408 method_code = mono_disasm_code_one (NULL, method, ip, NULL);
4409 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
4410 cfg->exception_message = g_strdup_printf ("Invalid IL code in %s: %s\n", method_fname, method_code);
4411 g_free (method_fname);
4412 g_free (method_code);
4416 get_runtime_generic_context (MonoCompile *cfg, MonoMethod *method, MonoInst *this, unsigned char *ip)
4418 g_assert (!method->klass->valuetype);
4420 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
4421 MonoInst *vtable_loc, *vtable_var;
4423 vtable_loc = mono_get_vtable_var (cfg);
4424 NEW_TEMPLOAD (cfg, vtable_var, vtable_loc->inst_c0);
4430 MONO_INST_NEW (cfg, vtable, CEE_LDIND_I);
4431 vtable->inst_left = this;
4432 vtable->type = STACK_PTR;
4439 create_rgctx_lazy_fetch_trampoline (guint32 offset)
4441 static gboolean inited = FALSE;
4442 static int num_trampolines = 0;
4444 gpointer tramp, ptr;
4447 if (rgctx_lazy_fetch_trampoline_hash)
4448 tramp = g_hash_table_lookup (rgctx_lazy_fetch_trampoline_hash, GUINT_TO_POINTER (offset));
4455 tramp = mono_arch_create_rgctx_lazy_fetch_trampoline (offset);
4456 ptr = mono_create_ftnptr (mono_get_root_domain (), tramp);
4459 if (!rgctx_lazy_fetch_trampoline_hash)
4460 rgctx_lazy_fetch_trampoline_hash = g_hash_table_new (NULL, NULL);
4461 g_hash_table_insert (rgctx_lazy_fetch_trampoline_hash, GUINT_TO_POINTER (offset), ptr);
4465 mono_counters_register ("RGCTX num lazy fetch trampolines",
4466 MONO_COUNTER_GENERICS | MONO_COUNTER_INT, &num_trampolines);
4475 * Generates rgc->other_infos [index].XXX if index is non-negative, or
4476 * rgc->extra_other_infos [-index + 1] if index is negative. XXX is
4477 * specified by rgctx_type;
4480 get_runtime_generic_context_other_table_ptr (MonoCompile *cfg, MonoBasicBlock *bblock,
4481 MonoInst *rgc_ptr, int slot, const unsigned char *ip)
4483 MonoMethodSignature *sig = helper_sig_rgctx_lazy_fetch_trampoline;
4484 guint8 *tramp = create_rgctx_lazy_fetch_trampoline (slot);
4488 temp = mono_emit_native_call (cfg, bblock, tramp, sig, &rgc_ptr, ip, FALSE, FALSE);
4490 NEW_TEMPLOAD (cfg, field, temp);
4496 get_runtime_generic_context_other_ptr (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *bblock,
4497 MonoInst *rgc_ptr, guint32 token, int token_source, int rgctx_type, unsigned char *ip, int index)
4503 g_assert (method->wrapper_type == MONO_WRAPPER_NONE);
4505 NEW_CLASSCONST (cfg, args [0], method->klass);
4507 NEW_ICONST (cfg, args [2], token);
4508 NEW_ICONST (cfg, args [3], token_source);
4509 NEW_ICONST (cfg, args [4], rgctx_type);
4510 NEW_ICONST (cfg, args [5], index);
4512 temp = mono_emit_jit_icall (cfg, bblock, mono_helper_get_rgctx_other_ptr, args, ip);
4513 NEW_TEMPLOAD (cfg, result, temp);
4519 get_runtime_generic_context_ptr (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *bblock,
4520 MonoClass *klass, guint32 type_token, int token_source, MonoGenericContext *generic_context, MonoInst *rgctx,
4521 int rgctx_type, unsigned char *ip)
4524 int relation = mono_class_generic_class_relation (klass, rgctx_type, method->klass, generic_context, &arg_num);
4527 case MINI_GENERIC_CLASS_RELATION_OTHER_TABLE:
4528 return get_runtime_generic_context_other_table_ptr (cfg, bblock, rgctx, arg_num, ip);
4529 case MINI_GENERIC_CLASS_RELATION_OTHER:
4530 return get_runtime_generic_context_other_ptr (cfg, method, bblock, rgctx,
4531 type_token, token_source, rgctx_type, ip, arg_num);
4533 g_assert_not_reached ();
4539 get_runtime_generic_context_method (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *bblock,
4540 MonoMethod *cmethod, MonoGenericContext *generic_context, MonoInst *rgctx, int rgctx_type, const unsigned char *ip)
4542 int arg_num = mono_class_lookup_or_register_other_info (method->klass, cmethod, rgctx_type, generic_context);
4544 return get_runtime_generic_context_other_table_ptr (cfg, bblock, rgctx, arg_num, ip);
4548 get_runtime_generic_context_field (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *bblock,
4549 MonoClassField *field, MonoGenericContext *generic_context, MonoInst *rgctx, int rgctx_type,
4550 const unsigned char *ip)
4552 int arg_num = mono_class_lookup_or_register_other_info (method->klass, field, rgctx_type, generic_context);
4554 return get_runtime_generic_context_other_table_ptr (cfg, bblock, rgctx, arg_num, ip);
4558 generic_class_is_reference_type (MonoCompile *cfg, MonoClass *klass)
4562 if (cfg->generic_sharing_context)
4563 type = mini_get_basic_type_from_generic (cfg->generic_sharing_context, &klass->byval_arg);
4565 type = &klass->byval_arg;
4566 return MONO_TYPE_IS_REFERENCE (type);
4570 * Handles unbox of a Nullable<T>, returning a temp variable where the
4571 * result is stored. If a rgctx is passed, then shared generic code
4575 handle_unbox_nullable (MonoCompile* cfg, MonoMethod *caller_method, MonoBasicBlock* bblock, MonoInst* val,
4576 guchar *ip, MonoClass* klass, MonoGenericContext *generic_context, MonoInst *rgctx)
4578 MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
4579 MonoMethodSignature *signature = mono_method_signature (method);
4582 MonoInst *addr = get_runtime_generic_context_method (cfg, caller_method, bblock, method,
4583 generic_context, rgctx, MONO_RGCTX_INFO_GENERIC_METHOD_CODE, ip);
4585 return mono_emit_rgctx_calli_spilled (cfg, bblock, signature, &val, addr, NULL, ip);
4587 return mono_emit_method_call_spilled (cfg, bblock, method, signature, &val, ip, NULL);
4592 handle_box_nullable_from_inst (MonoCompile *cfg, MonoMethod *caller_method, int context_used, MonoBasicBlock *bblock,
4593 MonoInst *val, const guchar *ip, MonoClass *klass, MonoGenericContext *generic_context, MonoInst *rgctx)
4595 MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
4596 MonoInst *dest, *method_addr;
4599 g_assert (mono_class_is_nullable (klass));
4601 method_addr = get_runtime_generic_context_method (cfg, caller_method, bblock, method,
4602 generic_context, rgctx, MONO_RGCTX_INFO_GENERIC_METHOD_CODE, ip);
4603 temp = mono_emit_rgctx_calli_spilled (cfg, bblock, mono_method_signature (method), &val,
4604 method_addr, NULL, ip);
4605 NEW_TEMPLOAD (cfg, dest, temp);
4610 mono_object_castclass (MonoObject *obj, MonoClass *klass)
4615 if (mono_object_isinst (obj, klass))
4618 mono_raise_exception (mono_exception_from_name (mono_defaults.corlib,
4619 "System", "InvalidCastException"));
4625 emit_castclass (MonoClass *klass, guint32 token, gboolean shared_access, gboolean inst_is_castclass, MonoCompile *cfg,
4626 MonoMethod *method, MonoInst **arg_array, MonoType **param_types, GList *dont_inline,
4627 unsigned char *end, MonoMethodHeader *header, MonoGenericContext *generic_context,
4628 MonoBasicBlock **_bblock, unsigned char **_ip, MonoInst ***_sp, int *_inline_costs, guint *_real_offset)
4630 MonoBasicBlock *bblock = *_bblock;
4631 unsigned char *ip = *_ip;
4632 MonoInst **sp = *_sp;
4633 int inline_costs = *_inline_costs;
4634 guint real_offset = *_real_offset;
4635 int return_value = 0;
4637 if (shared_access) {
4638 MonoInst *this = NULL, *rgctx;
4642 g_assert (!method->klass->valuetype);
4648 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
4649 NEW_ARGLOAD (cfg, this, 0);
4650 rgctx = get_runtime_generic_context (cfg, method, this, ip);
4651 args [1] = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
4652 token, MINI_TOKEN_SOURCE_CLASS, generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
4654 temp = mono_emit_jit_icall (cfg, bblock, mono_object_castclass, args, ip);
4655 NEW_TEMPLOAD (cfg, *sp, temp);
4660 } else if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
4662 MonoMethod *mono_castclass;
4663 MonoInst *iargs [1];
4664 MonoBasicBlock *ebblock;
4668 mono_castclass = mono_marshal_get_castclass (klass);
4671 costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), bblock,
4672 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
4674 g_assert (costs > 0);
4679 GET_BBLOCK (cfg, bblock, ip);
4680 ebblock->next_bb = bblock;
4681 link_bblock (cfg, ebblock, bblock);
4683 temp = iargs [0]->inst_i0->inst_c0;
4684 NEW_TEMPLOAD (cfg, *sp, temp);
4688 inline_costs += costs;
4692 /* Needed by the code generated in inssel.brg */
4693 mono_get_got_var (cfg);
4695 MONO_INST_NEW (cfg, ins, CEE_CASTCLASS);
4696 ins->type = STACK_OBJ;
4697 ins->inst_left = *sp;
4699 ins->inst_newa_class = klass;
4700 if (inst_is_castclass)
4701 ins->backend.record_cast_details = debug_options.better_cast_details;
4702 if (inst_is_castclass)
4703 *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
4713 *_inline_costs = inline_costs;
4714 *_real_offset = real_offset;
4715 return return_value;
4722 mini_assembly_can_skip_verification (MonoDomain *domain, MonoMethod *method)
4724 MonoAssembly *assembly = method->klass->image->assembly;
4725 if (method->wrapper_type != MONO_WRAPPER_NONE)
4727 if (assembly->in_gac || assembly->image == mono_defaults.corlib)
4729 if (mono_security_get_mode () != MONO_SECURITY_MODE_NONE)
4731 return mono_assembly_has_skip_verification (assembly);
4735 * mini_method_verify:
4737 * Verify the method using the new verfier.
4739 * Returns true if the method is invalid.
4742 mini_method_verify (MonoCompile *cfg, MonoMethod *method)
4745 gboolean is_fulltrust;
4746 MonoLoaderError *error;
4748 if (method->verification_success)
4751 is_fulltrust = mono_verifier_is_method_full_trust (method);
4753 if (!mono_verifier_is_enabled_for_method (method))
4756 res = mono_method_verify_with_current_settings (method, cfg->skip_visibility);
4758 if ((error = mono_loader_get_last_error ())) {
4759 cfg->exception_type = error->exception_type;
4761 mono_free_verify_list (res);
4766 for (tmp = res; tmp; tmp = tmp->next) {
4767 MonoVerifyInfoExtended *info = (MonoVerifyInfoExtended *)tmp->data;
4768 if (info->info.status == MONO_VERIFY_ERROR) {
4769 cfg->exception_type = info->exception_type;
4770 cfg->exception_message = g_strdup (info->info.message);
4771 mono_free_verify_list (res);
4774 if (info->info.status == MONO_VERIFY_NOT_VERIFIABLE && !is_fulltrust) {
4775 cfg->exception_type = info->exception_type;
4776 cfg->exception_message = g_strdup (info->info.message);
4777 mono_free_verify_list (res);
4781 mono_free_verify_list (res);
4783 method->verification_success = 1;
4788 * mono_method_to_ir: translates IL into basic blocks containing trees
4791 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock,
4792 int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args,
4793 guint inline_offset, gboolean is_virtual_call)
4795 MonoInst *zero_int32, *zero_int64, *zero_ptr, *zero_obj, *zero_r8;
4796 MonoInst *ins, **sp, **stack_start;
4797 MonoBasicBlock *bblock, *tblock = NULL, *init_localsbb = NULL;
4798 MonoMethod *cmethod, *method_definition;
4799 MonoInst **arg_array;
4800 MonoMethodHeader *header;
4802 guint32 token, ins_flag;
4804 MonoClass *constrained_call = NULL;
4805 unsigned char *ip, *end, *target, *err_pos;
4806 static double r8_0 = 0.0;
4807 MonoMethodSignature *sig;
4808 MonoGenericContext *generic_context = NULL;
4809 MonoGenericContainer *generic_container = NULL;
4810 MonoType **param_types;
4811 GList *bb_recheck = NULL, *tmp;
4812 int i, n, start_new_bblock, ialign;
4813 int num_calls = 0, inline_costs = 0;
4814 int breakpoint_id = 0;
4816 guint real_offset, num_args;
4817 MonoBoolean security, pinvoke;
4818 MonoSecurityManager* secman = NULL;
4819 MonoDeclSecurityActions actions;
4820 GSList *class_inits = NULL;
4821 gboolean dont_verify, dont_verify_stloc, readonly = FALSE;
4823 /* serialization and xdomain stuff may need access to private fields and methods */
4824 dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
4825 dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
4826 dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
4827 dont_verify |= method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE; /* bug #77896 */
4828 dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP;
4829 dont_verify |= method->wrapper_type == MONO_WRAPPER_COMINTEROP_INVOKE;
4831 /* turn off visibility checks for smcs */
4832 dont_verify |= mono_security_get_mode () == MONO_SECURITY_MODE_SMCS_HACK;
4834 /* still some type unsafety issues in marshal wrappers... (unknown is PtrToStructure) */
4835 dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
4836 dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
4837 dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
4839 image = method->klass->image;
4840 header = mono_method_get_header (method);
4841 generic_container = mono_method_get_generic_container (method);
4842 sig = mono_method_signature (method);
4843 num_args = sig->hasthis + sig->param_count;
4844 ip = (unsigned char*)header->code;
4845 cfg->cil_start = ip;
4846 end = ip + header->code_size;
4847 mono_jit_stats.cil_code_size += header->code_size;
4849 method_definition = method;
4850 while (method_definition->is_inflated) {
4851 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
4852 method_definition = imethod->declaring;
4855 /* SkipVerification is not allowed if core-clr is enabled */
4856 if (!dont_verify && mini_assembly_can_skip_verification (cfg->domain, method)) {
4858 dont_verify_stloc = TRUE;
4861 if (!dont_verify && mini_method_verify (cfg, method_definition))
4862 goto exception_exit;
4864 if (sig->is_inflated)
4865 generic_context = mono_method_get_context (method);
4866 else if (generic_container)
4867 generic_context = &generic_container->context;
4869 if (!cfg->generic_sharing_context)
4870 g_assert (!sig->has_type_parameters);
4872 if (cfg->method == method)
4875 real_offset = inline_offset;
4877 cfg->cil_offset_to_bb = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoBasicBlock*) * header->code_size);
4878 cfg->cil_offset_to_bb_len = header->code_size;
4880 if (cfg->verbose_level > 2)
4881 g_print ("method to IR %s\n", mono_method_full_name (method, TRUE));
4883 dont_inline = g_list_prepend (dont_inline, method);
4884 if (cfg->method == method) {
4886 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
4887 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
4890 NEW_BBLOCK (cfg, start_bblock);
4891 cfg->bb_entry = start_bblock;
4892 start_bblock->cil_code = NULL;
4893 start_bblock->cil_length = 0;
4894 start_bblock->block_num = cfg->num_bblocks++;
4897 NEW_BBLOCK (cfg, end_bblock);
4898 cfg->bb_exit = end_bblock;
4899 end_bblock->cil_code = NULL;
4900 end_bblock->cil_length = 0;
4901 end_bblock->block_num = cfg->num_bblocks++;
4902 g_assert (cfg->num_bblocks == 2);
4904 arg_array = alloca (sizeof (MonoInst *) * num_args);
4905 for (i = num_args - 1; i >= 0; i--)
4906 arg_array [i] = cfg->varinfo [i];
4908 if (header->num_clauses) {
4909 cfg->spvars = g_hash_table_new (NULL, NULL);
4910 cfg->exvars = g_hash_table_new (NULL, NULL);
4912 /* handle exception clauses */
4913 for (i = 0; i < header->num_clauses; ++i) {
4914 MonoBasicBlock *try_bb;
4915 MonoExceptionClause *clause = &header->clauses [i];
4917 GET_BBLOCK (cfg, try_bb, ip + clause->try_offset);
4918 try_bb->real_offset = clause->try_offset;
4919 GET_BBLOCK (cfg, tblock, ip + clause->handler_offset);
4920 tblock->real_offset = clause->handler_offset;
4921 tblock->flags |= BB_EXCEPTION_HANDLER;
4923 link_bblock (cfg, try_bb, tblock);
4925 if (*(ip + clause->handler_offset) == CEE_POP)
4926 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
4928 if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
4929 clause->flags == MONO_EXCEPTION_CLAUSE_FILTER ||
4930 clause->flags == MONO_EXCEPTION_CLAUSE_FAULT) {
4931 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
4932 MONO_ADD_INS (tblock, ins);
4934 /* todo: is a fault block unsafe to optimize? */
4935 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
4936 tblock->flags |= BB_EXCEPTION_UNSAFE;
4940 /*g_print ("clause try IL_%04x to IL_%04x handler %d at IL_%04x to IL_%04x\n", clause->try_offset, clause->try_offset + clause->try_len, clause->flags, clause->handler_offset, clause->handler_offset + clause->handler_len);
4942 g_print ("%s", mono_disasm_code_one (NULL, method, p, &p));
4944 /* catch and filter blocks get the exception object on the stack */
4945 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
4946 clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4947 MonoInst *load, *dummy_use;
4949 /* mostly like handle_stack_args (), but just sets the input args */
4950 /* g_print ("handling clause at IL_%04x\n", clause->handler_offset); */
4951 tblock->in_scount = 1;
4952 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
4953 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
4956 * Add a dummy use for the exvar so its liveness info will be
4959 NEW_TEMPLOAD (cfg, load, tblock->in_stack [0]->inst_c0);
4960 NEW_DUMMY_USE (cfg, dummy_use, load);
4961 MONO_ADD_INS (tblock, dummy_use);
4963 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
4964 GET_BBLOCK (cfg, tblock, ip + clause->data.filter_offset);
4965 tblock->real_offset = clause->data.filter_offset;
4966 tblock->in_scount = 1;
4967 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
4968 /* The filter block shares the exvar with the handler block */
4969 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
4970 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
4971 MONO_ADD_INS (tblock, ins);
4975 if (clause->flags != MONO_EXCEPTION_CLAUSE_FILTER &&
4976 clause->data.catch_class &&
4977 cfg->generic_sharing_context &&
4978 mono_class_check_context_used (clause->data.catch_class)) {
4980 * In shared generic code with catch
4981 * clauses containing type variables
4982 * the exception handling code has to
4983 * be able to get to the rgctx.
4984 * Therefore we have to make sure that
4985 * the rgctx argument (for static
4986 * methods) or the "this" argument
4987 * (for non-static methods) are live.
4989 if (method->flags & METHOD_ATTRIBUTE_STATIC) {
4990 mono_get_vtable_var (cfg);
4992 MonoInst *this, *dummy_use;
4993 MonoType *this_type;
4995 if (method->klass->valuetype)
4996 this_type = &method->klass->this_arg;
4998 this_type = &method->klass->byval_arg;
5000 if (arg_array [0]->opcode == OP_ICONST) {
5001 this = arg_array [0];
5003 this = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst));
5004 this->ssa_op = MONO_SSA_LOAD;
5005 this->inst_i0 = arg_array [0];
5006 this->opcode = mini_type_to_ldind ((cfg), this->inst_i0->inst_vtype);
5007 type_to_eval_stack_type ((cfg), this_type, this);
5008 this->klass = this->inst_i0->klass;
5011 NEW_DUMMY_USE (cfg, dummy_use, this);
5012 MONO_ADD_INS (tblock, dummy_use);
5017 arg_array = alloca (sizeof (MonoInst *) * num_args);
5018 mono_save_args (cfg, start_bblock, sig, inline_args, arg_array);
5021 /* FIRST CODE BLOCK */
5022 NEW_BBLOCK (cfg, bblock);
5023 bblock->cil_code = ip;
5025 ADD_BBLOCK (cfg, bblock);
5027 if (cfg->method == method) {
5028 breakpoint_id = mono_debugger_method_has_breakpoint (method);
5029 if (breakpoint_id && (mono_debug_format != MONO_DEBUG_FORMAT_DEBUGGER)) {
5030 MONO_INST_NEW (cfg, ins, OP_BREAK);
5031 MONO_ADD_INS (bblock, ins);
5035 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS)
5036 secman = mono_security_manager_get_methods ();
5038 security = (secman && mono_method_has_declsec (method));
5039 /* at this point having security doesn't mean we have any code to generate */
5040 if (security && (cfg->method == method)) {
5041 /* Only Demand, NonCasDemand and DemandChoice requires code generation.
5042 * And we do not want to enter the next section (with allocation) if we
5043 * have nothing to generate */
5044 security = mono_declsec_get_demands (method, &actions);
5047 /* we must Demand SecurityPermission.Unmanaged before P/Invoking */
5048 pinvoke = (secman && (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE));
5050 MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
5051 if (wrapped && (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5052 MonoCustomAttrInfo* custom = mono_custom_attrs_from_method (wrapped);
5054 /* unless the method or it's class has the [SuppressUnmanagedCodeSecurity] attribute */
5055 if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
5059 mono_custom_attrs_free (custom);
5062 custom = mono_custom_attrs_from_class (wrapped->klass);
5063 if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
5067 mono_custom_attrs_free (custom);
5070 /* not a P/Invoke after all */
5075 if ((header->init_locals || (cfg->method == method && (cfg->opt & MONO_OPT_SHARED))) || cfg->compile_aot || security || pinvoke) {
5076 /* we use a separate basic block for the initialization code */
5077 NEW_BBLOCK (cfg, init_localsbb);
5078 cfg->bb_init = init_localsbb;
5079 init_localsbb->real_offset = real_offset;
5080 start_bblock->next_bb = init_localsbb;
5081 init_localsbb->next_bb = bblock;
5082 link_bblock (cfg, start_bblock, init_localsbb);
5083 link_bblock (cfg, init_localsbb, bblock);
5084 init_localsbb->block_num = cfg->num_bblocks++;
5086 start_bblock->next_bb = bblock;
5087 link_bblock (cfg, start_bblock, bblock);
5090 /* at this point we know, if security is TRUE, that some code needs to be generated */
5091 if (security && (cfg->method == method)) {
5094 mono_jit_stats.cas_demand_generation++;
5096 if (actions.demand.blob) {
5097 /* Add code for SecurityAction.Demand */
5098 NEW_DECLSECCONST (cfg, args[0], image, actions.demand);
5099 NEW_ICONST (cfg, args [1], actions.demand.size);
5100 /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
5101 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
5103 if (actions.noncasdemand.blob) {
5104 /* CLR 1.x uses a .noncasdemand (but 2.x doesn't) */
5105 /* For Mono we re-route non-CAS Demand to Demand (as the managed code must deal with it anyway) */
5106 NEW_DECLSECCONST (cfg, args[0], image, actions.noncasdemand);
5107 NEW_ICONST (cfg, args [1], actions.noncasdemand.size);
5108 /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
5109 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
5111 if (actions.demandchoice.blob) {
5112 /* New in 2.0, Demand must succeed for one of the permissions (i.e. not all) */
5113 NEW_DECLSECCONST (cfg, args[0], image, actions.demandchoice);
5114 NEW_ICONST (cfg, args [1], actions.demandchoice.size);
5115 /* Calls static void SecurityManager.InternalDemandChoice (byte* permissions, int size); */
5116 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandchoice, mono_method_signature (secman->demandchoice), args, ip, NULL);
5120 /* we must Demand SecurityPermission.Unmanaged before p/invoking */
5122 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandunmanaged, mono_method_signature (secman->demandunmanaged), NULL, ip, NULL);
5125 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
5126 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
5127 MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
5128 if (wrapped && (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5129 if (!(method->klass && method->klass->image &&
5130 mono_security_core_clr_is_platform_image (method->klass->image))) {
5131 emit_throw_method_access_exception (cfg, method, wrapped, bblock, ip);
5135 if (!method_is_safe (method))
5136 emit_throw_verification_exception (cfg, bblock, ip);
5139 if (header->code_size == 0)
5142 if (get_basic_blocks (cfg, header, real_offset, ip, end, &err_pos)) {
5147 if (cfg->method == method)
5148 mono_debug_init_method (cfg, bblock, breakpoint_id);
5150 param_types = mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
5152 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
5153 for (n = 0; n < sig->param_count; ++n)
5154 param_types [n + sig->hasthis] = sig->params [n];
5155 for (n = 0; n < header->num_locals; ++n) {
5156 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
5161 /* do this somewhere outside - not here */
5162 NEW_ICONST (cfg, zero_int32, 0);
5163 NEW_ICONST (cfg, zero_int64, 0);
5164 zero_int64->type = STACK_I8;
5165 NEW_PCONST (cfg, zero_ptr, 0);
5166 NEW_PCONST (cfg, zero_obj, 0);
5167 zero_obj->type = STACK_OBJ;
5169 MONO_INST_NEW (cfg, zero_r8, OP_R8CONST);
5170 zero_r8->type = STACK_R8;
5171 zero_r8->inst_p0 = &r8_0;
5173 /* add a check for this != NULL to inlined methods */
5174 if (is_virtual_call) {
5175 MONO_INST_NEW (cfg, ins, OP_CHECK_THIS);
5176 NEW_ARGLOAD (cfg, ins->inst_left, 0);
5178 MONO_ADD_INS (bblock, ins);
5181 /* we use a spare stack slot in SWITCH and NEWOBJ and others */
5182 stack_start = sp = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
5185 start_new_bblock = 0;
5188 if (cfg->method == method)
5189 real_offset = ip - header->code;
5191 real_offset = inline_offset;
5194 if (start_new_bblock) {
5195 bblock->cil_length = ip - bblock->cil_code;
5196 if (start_new_bblock == 2) {
5197 g_assert (ip == tblock->cil_code);
5199 GET_BBLOCK (cfg, tblock, ip);
5201 bblock->next_bb = tblock;
5203 start_new_bblock = 0;
5204 for (i = 0; i < bblock->in_scount; ++i) {
5205 if (cfg->verbose_level > 3)
5206 g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);
5207 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
5210 g_slist_free (class_inits);
5213 if ((tblock = cfg->cil_offset_to_bb [ip - cfg->cil_start]) && (tblock != bblock)) {
5214 link_bblock (cfg, bblock, tblock);
5215 if (sp != stack_start) {
5216 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5218 CHECK_UNVERIFIABLE (cfg);
5220 bblock->next_bb = tblock;
5222 for (i = 0; i < bblock->in_scount; ++i) {
5223 if (cfg->verbose_level > 3)
5224 g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);
5225 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
5228 g_slist_free (class_inits);
5233 bblock->real_offset = real_offset;
5235 if ((cfg->method == method) && cfg->coverage_info) {
5236 MonoInst *store, *one;
5237 guint32 cil_offset = ip - header->code;
5238 cfg->coverage_info->data [cil_offset].cil_code = ip;
5240 /* TODO: Use an increment here */
5241 NEW_ICONST (cfg, one, 1);
5244 NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
5247 MONO_INST_NEW (cfg, store, CEE_STIND_I);
5248 store->inst_left = ins;
5249 store->inst_right = one;
5251 MONO_ADD_INS (bblock, store);
5254 if (cfg->verbose_level > 3)
5255 g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
5259 MONO_INST_NEW (cfg, ins, OP_NOP);
5261 MONO_ADD_INS (bblock, ins);
5264 MONO_INST_NEW (cfg, ins, OP_BREAK);
5266 MONO_ADD_INS (bblock, ins);
5272 CHECK_STACK_OVF (1);
5273 n = (*ip)-CEE_LDARG_0;
5275 NEW_ARGLOAD (cfg, ins, n);
5276 LDARG_SOFT_FLOAT (cfg, ins, n, ip);
5284 CHECK_STACK_OVF (1);
5285 n = (*ip)-CEE_LDLOC_0;
5287 NEW_LOCLOAD (cfg, ins, n);
5288 LDLOC_SOFT_FLOAT (cfg, ins, n, ip);
5297 n = (*ip)-CEE_STLOC_0;
5300 handle_loaded_temps (cfg, bblock, stack_start, sp);
5301 NEW_LOCSTORE (cfg, ins, n, *sp);
5302 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
5304 STLOC_SOFT_FLOAT (cfg, ins, n, ip);
5305 if (ins->opcode == CEE_STOBJ) {
5306 NEW_LOCLOADA (cfg, ins, n);
5307 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5309 MONO_ADD_INS (bblock, ins);
5315 CHECK_STACK_OVF (1);
5317 NEW_ARGLOAD (cfg, ins, ip [1]);
5318 LDARG_SOFT_FLOAT (cfg, ins, ip [1], ip);
5324 CHECK_STACK_OVF (1);
5326 NEW_ARGLOADA (cfg, ins, ip [1]);
5335 NEW_ARGSTORE (cfg, ins, ip [1], *sp);
5336 handle_loaded_temps (cfg, bblock, stack_start, sp);
5337 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
5339 STARG_SOFT_FLOAT (cfg, ins, ip [1], ip);
5340 if (ins->opcode == CEE_STOBJ) {
5341 NEW_ARGLOADA (cfg, ins, ip [1]);
5342 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5344 MONO_ADD_INS (bblock, ins);
5349 CHECK_STACK_OVF (1);
5350 CHECK_LOCAL (ip [1]);
5351 NEW_LOCLOAD (cfg, ins, ip [1]);
5352 LDLOC_SOFT_FLOAT (cfg, ins, ip [1], ip);
5358 CHECK_STACK_OVF (1);
5359 CHECK_LOCAL (ip [1]);
5360 NEW_LOCLOADA (cfg, ins, ip [1]);
5368 handle_loaded_temps (cfg, bblock, stack_start, sp);
5369 CHECK_LOCAL (ip [1]);
5370 NEW_LOCSTORE (cfg, ins, ip [1], *sp);
5371 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
5373 STLOC_SOFT_FLOAT (cfg, ins, ip [1], ip);
5374 if (ins->opcode == CEE_STOBJ) {
5375 NEW_LOCLOADA (cfg, ins, ip [1]);
5376 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
5378 MONO_ADD_INS (bblock, ins);
5383 CHECK_STACK_OVF (1);
5384 NEW_PCONST (cfg, ins, NULL);
5385 ins->type = STACK_OBJ;
5390 CHECK_STACK_OVF (1);
5391 NEW_ICONST (cfg, ins, -1);
5404 CHECK_STACK_OVF (1);
5405 NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
5411 CHECK_STACK_OVF (1);
5413 NEW_ICONST (cfg, ins, *((signed char*)ip));
5419 CHECK_STACK_OVF (1);
5420 NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
5426 CHECK_STACK_OVF (1);
5427 MONO_INST_NEW (cfg, ins, OP_I8CONST);
5428 ins->type = STACK_I8;
5430 ins->inst_l = (gint64)read64 (ip);
5436 /* we should really allocate this only late in the compilation process */
5437 mono_domain_lock (cfg->domain);
5438 f = mono_mempool_alloc (cfg->domain->mp, sizeof (float));
5439 mono_domain_unlock (cfg->domain);
5441 CHECK_STACK_OVF (1);
5442 MONO_INST_NEW (cfg, ins, OP_R4CONST);
5443 ins->type = STACK_R8;
5454 mono_domain_lock (cfg->domain);
5455 d = mono_mempool_alloc (cfg->domain->mp, sizeof (double));
5456 mono_domain_unlock (cfg->domain);
5458 CHECK_STACK_OVF (1);
5459 MONO_INST_NEW (cfg, ins, OP_R8CONST);
5460 ins->type = STACK_R8;
5470 MonoInst *temp, *store;
5472 CHECK_STACK_OVF (1);
5477 * small optimization: if the loaded value was from a local already,
5478 * just load it twice.
5480 if (ins->ssa_op == MONO_SSA_LOAD &&
5481 (ins->inst_i0->opcode == OP_LOCAL || ins->inst_i0->opcode == OP_ARG)) {
5483 MONO_INST_NEW (cfg, temp, 0);
5487 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
5488 temp->flags |= MONO_INST_IS_TEMP;
5489 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
5490 /* FIXME: handle CEE_STIND_R4 */
5491 if (store->opcode == CEE_STOBJ) {
5492 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
5493 handle_stobj (cfg, bblock, store, sp [0], sp [0]->cil_code, store->klass, TRUE, FALSE, FALSE);
5495 MONO_ADD_INS (bblock, store);
5497 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
5499 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
5508 MONO_INST_NEW (cfg, ins, CEE_POP);
5509 MONO_ADD_INS (bblock, ins);
5516 if (stack_start != sp)
5518 MONO_INST_NEW (cfg, ins, OP_JMP);
5519 token = read32 (ip + 1);
5520 /* FIXME: check the signature matches */
5521 cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
5526 if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
5527 GENERIC_SHARING_FAILURE (CEE_JMP);
5529 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
5530 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
5532 CHECK_CFG_EXCEPTION;
5535 ins->inst_p0 = cmethod;
5536 MONO_ADD_INS (bblock, ins);
5538 start_new_bblock = 1;
5542 case CEE_CALLVIRT: {
5543 MonoInst *addr = NULL;
5544 MonoMethodSignature *fsig = NULL;
5545 int temp, array_rank = 0;
5546 int virtual = *ip == CEE_CALLVIRT;
5548 int context_used = 0;
5549 gboolean pass_vtable = FALSE;
5550 MonoInst *vtable_arg = NULL;
5553 token = read32 (ip + 1);
5555 if (*ip == CEE_CALLI) {
5560 if (method->wrapper_type != MONO_WRAPPER_NONE)
5561 fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
5563 fsig = mono_metadata_parse_signature (image, token);
5565 n = fsig->param_count + fsig->hasthis;
5567 MonoMethod *cil_method;
5569 if (method->wrapper_type != MONO_WRAPPER_NONE) {
5570 cmethod = (MonoMethod *)mono_method_get_wrapper_data (method, token);
5571 cil_method = cmethod;
5572 } else if (constrained_call) {
5573 cmethod = mono_get_method_constrained (image, token, constrained_call, generic_context, &cil_method);
5574 cil_method = cmethod;
5576 cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
5577 cil_method = cmethod;
5582 if (!dont_verify && !cfg->skip_visibility) {
5583 MonoMethod *target_method = cil_method;
5584 if (method->is_inflated) {
5585 target_method = mini_get_method_allow_open (method, token, NULL, &(mono_method_get_generic_container (method_definition)->context));
5587 if (!mono_method_can_access_method (method_definition, target_method) &&
5588 !mono_method_can_access_method (method, cil_method))
5589 METHOD_ACCESS_FAILURE;
5592 if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR)
5593 ensure_method_is_allowed_to_call_method (cfg, method, cil_method, bblock, ip);
5595 if (!virtual && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
5596 /* MS.NET seems to silently convert this to a callvirt */
5599 if (!cmethod->klass->inited){
5600 if (!mono_class_init (cmethod->klass))
5604 if (mono_method_signature (cmethod)->pinvoke) {
5605 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod, check_for_pending_exc);
5606 fsig = mono_method_signature (wrapper);
5607 } else if (constrained_call) {
5608 fsig = mono_method_signature (cmethod);
5610 fsig = mono_method_get_signature_full (cmethod, image, token, generic_context);
5613 mono_save_token_info (cfg, image, token, cmethod);
5615 n = fsig->param_count + fsig->hasthis;
5617 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
5618 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
5620 CHECK_CFG_EXCEPTION;
5623 if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
5624 mini_class_is_system_array (cmethod->klass)) {
5625 array_rank = cmethod->klass->rank;
5628 if (cmethod->string_ctor)
5629 g_assert_not_reached ();
5633 if (!cfg->generic_sharing_context && cmethod && cmethod->klass->generic_container)
5638 //g_assert (!virtual || fsig->hasthis);
5642 if (constrained_call) {
5644 * We have the `constrained.' prefix opcode.
5646 if (constrained_call->valuetype && !cmethod->klass->valuetype) {
5649 * The type parameter is instantiated as a valuetype,
5650 * but that type doesn't override the method we're
5651 * calling, so we need to box `this'.
5652 * sp [0] is a pointer to the data: we need the value
5653 * in handle_box (), so load it here.
5655 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, &constrained_call->byval_arg));
5656 type_to_eval_stack_type (cfg, &constrained_call->byval_arg, load);
5657 load->inst_left = sp [0];
5658 sp [0] = handle_box (cfg, bblock, load, ip, constrained_call);
5659 } else if (!constrained_call->valuetype) {
5663 * The type parameter is instantiated as a reference
5664 * type. We have a managed pointer on the stack, so
5665 * we need to dereference it here.
5668 MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
5669 ins->inst_i0 = sp [0];
5670 ins->type = STACK_OBJ;
5671 ins->klass = mono_class_from_mono_type (&constrained_call->byval_arg);
5673 } else if (cmethod->klass->valuetype)
5675 constrained_call = NULL;
5678 if (*ip != CEE_CALLI && check_call_signature (cfg, fsig, sp))
5681 if (cmethod && (cmethod->flags & METHOD_ATTRIBUTE_STATIC) &&
5682 (cmethod->klass->generic_class || cmethod->klass->generic_container)) {
5683 gboolean sharing_enabled = mono_class_generic_sharing_enabled (cmethod->klass);
5684 MonoGenericContext *context = mini_class_get_context (cmethod->klass);
5685 gboolean context_sharable = mono_generic_context_is_sharable (context, TRUE);
5688 * Pass vtable iff target method might
5689 * be shared, which means that sharing
5690 * is enabled for its class and its
5691 * context is sharable (and it's not a
5694 if (sharing_enabled && context_sharable &&
5695 !mini_method_get_context (cmethod)->method_inst)
5699 if (cfg->generic_sharing_context && cmethod) {
5700 MonoGenericContext *cmethod_context = mono_method_get_context (cmethod);
5702 context_used = mono_method_check_context_used (cmethod);
5704 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD)
5705 GENERIC_SHARING_FAILURE (*ip);
5708 ((cmethod->klass->flags & TYPE_ATTRIBUTE_INTERFACE) ||
5709 (cmethod_context && cmethod_context->method_inst && cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))) {
5710 GENERIC_SHARING_FAILURE (*ip);
5719 vtable_arg = get_runtime_generic_context_ptr (cfg, method, bblock, cmethod->klass,
5720 token, MINI_TOKEN_SOURCE_METHOD, generic_context,
5721 rgctx, MONO_RGCTX_INFO_VTABLE, ip);
5723 MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
5725 CHECK_TYPELOAD (cmethod->klass);
5726 NEW_VTABLECONST (cfg, vtable_arg, vtable);
5730 if (cmethod && virtual &&
5731 (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) &&
5732 !((cmethod->flags & METHOD_ATTRIBUTE_FINAL) &&
5733 cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
5734 mono_method_signature (cmethod)->generic_param_count) {
5735 MonoInst *this_temp, *this_arg_temp, *store;
5736 MonoInst *iargs [4];
5738 g_assert (mono_method_signature (cmethod)->is_inflated);
5739 /* Prevent inlining of methods that contain indirect calls */
5742 this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
5743 NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
5744 MONO_ADD_INS (bblock, store);
5746 /* FIXME: This should be a managed pointer */
5747 this_arg_temp = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
5749 /* Because of the PCONST below */
5750 cfg->disable_aot = TRUE;
5751 NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
5752 NEW_METHODCONST (cfg, iargs [1], cmethod);
5753 NEW_PCONST (cfg, iargs [2], mono_method_get_context (cmethod));
5754 NEW_TEMPLOADA (cfg, iargs [3], this_arg_temp->inst_c0);
5755 temp = mono_emit_jit_icall (cfg, bblock, mono_helper_compile_generic_method, iargs, ip);
5757 NEW_TEMPLOAD (cfg, addr, temp);
5758 NEW_TEMPLOAD (cfg, sp [0], this_arg_temp->inst_c0);
5760 if ((temp = mono_emit_calli_spilled (cfg, bblock, fsig, sp, addr, ip)) != -1) {
5761 NEW_TEMPLOAD (cfg, *sp, temp);
5770 /* FIXME: runtime generic context pointer for jumps? */
5771 if ((ins_flag & MONO_INST_TAILCALL) && !cfg->generic_sharing_context && !vtable_arg && cmethod && (*ip == CEE_CALL) &&
5772 (mono_metadata_signature_equal (mono_method_signature (method), mono_method_signature (cmethod)))) {
5775 GENERIC_SHARING_FAILURE (*ip);
5777 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
5779 /* FIXME: This assumes the two methods has the same number and type of arguments */
5781 * We implement tail calls by storing the actual arguments into the
5782 * argument variables, then emitting a OP_JMP. Since the actual arguments
5783 * can refer to the arg variables, we have to spill them.
5785 handle_loaded_temps (cfg, bblock, sp, sp + n);
5786 for (i = 0; i < n; ++i) {
5787 /* Prevent argument from being register allocated */
5788 arg_array [i]->flags |= MONO_INST_VOLATILE;
5790 /* Check if argument is the same */
5792 * FIXME: This loses liveness info, so it can only be done if the
5793 * argument is not register allocated.
5795 NEW_ARGLOAD (cfg, ins, i);
5796 if ((ins->opcode == sp [i]->opcode) && (ins->inst_i0 == sp [i]->inst_i0))
5799 NEW_ARGSTORE (cfg, ins, i, sp [i]);
5800 /* FIXME: handle CEE_STIND_R4 */
5801 if (ins->opcode == CEE_STOBJ) {
5802 NEW_ARGLOADA (cfg, ins, i);
5803 handle_stobj (cfg, bblock, ins, sp [i], sp [i]->cil_code, ins->klass, FALSE, FALSE, FALSE);
5806 MONO_ADD_INS (bblock, ins);
5808 MONO_INST_NEW (cfg, ins, OP_JMP);
5809 ins->inst_p0 = cmethod;
5810 ins->inst_p1 = arg_array [0];
5811 MONO_ADD_INS (bblock, ins);
5812 link_bblock (cfg, bblock, end_bblock);
5813 start_new_bblock = 1;
5814 /* skip CEE_RET as well */
5819 if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_get_inst_for_method (cfg, cmethod, fsig, sp))) {
5820 if (MONO_TYPE_IS_VOID (fsig->ret)) {
5821 MONO_ADD_INS (bblock, ins);
5823 type_to_eval_stack_type (cfg, fsig->ret, ins);
5833 handle_loaded_temps (cfg, bblock, stack_start, sp);
5835 if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
5836 (!virtual || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || (cmethod->flags & METHOD_ATTRIBUTE_FINAL)) &&
5837 mono_method_check_inlining (cfg, cmethod) &&
5838 !g_list_find (dont_inline, cmethod)) {
5840 MonoBasicBlock *ebblock;
5841 gboolean allways = FALSE;
5843 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
5844 (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
5845 /* Prevent inlining of methods that call wrappers */
5847 cmethod = mono_marshal_get_native_wrapper (cmethod, check_for_pending_exc);
5851 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, allways))) {
5855 GET_BBLOCK (cfg, bblock, ip);
5856 ebblock->next_bb = bblock;
5857 link_bblock (cfg, ebblock, bblock);
5859 if (!MONO_TYPE_IS_VOID (fsig->ret))
5862 /* indicates start of a new block, and triggers a load of all
5863 stack arguments at bb boundarie */
5866 inline_costs += costs;
5872 inline_costs += 10 * num_calls++;
5874 /* tail recursion elimination */
5875 if ((cfg->opt & MONO_OPT_TAILC) && *ip == CEE_CALL && cmethod == method && ip [5] == CEE_RET &&
5877 gboolean has_vtargs = FALSE;
5880 /* Prevent inlining of methods with tail calls (the call stack would be altered) */
5882 /* keep it simple */
5883 for (i = fsig->param_count - 1; i >= 0; i--) {
5884 if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i]))
5889 for (i = 0; i < n; ++i) {
5890 /* FIXME: handle CEE_STIND_R4 */
5891 NEW_ARGSTORE (cfg, ins, i, sp [i]);
5892 MONO_ADD_INS (bblock, ins);
5894 MONO_INST_NEW (cfg, ins, OP_BR);
5895 MONO_ADD_INS (bblock, ins);
5896 tblock = start_bblock->out_bb [0];
5897 link_bblock (cfg, bblock, tblock);
5898 ins->inst_target_bb = tblock;
5899 start_new_bblock = 1;
5901 /* skip the CEE_RET, too */
5902 if (ip_in_bb (cfg, bblock, ip + 5))
5911 if (ip_in_bb (cfg, bblock, ip + 5)
5912 && (!MONO_TYPE_ISSTRUCT (fsig->ret))
5913 && (!MONO_TYPE_IS_VOID (fsig->ret) || (cmethod && cmethod->string_ctor))
5914 && (CODE_IS_STLOC (ip + 5) || ip [5] == CEE_POP || ip [5] == CEE_RET))
5915 /* No need to spill */
5921 (cmethod->klass->valuetype ||
5922 (cmethod->is_inflated && mono_method_get_context (cmethod)->method_inst) ||
5923 ((cmethod->flags & METHOD_ATTRIBUTE_STATIC) &&
5924 mono_class_generic_sharing_enabled (cmethod->klass)) ||
5925 (!mono_method_is_generic_sharable_impl (cmethod) &&
5926 (!virtual || cmethod->flags & METHOD_ATTRIBUTE_FINAL ||
5927 !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL))))) {
5928 MonoInst *this = NULL, *rgctx;
5932 g_assert (cfg->generic_sharing_context && cmethod);
5933 g_assert (addr == NULL);
5936 * We are compiling a call to a
5937 * generic method from shared code,
5938 * which means that we have to look up
5939 * the method in the rgctx and do an
5943 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
5945 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
5946 NEW_ARGLOAD (cfg, this, 0);
5947 rgctx = get_runtime_generic_context (cfg, method, this, ip);
5948 addr = get_runtime_generic_context_method (cfg, method, bblock, cmethod,
5949 generic_context, rgctx, MONO_RGCTX_INFO_GENERIC_METHOD_CODE, ip);
5953 if (*ip == CEE_CALL) {
5954 g_assert (context_used);
5955 } else if (*ip == CEE_CALLI) {
5956 g_assert (!vtable_arg);
5958 g_assert (cmethod->flags & METHOD_ATTRIBUTE_FINAL ||
5959 !(cmethod->flags & METHOD_ATTRIBUTE_FINAL));
5962 /* Prevent inlining of methods with indirect calls */
5965 ins = (MonoInst*)mono_emit_rgctx_calli (cfg, bblock, fsig, sp, addr, vtable_arg, ip);
5968 temp = mono_emit_rgctx_calli_spilled (cfg, bblock, fsig, sp, addr, vtable_arg, ip);
5970 NEW_TEMPLOAD (cfg, *sp, temp);
5974 } else if (array_rank) {
5977 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */
5978 if (sp [fsig->param_count]->type == STACK_OBJ) {
5979 MonoInst *iargs [2];
5980 MonoInst *array, *to_store, *store;
5982 handle_loaded_temps (cfg, bblock, stack_start, sp);
5984 array = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
5985 NEW_TEMPSTORE (cfg, store, array->inst_c0, sp [0]);
5986 MONO_ADD_INS (bblock, store);
5987 NEW_TEMPLOAD (cfg, iargs [0], array->inst_c0);
5989 to_store = mono_compile_create_var (cfg, type_from_stack_type (sp [fsig->param_count]), OP_LOCAL);
5990 NEW_TEMPSTORE (cfg, store, to_store->inst_c0, sp [fsig->param_count]);
5991 /* FIXME: handle CEE_STIND_R4 */
5992 MONO_ADD_INS (bblock, store);
5993 NEW_TEMPLOAD (cfg, iargs [1], to_store->inst_c0);
5996 * We first save the args for the call so that the args are copied to the stack
5997 * and a new instruction tree for them is created. If we don't do this,
5998 * the same MonoInst is added to two different trees and this is not
6001 mono_emit_jit_icall (cfg, bblock, mono_helper_stelem_ref_check, iargs, ip);
6003 NEW_TEMPLOAD (cfg, sp [0], array->inst_c0);
6004 NEW_TEMPLOAD (cfg, sp [fsig->param_count], to_store->inst_c0);
6007 addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, TRUE);
6008 NEW_INDSTORE (cfg, ins, addr, sp [fsig->param_count], fsig->params [fsig->param_count - 1]);
6009 /* FIXME: handle CEE_STIND_R4 */
6010 if (ins->opcode == CEE_STOBJ) {
6011 handle_stobj (cfg, bblock, addr, sp [fsig->param_count], ip, mono_class_from_mono_type (fsig->params [fsig->param_count-1]), FALSE, FALSE, TRUE);
6013 MONO_ADD_INS (bblock, ins);
6016 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
6017 addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
6018 NEW_INDLOAD (cfg, ins, addr, fsig->ret);
6021 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
6022 if (!cmethod->klass->element_class->valuetype && !readonly) {
6024 //* Needed by the code generated in inssel.brg * /
6025 mono_get_got_var (cfg);
6027 MONO_INST_NEW (cfg, check, OP_CHECK_ARRAY_TYPE);
6028 check->klass = cmethod->klass;
6029 check->inst_left = sp [0];
6030 check->type = STACK_OBJ;
6035 addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
6038 g_assert_not_reached ();
6042 /* Prevent inlining of methods which call other methods */
6044 if (mini_redirect_call (&temp, cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL)) {
6046 NEW_TEMPLOAD (cfg, *sp, temp);
6049 } else if (no_spill) {
6050 ins = (MonoInst*)mono_emit_rgctx_method_call (cfg, bblock, cmethod, fsig, sp,
6051 vtable_arg, ip, virtual ? sp [0] : NULL);
6054 if ((temp = mono_emit_rgctx_method_call_spilled (cfg, bblock, cmethod, fsig, sp,
6055 vtable_arg, ip, virtual ? sp [0] : NULL)) != -1) {
6057 NEW_TEMPLOAD (cfg, load, temp);
6059 #ifdef MONO_ARCH_SOFT_FLOAT
6060 if (load->opcode == CEE_LDIND_R4) {
6061 NEW_TEMPLOADA (cfg, load, temp);
6062 temp = handle_load_float (cfg, bblock, load, ip);
6063 NEW_TEMPLOAD (cfg, load, temp);
6076 if (cfg->method != method) {
6077 /* return from inlined method */
6082 //g_assert (returnvar != -1);
6083 NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
6084 store->cil_code = sp [0]->cil_code;
6085 /* FIXME: handle CEE_STIND_R4 */
6086 if (store->opcode == CEE_STOBJ) {
6087 g_assert_not_reached ();
6088 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
6089 /* FIXME: it is possible some optimization will pass the a heap pointer for the struct address, so we'll need the write barrier */
6090 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, return_var->klass, FALSE, FALSE, FALSE);
6091 #ifdef MONO_ARCH_SOFT_FLOAT
6092 } else if (store->opcode == CEE_STIND_R4) {
6093 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
6094 handle_store_float (cfg, bblock, store, *sp, sp [0]->cil_code);
6097 MONO_ADD_INS (bblock, store);
6101 g_assert (!return_var);
6104 MONO_INST_NEW (cfg, ins, OP_NOP);
6105 ins->opcode = mini_type_to_stind (cfg, mono_method_signature (method)->ret);
6106 if (ins->opcode == CEE_STOBJ) {
6107 NEW_RETLOADA (cfg, ins);
6108 /* FIXME: it is possible some optimization will pass the a heap pointer for the struct address, so we'll need the write barrier */
6109 handle_stobj (cfg, bblock, ins, *sp, ip, cfg->ret->klass, FALSE, FALSE, FALSE);
6111 ins->opcode = OP_SETRET;
6112 ins->inst_i0 = *sp;;
6113 ins->inst_i1 = NULL;
6114 MONO_ADD_INS (bblock, ins);
6118 if (sp != stack_start)
6120 MONO_INST_NEW (cfg, ins, OP_BR);
6122 ins->inst_target_bb = end_bblock;
6123 MONO_ADD_INS (bblock, ins);
6124 link_bblock (cfg, bblock, end_bblock);
6125 start_new_bblock = 1;
6129 MONO_INST_NEW (cfg, ins, OP_BR);
6131 MONO_ADD_INS (bblock, ins);
6132 target = ip + 1 + (signed char)(*ip);
6134 GET_BBLOCK (cfg, tblock, target);
6135 link_bblock (cfg, bblock, tblock);
6136 CHECK_BBLOCK (target, ip, tblock);
6137 ins->inst_target_bb = tblock;
6138 if (sp != stack_start) {
6139 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6141 CHECK_UNVERIFIABLE (cfg);
6143 start_new_bblock = 1;
6144 inline_costs += BRANCH_COST;
6150 if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
6152 MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
6154 target = ip + 1 + *(signed char*)ip;
6156 ADD_UNCOND (ins->opcode == CEE_BRTRUE);
6157 if (sp != stack_start) {
6158 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6160 CHECK_UNVERIFIABLE (cfg);
6162 inline_costs += BRANCH_COST;
6176 MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
6178 target = ip + 1 + *(signed char*)ip;
6180 #ifdef MONO_ARCH_SOFT_FLOAT
6181 if (sp [-1]->type == STACK_R8 || sp [-2]->type == STACK_R8) {
6182 ins->opcode = condbr_to_fp_br (ins->opcode);
6184 ins->inst_left = sp [0];
6185 ins->inst_right = sp [1];
6186 ins->type = STACK_I4;
6187 *sp++ = emit_tree (cfg, bblock, ins, ins->cil_code);
6188 MONO_INST_NEW (cfg, ins, CEE_BRTRUE);
6196 if (sp != stack_start) {
6197 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6199 CHECK_UNVERIFIABLE (cfg);
6201 inline_costs += BRANCH_COST;
6205 MONO_INST_NEW (cfg, ins, OP_BR);
6207 MONO_ADD_INS (bblock, ins);
6208 target = ip + 4 + (gint32)read32(ip);
6210 GET_BBLOCK (cfg, tblock, target);
6211 link_bblock (cfg, bblock, tblock);
6212 CHECK_BBLOCK (target, ip, tblock);
6213 ins->inst_target_bb = tblock;
6214 if (sp != stack_start) {
6215 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6217 CHECK_UNVERIFIABLE (cfg);
6219 start_new_bblock = 1;
6220 inline_costs += BRANCH_COST;
6226 if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
6228 MONO_INST_NEW (cfg, ins, *ip);
6230 target = ip + 4 + (gint32)read32(ip);
6232 ADD_UNCOND(ins->opcode == CEE_BRTRUE);
6233 if (sp != stack_start) {
6234 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6236 CHECK_UNVERIFIABLE (cfg);
6238 inline_costs += BRANCH_COST;
6252 MONO_INST_NEW (cfg, ins, *ip);
6254 target = ip + 4 + (gint32)read32(ip);
6256 #ifdef MONO_ARCH_SOFT_FLOAT
6257 if (sp [-1]->type == STACK_R8 || sp [-2]->type == STACK_R8) {
6258 ins->opcode = condbr_to_fp_br (ins->opcode);
6260 ins->inst_left = sp [0];
6261 ins->inst_right = sp [1];
6262 ins->type = STACK_I4;
6263 *sp++ = emit_tree (cfg, bblock, ins, ins->cil_code);
6264 MONO_INST_NEW (cfg, ins, CEE_BRTRUE);
6272 if (sp != stack_start) {
6273 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6275 CHECK_UNVERIFIABLE (cfg);
6277 inline_costs += BRANCH_COST;
6282 n = read32 (ip + 1);
6283 MONO_INST_NEW (cfg, ins, OP_SWITCH);
6285 ins->inst_left = *sp;
6286 if ((ins->inst_left->type != STACK_I4) && (ins->inst_left->type != STACK_PTR))
6289 CHECK_OPSIZE (n * sizeof (guint32));
6290 target = ip + n * sizeof (guint32);
6291 MONO_ADD_INS (bblock, ins);
6292 GET_BBLOCK (cfg, tblock, target);
6293 link_bblock (cfg, bblock, tblock);
6294 ins->klass = GUINT_TO_POINTER (n);
6295 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (n + 1));
6296 ins->inst_many_bb [n] = tblock;
6298 for (i = 0; i < n; ++i) {
6299 GET_BBLOCK (cfg, tblock, target + (gint32)read32(ip));
6300 link_bblock (cfg, bblock, tblock);
6301 ins->inst_many_bb [i] = tblock;
6304 if (sp != stack_start) {
6305 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
6307 CHECK_UNVERIFIABLE (cfg);
6309 /* Needed by the code generated in inssel.brg */
6310 mono_get_got_var (cfg);
6311 inline_costs += (BRANCH_COST * 2);
6325 MONO_INST_NEW (cfg, ins, *ip);
6329 ins->type = ldind_type [*ip - CEE_LDIND_I1];
6330 ins->flags |= ins_flag;
6332 if (ins->type == STACK_OBJ)
6333 ins->klass = mono_defaults.object_class;
6334 #ifdef MONO_ARCH_SOFT_FLOAT
6335 if (*ip == CEE_LDIND_R4) {
6338 temp = handle_load_float (cfg, bblock, ins->inst_i0, ip);
6339 NEW_TEMPLOAD (cfg, *sp, temp);
6353 #ifdef MONO_ARCH_SOFT_FLOAT
6354 if (*ip == CEE_STIND_R4) {
6356 handle_store_float (cfg, bblock, sp [0], sp [1], ip);
6361 #if HAVE_WRITE_BARRIERS
6362 if (*ip == CEE_STIND_REF && method->wrapper_type != MONO_WRAPPER_WRITE_BARRIER && !((sp [-1]->opcode == OP_PCONST) && (sp [-1]->inst_p0 == 0))) {
6363 /* insert call to write barrier */
6364 MonoMethod *write_barrier = mono_marshal_get_write_barrier ();
6366 mono_emit_method_call_spilled (cfg, bblock, write_barrier, mono_method_signature (write_barrier), sp, ip, NULL);
6371 MONO_INST_NEW (cfg, ins, *ip);
6374 handle_loaded_temps (cfg, bblock, stack_start, sp);
6375 MONO_ADD_INS (bblock, ins);
6376 ins->inst_i0 = sp [0];
6377 ins->inst_i1 = sp [1];
6378 ins->flags |= ins_flag;
6386 #ifdef MONO_ARCH_NO_EMULATE_MUL_IMM
6387 /* FIXME: This breaks with ssapre (mono -O=ssapre loader.exe) */
6388 if ((ins->inst_right->opcode == OP_ICONST) && !(cfg->opt & MONO_OPT_SSAPRE)) {
6389 switch (ins->opcode) {
6391 ins->opcode = OP_IMUL_IMM;
6392 ins->inst_imm = ins->inst_right->inst_c0;
6395 ins->opcode = OP_LMUL_IMM;
6396 ins->inst_imm = ins->inst_right->inst_c0;
6399 g_assert_not_reached ();
6404 if (mono_find_jit_opcode_emulation (ins->opcode)) {
6406 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6424 /* special case that gives a nice speedup and happens to workaorund a ppc jit but (for the release)
6425 * later apply the speedup to the left shift as well
6428 if ((ins->opcode == OP_LSHR_UN) && (ins->type == STACK_I8)
6429 && (ins->inst_right->opcode == OP_ICONST) && (ins->inst_right->inst_c0 == 32)) {
6430 ins->opcode = OP_LONG_SHRUN_32;
6431 /*g_print ("applied long shr speedup to %s\n", cfg->method->name);*/
6435 if (mono_find_jit_opcode_emulation (ins->opcode)) {
6437 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6451 case CEE_CONV_OVF_I8:
6452 case CEE_CONV_OVF_U8:
6456 if (mono_find_jit_opcode_emulation (ins->opcode)) {
6458 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6462 case CEE_CONV_OVF_I4:
6463 case CEE_CONV_OVF_I1:
6464 case CEE_CONV_OVF_I2:
6465 case CEE_CONV_OVF_I:
6466 case CEE_CONV_OVF_U:
6469 if (sp [-1]->type == STACK_R8) {
6470 ADD_UNOP (CEE_CONV_OVF_I8);
6478 case CEE_CONV_OVF_U1:
6479 case CEE_CONV_OVF_U2:
6480 case CEE_CONV_OVF_U4:
6483 if (sp [-1]->type == STACK_R8) {
6484 ADD_UNOP (CEE_CONV_OVF_U8);
6492 case CEE_CONV_OVF_I1_UN:
6493 case CEE_CONV_OVF_I2_UN:
6494 case CEE_CONV_OVF_I4_UN:
6495 case CEE_CONV_OVF_I8_UN:
6496 case CEE_CONV_OVF_U1_UN:
6497 case CEE_CONV_OVF_U2_UN:
6498 case CEE_CONV_OVF_U4_UN:
6499 case CEE_CONV_OVF_U8_UN:
6500 case CEE_CONV_OVF_I_UN:
6501 case CEE_CONV_OVF_U_UN:
6509 token = read32 (ip + 1);
6510 klass = mini_get_class (method, token, generic_context);
6511 CHECK_TYPELOAD (klass);
6513 if (generic_class_is_reference_type (cfg, klass)) {
6514 MonoInst *store, *load;
6515 MONO_INST_NEW (cfg, load, CEE_LDIND_REF);
6516 load->inst_i0 = sp [1];
6517 load->type = STACK_OBJ;
6518 load->klass = klass;
6519 load->flags |= ins_flag;
6520 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
6521 handle_loaded_temps (cfg, bblock, stack_start, sp);
6522 MONO_ADD_INS (bblock, store);
6523 store->inst_i0 = sp [0];
6524 store->inst_i1 = load;
6525 store->flags |= ins_flag;
6529 n = mono_class_value_size (klass, &align);
6530 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
6532 NEW_MEMCPY (cfg, copy, sp [0], sp [1], n, align);
6533 MONO_ADD_INS (bblock, copy);
6535 MonoMethod *memcpy_method = get_memcpy_method ();
6536 MonoInst *iargs [3];
6539 NEW_ICONST (cfg, iargs [2], n);
6541 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6548 MonoInst *iargs [3];
6556 token = read32 (ip + 1);
6557 klass = mini_get_class (method, token, generic_context);
6558 CHECK_TYPELOAD (klass);
6559 if (generic_class_is_reference_type (cfg, klass)) {
6560 MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
6561 ins->inst_i0 = sp [0];
6562 ins->type = STACK_OBJ;
6564 ins->flags |= ins_flag;
6571 /* Optimize the common ldobj+stloc combination */
6581 loc_index = ip [5] - CEE_STLOC_0;
6588 if ((loc_index != -1) && ip_in_bb (cfg, bblock, ip + 5)) {
6589 CHECK_LOCAL (loc_index);
6590 NEW_LOCSTORE (cfg, ins, loc_index, *sp);
6592 /* FIXME: handle CEE_STIND_R4 */
6593 if (ins->opcode == CEE_STOBJ) {
6594 handle_loaded_temps (cfg, bblock, stack_start, sp);
6595 g_assert (ins->opcode == CEE_STOBJ);
6596 NEW_LOCLOADA (cfg, ins, loc_index);
6597 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
6604 n = mono_class_value_size (klass, &align);
6605 ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
6606 NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
6607 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
6609 NEW_MEMCPY (cfg, copy, iargs [0], *sp, n, align);
6610 MONO_ADD_INS (bblock, copy);
6612 MonoMethod *memcpy_method = get_memcpy_method ();
6614 NEW_ICONST (cfg, iargs [2], n);
6616 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
6618 NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
6626 CHECK_STACK_OVF (1);
6628 n = read32 (ip + 1);
6630 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
6631 /* FIXME: moving GC */
6632 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
6633 ins->type = STACK_OBJ;
6634 ins->klass = mono_defaults.string_class;
6637 else if (method->wrapper_type != MONO_WRAPPER_NONE) {
6639 MonoInst *iargs [1];
6641 NEW_PCONST (cfg, iargs [0], mono_method_get_wrapper_data (method, n));
6642 temp = mono_emit_jit_icall (cfg, bblock, mono_string_new_wrapper, iargs, ip);
6643 NEW_TEMPLOAD (cfg, *sp, temp);
6647 if (cfg->opt & MONO_OPT_SHARED) {
6649 MonoInst *iargs [3];
6650 MonoInst* domain_var;
6652 if (cfg->compile_aot) {
6653 /* FIXME: bug when inlining methods from different assemblies (n is a token valid just in one). */
6654 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
6656 /* avoid depending on undefined C behavior in sequence points */
6657 domain_var = mono_get_domainvar (cfg);
6658 NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
6659 NEW_IMAGECONST (cfg, iargs [1], image);
6660 NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
6661 temp = mono_emit_jit_icall (cfg, bblock, mono_ldstr, iargs, ip);
6662 NEW_TEMPLOAD (cfg, *sp, temp);
6663 mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
6665 if (bblock->out_of_line) {
6666 MonoInst *iargs [2];
6669 if (cfg->method->klass->image == mono_defaults.corlib) {
6671 * Avoid relocations and save some code size by using a
6672 * version of helper_ldstr specialized to mscorlib.
6674 NEW_ICONST (cfg, iargs [0], mono_metadata_token_index (n));
6675 temp = mono_emit_jit_icall (cfg, bblock, mono_helper_ldstr_mscorlib, iargs, ip);
6677 /* Avoid creating the string object */
6678 NEW_IMAGECONST (cfg, iargs [0], image);
6679 NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
6680 temp = mono_emit_jit_icall (cfg, bblock, mono_helper_ldstr, iargs, ip);
6682 NEW_TEMPLOAD (cfg, *sp, temp);
6685 if (cfg->compile_aot) {
6686 NEW_LDSTRCONST (cfg, ins, image, n);
6690 NEW_PCONST (cfg, ins, NULL);
6691 ins->type = STACK_OBJ;
6692 ins->inst_p0 = mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
6693 ins->klass = mono_defaults.string_class;
6703 MonoInst *iargs [2];
6704 MonoMethodSignature *fsig;
6706 gboolean generic_shared = FALSE;
6709 token = read32 (ip + 1);
6710 cmethod = mini_get_method (cfg, method, token, NULL, generic_context);
6713 fsig = mono_method_get_signature (cmethod, image, token);
6715 mono_save_token_info (cfg, image, token, cmethod);
6717 if (!mono_class_init (cmethod->klass))
6720 if (cfg->generic_sharing_context) {
6721 int context_used = mono_method_check_context_used (cmethod);
6723 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD)
6724 GENERIC_SHARING_FAILURE (CEE_NEWOBJ);
6727 generic_shared = TRUE;
6730 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
6731 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
6733 CHECK_CFG_EXCEPTION;
6734 } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
6735 ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
6738 n = fsig->param_count;
6742 * Generate smaller code for the common newobj <exception> instruction in
6743 * argument checking code.
6745 if (bblock->out_of_line && cmethod->klass->image == mono_defaults.corlib && n <= 2 &&
6746 ((n < 1) || (!fsig->params [0]->byref && fsig->params [0]->type == MONO_TYPE_STRING)) &&
6747 ((n < 2) || (!fsig->params [1]->byref && fsig->params [1]->type == MONO_TYPE_STRING))) {
6748 MonoInst *iargs [3];
6753 NEW_ICONST (cfg, iargs [0], cmethod->klass->type_token);
6756 temp = mono_emit_jit_icall (cfg, bblock, mono_create_corlib_exception_0, iargs, ip);
6760 temp = mono_emit_jit_icall (cfg, bblock, mono_create_corlib_exception_1, iargs, ip);
6765 temp = mono_emit_jit_icall (cfg, bblock, mono_create_corlib_exception_2, iargs, ip);
6768 g_assert_not_reached ();
6770 NEW_TEMPLOAD (cfg, ins, temp);
6778 /* move the args to allow room for 'this' in the first position */
6784 handle_loaded_temps (cfg, bblock, stack_start, sp);
6786 if (mini_class_is_system_array (cmethod->klass)) {
6787 g_assert (!generic_shared);
6789 NEW_METHODCONST (cfg, *sp, cmethod);
6790 temp = handle_array_new (cfg, bblock, fsig->param_count, sp, ip);
6791 } else if (cmethod->string_ctor) {
6792 g_assert (!generic_shared);
6794 /* we simply pass a null pointer */
6795 NEW_PCONST (cfg, *sp, NULL);
6796 /* now call the string ctor */
6797 temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, NULL);
6799 MonoInst* callvirt_this_arg = NULL;
6801 if (cmethod->klass->valuetype) {
6802 iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
6803 temp = iargs [0]->inst_c0;
6805 NEW_TEMPLOADA (cfg, *sp, temp);
6807 handle_initobj (cfg, bblock, *sp, NULL, cmethod->klass, stack_start, sp);
6809 NEW_TEMPLOADA (cfg, *sp, temp);
6812 * The code generated by mini_emit_virtual_call () expects
6813 * iargs [0] to be a boxed instance, but luckily the vcall
6814 * will be transformed into a normal call there.
6816 } else if (generic_shared) {
6817 MonoInst *rgctx, *data;
6821 if (cfg->opt & MONO_OPT_SHARED)
6822 rgctx_info = MONO_RGCTX_INFO_KLASS;
6824 rgctx_info = MONO_RGCTX_INFO_VTABLE;
6825 data = get_runtime_generic_context_ptr (cfg, method, bblock, cmethod->klass,
6826 token, MINI_TOKEN_SOURCE_METHOD, generic_context,
6827 rgctx, rgctx_info, ip);
6829 temp = handle_alloc_from_inst (cfg, bblock, cmethod->klass, data, FALSE, ip);
6830 NEW_TEMPLOAD (cfg, *sp, temp);
6832 MonoVTable *vtable = mono_class_vtable (cfg->domain, cmethod->klass);
6834 CHECK_TYPELOAD (cmethod->klass);
6835 if (mini_field_access_needs_cctor_run (cfg, method, vtable) && !(g_slist_find (class_inits, vtable))) {
6836 guint8 *tramp = mono_create_class_init_trampoline (vtable);
6837 mono_emit_native_call (cfg, bblock, tramp,
6838 helper_sig_class_init_trampoline,
6839 NULL, ip, FALSE, FALSE);
6840 if (cfg->verbose_level > 2)
6841 g_print ("class %s.%s needs init call for ctor\n", cmethod->klass->name_space, cmethod->klass->name);
6842 class_inits = g_slist_prepend (class_inits, vtable);
6844 temp = handle_alloc (cfg, bblock, cmethod->klass, FALSE, ip);
6845 NEW_TEMPLOAD (cfg, *sp, temp);
6848 /* Avoid virtual calls to ctors if possible */
6849 if (cmethod->klass->marshalbyref)
6850 callvirt_this_arg = sp [0];
6852 if ((cfg->opt & MONO_OPT_INLINE) && cmethod && !generic_shared &&
6853 mono_method_check_inlining (cfg, cmethod) &&
6854 !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE) &&
6855 !g_list_find (dont_inline, cmethod)) {
6857 MonoBasicBlock *ebblock;
6858 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, FALSE))) {
6863 GET_BBLOCK (cfg, bblock, ip);
6864 ebblock->next_bb = bblock;
6865 link_bblock (cfg, ebblock, bblock);
6867 NEW_TEMPLOAD (cfg, *sp, temp);
6870 /* indicates start of a new block, and triggers a load
6871 of all stack arguments at bb boundarie */
6874 inline_costs += costs;
6878 /* Prevent inlining of methods which call other methods */
6880 mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
6882 } else if (generic_shared &&
6883 (cmethod->klass->valuetype ||
6884 !mono_method_is_generic_sharable_impl (cmethod))) {
6885 MonoInst *this = NULL, *rgctx, *cmethod_addr;
6887 g_assert (!callvirt_this_arg);
6889 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
6891 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
6892 NEW_ARGLOAD (cfg, this, 0);
6893 rgctx = get_runtime_generic_context (cfg, method, this, ip);
6894 cmethod_addr = get_runtime_generic_context_method (cfg, method, bblock, cmethod,
6895 generic_context, rgctx, MONO_RGCTX_INFO_GENERIC_METHOD_CODE, ip);
6897 mono_emit_calli_spilled (cfg, bblock, fsig, sp, cmethod_addr, ip);
6899 /* Prevent inlining of methods which call other methods */
6901 /* now call the actual ctor */
6902 mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
6906 NEW_TEMPLOAD (cfg, *sp, temp);
6914 gboolean shared_access = FALSE;
6919 token = read32 (ip + 1);
6920 klass = mini_get_class (method, token, generic_context);
6921 CHECK_TYPELOAD (klass);
6922 if (sp [0]->type != STACK_OBJ)
6925 if (cfg->generic_sharing_context) {
6926 int context_used = mono_class_check_context_used (klass);
6928 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD)
6929 GENERIC_SHARING_FAILURE (CEE_ISINST);
6932 shared_access = TRUE;
6935 /* Needed by the code generated in inssel.brg */
6937 mono_get_got_var (cfg);
6939 if (shared_access) {
6940 MonoInst *this = NULL, *rgctx;
6944 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
6950 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
6951 NEW_ARGLOAD (cfg, this, 0);
6952 rgctx = get_runtime_generic_context (cfg, method, this, ip);
6953 args [1] = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
6954 token, MINI_TOKEN_SOURCE_CLASS, generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
6956 temp = mono_emit_jit_icall (cfg, bblock, mono_object_isinst, args, ip);
6957 NEW_TEMPLOAD (cfg, *sp, temp);
6962 } else if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
6964 MonoMethod *mono_isinst;
6965 MonoInst *iargs [1];
6966 MonoBasicBlock *ebblock;
6970 mono_isinst = mono_marshal_get_isinst (klass);
6973 costs = inline_method (cfg, mono_isinst, mono_method_signature (mono_isinst), bblock,
6974 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
6976 g_assert (costs > 0);
6981 GET_BBLOCK (cfg, bblock, ip);
6982 ebblock->next_bb = bblock;
6983 link_bblock (cfg, ebblock, bblock);
6985 temp = iargs [0]->inst_i0->inst_c0;
6986 NEW_TEMPLOAD (cfg, *sp, temp);
6990 inline_costs += costs;
6992 MONO_INST_NEW (cfg, ins, *ip);
6993 ins->type = STACK_OBJ;
6994 ins->inst_left = *sp;
6995 ins->inst_newa_class = klass;
6997 *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
7002 case CEE_UNBOX_ANY: {
7003 MonoInst *add, *vtoffset;
7004 MonoInst *iargs [3];
7006 int context_used = 0;
7011 token = read32 (ip + 1);
7012 klass = mini_get_class (method, token, generic_context);
7013 CHECK_TYPELOAD (klass);
7015 if (cfg->generic_sharing_context) {
7016 context_used = mono_class_check_context_used (klass);
7018 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD)
7019 GENERIC_SHARING_FAILURE (CEE_UNBOX_ANY);
7022 if (generic_class_is_reference_type (cfg, klass)) {
7024 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (CEE_UNBOX_ANY);
7025 switch (emit_castclass (klass, token, context_used, FALSE,
7026 cfg, method, arg_array, param_types, dont_inline, end, header,
7027 generic_context, &bblock, &ip, &sp, &inline_costs, &real_offset)) {
7029 case -1: goto unverified;
7030 default: g_assert_not_reached ();
7035 if (mono_class_is_nullable (klass)) {
7037 MonoInst *rgctx = NULL;
7040 MonoInst *this = NULL;
7042 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
7043 NEW_ARGLOAD (cfg, this, 0);
7044 rgctx = get_runtime_generic_context (cfg, method, this, ip);
7047 v = handle_unbox_nullable (cfg, method, bblock, *sp, ip, klass, generic_context, rgctx);
7048 NEW_TEMPLOAD (cfg, *sp, v);
7054 /* Needed by the code generated in inssel.brg */
7055 mono_get_got_var (cfg);
7058 MonoInst *this = NULL, *rgctx;
7059 MonoInst *element_class;
7061 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (CEE_UNBOX_ANY);
7063 /* This assertion is from the
7065 g_assert (klass->rank == 0);
7067 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
7068 NEW_ARGLOAD (cfg, this, 0);
7069 rgctx = get_runtime_generic_context (cfg, method, this, ip);
7070 /* FIXME: Passing token here is
7071 technically not correct, because we
7073 klass->element_class. Since it's
7074 only used by code for debugging the
7075 extensible runtime generic context
7076 it's not a big deal. To be correct
7077 we'd have to invent a new token
7079 element_class = get_runtime_generic_context_ptr (cfg, method, bblock,
7080 klass->element_class, token, MINI_TOKEN_SOURCE_CLASS,
7081 generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
7083 MONO_INST_NEW (cfg, ins, OP_UNBOXCAST_REG);
7084 ins->type = STACK_OBJ;
7085 ins->inst_left = *sp;
7086 ins->inst_right = element_class;
7089 MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
7090 ins->type = STACK_OBJ;
7091 ins->inst_left = *sp;
7093 ins->inst_newa_class = klass;
7096 MONO_INST_NEW (cfg, add, OP_PADD);
7097 NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
7098 add->inst_left = ins;
7099 add->inst_right = vtoffset;
7100 add->type = STACK_MP;
7101 add->klass = mono_defaults.object_class;
7105 n = mono_class_value_size (klass, &align);
7106 ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
7107 NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
7108 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
7110 NEW_MEMCPY (cfg, copy, iargs [0], *sp, n, align);
7111 MONO_ADD_INS (bblock, copy);
7113 MonoMethod *memcpy_method = get_memcpy_method ();
7115 NEW_ICONST (cfg, iargs [2], n);
7117 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
7119 NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
7125 MonoInst *add, *vtoffset;
7130 token = read32 (ip + 1);
7131 klass = mini_get_class (method, token, generic_context);
7132 CHECK_TYPELOAD (klass);
7134 if (cfg->generic_sharing_context && mono_class_check_context_used (klass))
7135 GENERIC_SHARING_FAILURE (CEE_UNBOX);
7137 if (mono_class_is_nullable (klass)) {
7138 int v = handle_unbox_nullable (cfg, method, bblock, *sp, ip, klass, generic_context, NULL);
7139 NEW_TEMPLOAD (cfg, *sp, v);
7145 /* Needed by the code generated in inssel.brg */
7146 mono_get_got_var (cfg);
7148 MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
7149 ins->type = STACK_OBJ;
7150 ins->inst_left = *sp;
7152 ins->inst_newa_class = klass;
7154 MONO_INST_NEW (cfg, add, OP_PADD);
7155 NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
7156 add->inst_left = ins;
7157 add->inst_right = vtoffset;
7158 add->type = STACK_MP;
7165 case CEE_CASTCLASS: {
7166 gboolean shared_access = FALSE;
7171 token = read32 (ip + 1);
7172 klass = mini_get_class (method, token, generic_context);
7173 CHECK_TYPELOAD (klass);
7174 if (sp [0]->type != STACK_OBJ)
7177 if (cfg->generic_sharing_context) {
7178 int context_used = mono_class_check_context_used (klass);
7180 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD)
7181 GENERIC_SHARING_FAILURE (CEE_CASTCLASS);
7184 shared_access = TRUE;
7185 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
7189 switch (emit_castclass (klass, token, shared_access, TRUE,
7190 cfg, method, arg_array, param_types, dont_inline, end, header,
7191 generic_context, &bblock, &ip, &sp, &inline_costs, &real_offset)) {
7193 case -1: goto unverified;
7194 default: g_assert_not_reached ();
7200 MONO_INST_NEW (cfg, ins, OP_THROW);
7202 ins->inst_left = *sp;
7204 bblock->out_of_line = TRUE;
7205 MONO_ADD_INS (bblock, ins);
7206 MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
7207 ins->cil_code = ip - 1;
7208 MONO_ADD_INS (bblock, ins);
7211 link_bblock (cfg, bblock, end_bblock);
7212 start_new_bblock = 1;
7217 MonoInst *offset_ins;
7218 MonoClassField *field;
7219 MonoBasicBlock *ebblock;
7223 if (*ip == CEE_STFLD) {
7230 if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
7232 if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
7235 token = read32 (ip + 1);
7236 if (method->wrapper_type != MONO_WRAPPER_NONE) {
7237 field = mono_method_get_wrapper_data (method, token);
7238 klass = field->parent;
7240 field = mono_field_from_token (image, token, &klass, generic_context);
7244 mono_class_init (klass);
7245 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
7246 FIELD_ACCESS_FAILURE;
7248 foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
7249 /* FIXME: mark instructions for use in SSA */
7250 if (*ip == CEE_STFLD) {
7251 if (target_type_is_incompatible (cfg, field->type, sp [1]))
7253 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
7254 MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type);
7255 MonoInst *iargs [5];
7258 NEW_CLASSCONST (cfg, iargs [1], klass);
7259 NEW_FIELDCONST (cfg, iargs [2], field);
7260 NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) :
7264 if (cfg->opt & MONO_OPT_INLINE) {
7265 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), bblock,
7266 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
7267 g_assert (costs > 0);
7272 GET_BBLOCK (cfg, bblock, ip);
7273 ebblock->next_bb = bblock;
7274 link_bblock (cfg, ebblock, bblock);
7276 /* indicates start of a new block, and triggers a load
7277 of all stack arguments at bb boundarie */
7280 inline_costs += costs;
7283 mono_emit_method_call_spilled (cfg, bblock, stfld_wrapper, mono_method_signature (stfld_wrapper), iargs, ip, NULL);
7285 #if HAVE_WRITE_BARRIERS
7286 } else if (mini_type_to_stind (cfg, field->type) == CEE_STIND_REF && !(sp [1]->opcode == OP_PCONST && sp [1]->inst_c0 == 0)) {
7287 /* insert call to write barrier */
7288 MonoMethod *write_barrier = mono_marshal_get_write_barrier ();
7289 MonoInst *iargs [2];
7290 NEW_ICONST (cfg, offset_ins, foffset);
7291 MONO_INST_NEW (cfg, ins, OP_PADD);
7292 ins->inst_left = *sp;
7293 ins->inst_right = offset_ins;
7294 ins->type = STACK_MP;
7295 ins->klass = mono_defaults.object_class;
7298 mono_emit_method_call_spilled (cfg, bblock, write_barrier, mono_method_signature (write_barrier), iargs, ip, NULL);
7300 #ifdef MONO_ARCH_SOFT_FLOAT
7301 } else if (mini_type_to_stind (cfg, field->type) == CEE_STIND_R4) {
7302 NEW_ICONST (cfg, offset_ins, foffset);
7303 MONO_INST_NEW (cfg, ins, OP_PADD);
7304 ins->inst_left = *sp;
7305 ins->inst_right = offset_ins;
7306 ins->type = STACK_MP;
7307 ins->klass = mono_defaults.object_class;
7308 handle_store_float (cfg, bblock, ins, sp [1], ip);
7312 NEW_ICONST (cfg, offset_ins, foffset);
7313 MONO_INST_NEW (cfg, ins, OP_PADD);
7314 ins->inst_left = *sp;
7315 ins->inst_right = offset_ins;
7316 ins->type = STACK_MP;
7318 MONO_INST_NEW (cfg, store, mini_type_to_stind (cfg, field->type));
7319 store->inst_left = ins;
7320 store->inst_right = sp [1];
7321 handle_loaded_temps (cfg, bblock, stack_start, sp);
7322 store->flags |= ins_flag;
7324 if (store->opcode == CEE_STOBJ) {
7325 handle_stobj (cfg, bblock, ins, sp [1], ip,
7326 mono_class_from_mono_type (field->type), FALSE, FALSE, TRUE);
7328 MONO_ADD_INS (bblock, store);
7331 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
7332 MonoMethod *wrapper = (*ip == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type);
7333 MonoInst *iargs [4];
7337 NEW_CLASSCONST (cfg, iargs [1], klass);
7338 NEW_FIELDCONST (cfg, iargs [2], field);
7339 NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
7340 if ((cfg->opt & MONO_OPT_INLINE) && !MONO_TYPE_ISSTRUCT (mono_method_signature (wrapper)->ret)) {
7341 costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), bblock,
7342 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
7343 g_assert (costs > 0);
7348 GET_BBLOCK (cfg, bblock, ip);
7349 ebblock->next_bb = bblock;
7350 link_bblock (cfg, ebblock, bblock);
7352 temp = iargs [0]->inst_i0->inst_c0;
7354 NEW_TEMPLOAD (cfg, *sp, temp);
7357 /* indicates start of a new block, and triggers a load of
7358 all stack arguments at bb boundarie */
7361 inline_costs += costs;
7364 temp = mono_emit_method_call_spilled (cfg, bblock, wrapper, mono_method_signature (wrapper), iargs, ip, NULL);
7365 NEW_TEMPLOAD (cfg, *sp, temp);
7369 NEW_ICONST (cfg, offset_ins, foffset);
7370 MONO_INST_NEW (cfg, ins, OP_PADD);
7371 ins->inst_left = *sp;
7372 ins->inst_right = offset_ins;
7373 ins->type = STACK_MP;
7375 if (*ip == CEE_LDFLDA) {
7376 ins->klass = mono_class_from_mono_type (field->type);
7380 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, field->type));
7381 type_to_eval_stack_type (cfg, field->type, load);
7382 load->inst_left = ins;
7383 load->flags |= ins_flag;
7385 #ifdef MONO_ARCH_SOFT_FLOAT
7386 if (mini_type_to_ldind (cfg, field->type) == CEE_LDIND_R4) {
7388 temp = handle_load_float (cfg, bblock, ins, ip);
7389 NEW_TEMPLOAD (cfg, *sp, temp);
7403 MonoClassField *field;
7404 gpointer addr = NULL;
7405 gboolean shared_access = FALSE;
7409 token = read32 (ip + 1);
7410 if (method->wrapper_type != MONO_WRAPPER_NONE) {
7411 field = mono_method_get_wrapper_data (method, token);
7412 klass = field->parent;
7415 field = mono_field_from_token (image, token, &klass, generic_context);
7418 mono_class_init (klass);
7419 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_field (method, field))
7420 FIELD_ACCESS_FAILURE;
7423 * We can only support shared generic static
7424 * field access on architectures where the
7425 * trampoline code has been extended to handle
7426 * the generic class init.
7428 #ifndef MONO_ARCH_VTABLE_REG
7429 GENERIC_SHARING_FAILURE (*ip);
7432 if (cfg->generic_sharing_context) {
7433 int context_used = mono_class_check_context_used (klass);
7435 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD ||
7437 GENERIC_SHARING_FAILURE (*ip);
7440 relation = mono_class_generic_class_relation (klass, MONO_RGCTX_INFO_VTABLE,
7441 method->klass, generic_context, NULL);
7442 shared_access = TRUE;
7446 g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL));
7448 if ((*ip) == CEE_STSFLD)
7449 handle_loaded_temps (cfg, bblock, stack_start, sp);
7451 /* The special_static_fields field is init'd in mono_class_vtable, so it needs
7452 * to be called here.
7454 if (!(cfg->opt & MONO_OPT_SHARED)) {
7455 mono_class_vtable (cfg->domain, klass);
7456 CHECK_TYPELOAD (klass);
7458 mono_domain_lock (cfg->domain);
7459 if (cfg->domain->special_static_fields)
7460 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
7461 mono_domain_unlock (cfg->domain);
7463 if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
7465 MonoInst *iargs [2];
7466 MonoInst *domain_var;
7468 g_assert (field->parent);
7469 /* avoid depending on undefined C behavior in sequence points */
7470 domain_var = mono_get_domainvar (cfg);
7471 NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
7472 if (shared_access) {
7476 iargs [1] = get_runtime_generic_context_field (cfg, method, bblock, field,
7477 generic_context, rgctx, MONO_RGCTX_INFO_CLASS_FIELD, ip);
7479 NEW_FIELDCONST (cfg, iargs [1], field);
7481 temp = mono_emit_jit_icall (cfg, bblock, mono_class_static_field_address, iargs, ip);
7482 NEW_TEMPLOAD (cfg, ins, temp);
7483 } else if (shared_access) {
7484 MonoInst *this, *rgctx, *static_data;
7486 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
7489 g_print ("sharing static field access in %s.%s.%s - depth %d offset %d\n",
7490 method->klass->name_space, method->klass->name, method->name,
7491 depth, field->offset);
7494 if (mono_class_needs_cctor_run (klass, method)) {
7495 MonoMethodSignature *sig = helper_sig_generic_class_init_trampoline;
7497 MonoInst *vtable, *rgctx;
7499 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
7500 NEW_ARGLOAD (cfg, this, 0);
7504 rgctx = get_runtime_generic_context (cfg, method, this, ip);
7505 vtable = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
7506 token, MINI_TOKEN_SOURCE_FIELD, generic_context,
7507 rgctx, MONO_RGCTX_INFO_VTABLE, ip);
7509 call = mono_emit_call_args (cfg, bblock, sig, NULL, FALSE, FALSE, ip, FALSE);
7510 call->inst.opcode = OP_TRAMPCALL_VTABLE;
7511 call->fptr = mono_get_trampoline_code (MONO_TRAMPOLINE_GENERIC_CLASS_INIT);
7513 call->inst.inst_left = vtable;
7515 mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
7519 * The pointer we're computing here is
7521 * super_info.static_data + field->offset
7524 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
7525 NEW_ARGLOAD (cfg, this, 0);
7528 rgctx = get_runtime_generic_context (cfg, method, this, ip);
7529 static_data = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
7530 token, MINI_TOKEN_SOURCE_FIELD, generic_context,
7531 rgctx, MONO_RGCTX_INFO_STATIC_DATA, ip);
7533 if (field->offset == 0) {
7536 MonoInst *field_offset;
7538 NEW_ICONST (cfg, field_offset, field->offset);
7540 MONO_INST_NEW (cfg, ins, OP_PADD);
7541 ins->inst_left = static_data;
7542 ins->inst_right = field_offset;
7543 ins->type = STACK_PTR;
7549 vtable = mono_class_vtable (cfg->domain, klass);
7550 CHECK_TYPELOAD (klass);
7552 if (mini_field_access_needs_cctor_run (cfg, method, vtable) && !(g_slist_find (class_inits, vtable))) {
7553 guint8 *tramp = mono_create_class_init_trampoline (vtable);
7554 mono_emit_native_call (cfg, bblock, tramp,
7555 helper_sig_class_init_trampoline,
7556 NULL, ip, FALSE, FALSE);
7557 if (cfg->verbose_level > 2)
7558 g_print ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, field->name);
7559 class_inits = g_slist_prepend (class_inits, vtable);
7561 if (cfg->run_cctors) {
7562 /* This makes so that inline cannot trigger */
7563 /* .cctors: too many apps depend on them */
7564 /* running with a specific order... */
7565 if (! vtable->initialized)
7567 mono_runtime_class_init (vtable);
7570 addr = (char*)vtable->data + field->offset;
7572 if (cfg->compile_aot)
7573 NEW_SFLDACONST (cfg, ins, field);
7575 NEW_PCONST (cfg, ins, addr);
7578 * insert call to mono_threads_get_static_data (GPOINTER_TO_UINT (addr))
7579 * This could be later optimized to do just a couple of
7580 * memory dereferences with constant offsets.
7583 MonoInst *iargs [1];
7584 NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
7585 temp = mono_emit_jit_icall (cfg, bblock, mono_get_special_static_data, iargs, ip);
7586 NEW_TEMPLOAD (cfg, ins, temp);
7590 /* FIXME: mark instructions for use in SSA */
7591 if (*ip == CEE_LDSFLDA) {
7592 ins->klass = mono_class_from_mono_type (field->type);
7594 } else if (*ip == CEE_STSFLD) {
7598 MONO_INST_NEW (cfg, store, mini_type_to_stind (cfg, field->type));
7599 store->inst_left = ins;
7600 store->inst_right = sp [0];
7601 store->flags |= ins_flag;
7604 #ifdef MONO_ARCH_SOFT_FLOAT
7605 if (store->opcode == CEE_STIND_R4)
7606 handle_store_float (cfg, bblock, ins, sp [0], ip);
7609 if (store->opcode == CEE_STOBJ) {
7610 handle_stobj (cfg, bblock, ins, sp [0], ip, mono_class_from_mono_type (field->type), FALSE, FALSE, FALSE);
7612 MONO_ADD_INS (bblock, store);
7614 gboolean is_const = FALSE;
7615 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
7617 CHECK_TYPELOAD (klass);
7618 if (!shared_access && !((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) &&
7619 vtable->initialized && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY)) {
7620 gpointer addr = (char*)vtable->data + field->offset;
7621 int ro_type = field->type->type;
7622 if (ro_type == MONO_TYPE_VALUETYPE && field->type->data.klass->enumtype) {
7623 ro_type = field->type->data.klass->enum_basetype->type;
7625 /* g_print ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, field->name);*/
7628 case MONO_TYPE_BOOLEAN:
7630 NEW_ICONST (cfg, *sp, *((guint8 *)addr));
7634 NEW_ICONST (cfg, *sp, *((gint8 *)addr));
7637 case MONO_TYPE_CHAR:
7639 NEW_ICONST (cfg, *sp, *((guint16 *)addr));
7643 NEW_ICONST (cfg, *sp, *((gint16 *)addr));
7648 NEW_ICONST (cfg, *sp, *((gint32 *)addr));
7652 NEW_ICONST (cfg, *sp, *((guint32 *)addr));
7655 #ifndef HAVE_MOVING_COLLECTOR
7658 case MONO_TYPE_STRING:
7659 case MONO_TYPE_OBJECT:
7660 case MONO_TYPE_CLASS:
7661 case MONO_TYPE_SZARRAY:
7663 case MONO_TYPE_FNPTR:
7664 case MONO_TYPE_ARRAY:
7665 NEW_PCONST (cfg, *sp, *((gpointer *)addr));
7666 type_to_eval_stack_type (cfg, field->type, *sp);
7672 MONO_INST_NEW (cfg, *sp, OP_I8CONST);
7673 sp [0]->type = STACK_I8;
7674 sp [0]->inst_l = *((gint64 *)addr);
7679 case MONO_TYPE_VALUETYPE:
7688 CHECK_STACK_OVF (1);
7689 MONO_INST_NEW (cfg, load, mini_type_to_ldind (cfg, field->type));
7690 type_to_eval_stack_type (cfg, field->type, load);
7691 load->inst_left = ins;
7692 load->flags |= ins_flag;
7693 #ifdef MONO_ARCH_SOFT_FLOAT
7694 if (load->opcode == CEE_LDIND_R4) {
7696 temp = handle_load_float (cfg, bblock, ins, ip);
7697 NEW_TEMPLOAD (cfg, load, temp);
7711 token = read32 (ip + 1);
7712 klass = mini_get_class (method, token, generic_context);
7713 CHECK_TYPELOAD (klass);
7714 n = mini_type_to_stind (cfg, &klass->byval_arg);
7715 /* FIXME: handle CEE_STIND_R4 */
7716 if (n == CEE_STOBJ) {
7717 handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE, TRUE);
7719 /* FIXME: should check item at sp [1] is compatible with the type of the store. */
7721 MONO_INST_NEW (cfg, store, n);
7722 store->inst_left = sp [0];
7723 store->inst_right = sp [1];
7724 store->flags |= ins_flag;
7725 MONO_ADD_INS (bblock, store);
7733 int context_used = 0;
7739 token = read32 (ip + 1);
7740 klass = mini_get_class (method, token, generic_context);
7741 CHECK_TYPELOAD (klass);
7743 if (cfg->generic_sharing_context) {
7744 context_used = mono_class_check_context_used (klass);
7746 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD)
7747 GENERIC_SHARING_FAILURE (*ip);
7750 if (generic_class_is_reference_type (cfg, klass)) {
7755 if (klass == mono_defaults.void_class)
7757 if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
7759 /* frequent check in generic code: box (struct), brtrue */
7760 if (!mono_class_is_nullable (klass) &&
7761 ip + 5 < end && ip_in_bb (cfg, bblock, ip + 5) && (ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S)) {
7762 /*g_print ("box-brtrue opt at 0x%04x in %s\n", real_offset, method->name);*/
7763 MONO_INST_NEW (cfg, ins, CEE_POP);
7764 MONO_ADD_INS (bblock, ins);
7768 MONO_INST_NEW (cfg, ins, OP_BR);
7769 MONO_ADD_INS (bblock, ins);
7770 if (*ip == CEE_BRTRUE_S) {
7773 target = ip + 1 + (signed char)(*ip);
7778 target = ip + 4 + (gint)(read32 (ip));
7781 GET_BBLOCK (cfg, tblock, target);
7782 link_bblock (cfg, bblock, tblock);
7783 CHECK_BBLOCK (target, ip, tblock);
7784 ins->inst_target_bb = tblock;
7785 GET_BBLOCK (cfg, tblock, ip);
7786 link_bblock (cfg, bblock, tblock);
7787 if (sp != stack_start) {
7788 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
7790 CHECK_UNVERIFIABLE (cfg);
7792 start_new_bblock = 1;
7798 if (mono_class_is_nullable (klass)) {
7800 *sp++ = handle_box_nullable_from_inst (cfg, method, context_used, bblock, val,
7801 ip, klass, generic_context, rgctx);
7807 if (cfg->opt & MONO_OPT_SHARED)
7808 rgctx_info = MONO_RGCTX_INFO_KLASS;
7810 rgctx_info = MONO_RGCTX_INFO_VTABLE;
7811 data = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
7812 token, MINI_TOKEN_SOURCE_CLASS, generic_context,
7813 rgctx, rgctx_info, ip);
7815 *sp++ = handle_box_from_inst (cfg, bblock, val, ip, klass, data);
7818 *sp++ = handle_box (cfg, bblock, val, ip, klass);
7825 gboolean shared_access = FALSE;
7831 token = read32 (ip + 1);
7833 /* allocate the domainvar - becaus this is used in decompose_foreach */
7834 if (cfg->opt & MONO_OPT_SHARED) {
7835 mono_get_domainvar (cfg);
7836 /* LAME-IR: Mark it as used since otherwise it will be optimized away */
7837 cfg->domainvar->flags |= MONO_INST_VOLATILE;
7841 mono_get_got_var (cfg);
7843 klass = mini_get_class (method, token, generic_context);
7844 CHECK_TYPELOAD (klass);
7846 if (cfg->generic_sharing_context) {
7847 int context_used = mono_class_check_context_used (klass);
7849 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD || klass->valuetype)
7850 GENERIC_SHARING_FAILURE (CEE_NEWARR);
7853 shared_access = TRUE;
7856 if (shared_access) {
7857 MonoInst *this = NULL, *rgctx;
7861 GENERIC_SHARING_FAILURE_IF_VALUETYPE_METHOD (*ip);
7864 NEW_DOMAINCONST (cfg, args [0]);
7867 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
7868 NEW_ARGLOAD (cfg, this, 0);
7869 rgctx = get_runtime_generic_context (cfg, method, this, ip);
7870 args [1] = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
7871 token, MINI_TOKEN_SOURCE_CLASS, generic_context, rgctx, MONO_RGCTX_INFO_KLASS, ip);
7876 temp = mono_emit_jit_icall (cfg, bblock, mono_array_new, args, ip);
7877 NEW_TEMPLOAD (cfg, ins, temp);
7879 MONO_INST_NEW (cfg, ins, *ip);
7880 ins->inst_newa_class = klass;
7881 ins->inst_newa_len = *sp;
7882 ins->type = STACK_OBJ;
7883 ins->klass = mono_array_class_get (klass, 1);
7889 * we store the object so calls to create the array are not interleaved
7890 * with the arguments of other calls.
7893 MonoInst *store, *temp, *load;
7894 const char *data_ptr;
7897 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
7898 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
7899 store->cil_code = ins->cil_code;
7900 MONO_ADD_INS (bblock, store);
7902 * we inline/optimize the initialization sequence if possible.
7903 * we should also allocate the array as not cleared, since we spend as much time clearing to 0 as initializing
7904 * for small sizes open code the memcpy
7905 * ensure the rva field is big enough
7907 if ((cfg->opt & MONO_OPT_INTRINS) && ip + 6 < end && ip_in_bb (cfg, bblock, ip + 6) && (data_ptr = initialize_array_data (method, cfg->compile_aot, ip, ins, &data_size))) {
7908 MonoMethod *memcpy_method = get_memcpy_method ();
7909 MonoInst *data_offset, *add;
7910 MonoInst *iargs [3];
7911 NEW_ICONST (cfg, iargs [2], data_size);
7912 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
7913 load->cil_code = ins->cil_code;
7914 NEW_ICONST (cfg, data_offset, G_STRUCT_OFFSET (MonoArray, vector));
7915 MONO_INST_NEW (cfg, add, OP_PADD);
7916 add->inst_left = load;
7917 add->inst_right = data_offset;
7919 if (cfg->compile_aot) {
7920 NEW_AOTCONST_TOKEN (cfg, iargs [1], MONO_PATCH_INFO_RVA, method->klass->image, GPOINTER_TO_UINT(data_ptr), STACK_PTR, NULL);
7922 NEW_PCONST (cfg, iargs [1], (char*)data_ptr);
7924 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
7927 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
7928 load->cil_code = ins->cil_code;
7937 if (sp [0]->type != STACK_OBJ)
7939 MONO_INST_NEW (cfg, ins, *ip);
7941 ins->inst_left = *sp;
7942 ins->type = STACK_PTR;
7949 if (sp [0]->type != STACK_OBJ)
7952 klass = mini_get_class (method, read32 (ip + 1), generic_context);
7953 CHECK_TYPELOAD (klass);
7954 /* we need to make sure that this array is exactly the type it needs
7955 * to be for correctness. the wrappers are lax with their usage
7956 * so we need to ignore them here
7958 if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE && !readonly) {
7961 /* Needed by the code generated in inssel.brg */
7962 mono_get_got_var (cfg);
7964 MONO_INST_NEW (cfg, check, OP_CHECK_ARRAY_TYPE);
7965 check->klass = mono_array_class_get (klass, 1);
7966 check->inst_left = sp [0];
7967 check->type = STACK_OBJ;
7972 mono_class_init (klass);
7973 NEW_LDELEMA (cfg, ins, sp, klass);
7977 case CEE_LDELEM_ANY: {
7981 if (sp [0]->type != STACK_OBJ)
7984 token = read32 (ip + 1);
7985 klass = mini_get_class (method, token, generic_context);
7986 CHECK_TYPELOAD (klass);
7987 mono_class_init (klass);
7988 NEW_LDELEMA (cfg, load, sp, klass);
7989 MONO_INST_NEW (cfg, ins, mini_type_to_ldind (cfg, &klass->byval_arg));
7990 ins->inst_left = load;
7992 type_to_eval_stack_type (cfg, &klass->byval_arg, ins);
8006 case CEE_LDELEM_REF: {
8010 * ldind.x (ldelema (array, index))
8011 * ldelema does the bounds check
8015 if (sp [0]->type != STACK_OBJ)
8017 klass = array_access_to_klass (*ip, sp [0]);
8018 NEW_LDELEMA (cfg, load, sp, klass);
8019 #ifdef MONO_ARCH_SOFT_FLOAT
8020 if (*ip == CEE_LDELEM_R4) {
8022 temp = handle_load_float (cfg, bblock, load, ip);
8023 NEW_TEMPLOAD (cfg, *sp, temp);
8029 MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
8030 ins->inst_left = load;
8032 ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
8043 case CEE_STELEM_R8: {
8047 * stind.x (ldelema (array, index), val)
8048 * ldelema does the bounds check
8052 if (sp [0]->type != STACK_OBJ)
8054 klass = array_access_to_klass (*ip, sp [0]);
8055 NEW_LDELEMA (cfg, load, sp, klass);
8056 #ifdef MONO_ARCH_SOFT_FLOAT
8057 if (*ip == CEE_STELEM_R4) {
8058 handle_store_float (cfg, bblock, load, sp [2], ip);
8063 MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
8064 ins->inst_left = load;
8065 ins->inst_right = sp [2];
8067 handle_loaded_temps (cfg, bblock, stack_start, sp);
8068 MONO_ADD_INS (bblock, ins);
8072 case CEE_STELEM_ANY: {
8076 * stind.x (ldelema (array, index), val)
8077 * ldelema does the bounds check
8081 if (sp [0]->type != STACK_OBJ)
8084 token = read32 (ip + 1);
8085 klass = mini_get_class (method, token, generic_context);
8086 CHECK_TYPELOAD (klass);
8087 mono_class_init (klass);
8088 if (generic_class_is_reference_type (cfg, klass)) {
8089 /* storing a NULL doesn't need any of the complex checks in stelemref */
8090 if (sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL) {
8092 NEW_LDELEMA (cfg, load, sp, mono_defaults.object_class);
8093 MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
8094 ins->inst_left = load;
8095 ins->inst_right = sp [2];
8096 MONO_ADD_INS (bblock, ins);
8098 MonoMethod* helper = mono_marshal_get_stelemref ();
8099 MonoInst *iargs [3];
8100 handle_loaded_temps (cfg, bblock, stack_start, sp);
8106 mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
8109 NEW_LDELEMA (cfg, load, sp, klass);
8111 n = mini_type_to_stind (cfg, &klass->byval_arg);
8112 /* FIXME: CEE_STIND_R4 */
8114 handle_stobj (cfg, bblock, load, sp [2], ip, klass, FALSE, FALSE, TRUE);
8116 MONO_INST_NEW (cfg, ins, n);
8117 ins->inst_left = load;
8118 ins->inst_right = sp [2];
8119 handle_loaded_temps (cfg, bblock, stack_start, sp);
8120 MONO_ADD_INS (bblock, ins);
8127 case CEE_STELEM_REF: {
8128 MonoInst *iargs [3];
8129 MonoMethod* helper = mono_marshal_get_stelemref ();
8133 if (sp [0]->type != STACK_OBJ)
8135 if (sp [2]->type != STACK_OBJ)
8138 handle_loaded_temps (cfg, bblock, stack_start, sp);
8140 /* storing a NULL doesn't need any of the complex checks in stelemref */
8141 if (sp [2]->opcode == OP_PCONST && sp [2]->inst_p0 == NULL) {
8143 NEW_LDELEMA (cfg, load, sp, mono_defaults.object_class);
8144 MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
8145 ins->inst_left = load;
8146 ins->inst_right = sp [2];
8147 MONO_ADD_INS (bblock, ins);
8153 mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
8160 case CEE_CKFINITE: {
8161 MonoInst *store, *temp;
8164 /* this instr. can throw exceptions as side effect,
8165 * so we cant eliminate dead code which contains CKFINITE opdodes.
8166 * Spilling to memory makes sure that we always perform
8170 MONO_INST_NEW (cfg, ins, OP_CKFINITE);
8171 ins->inst_left = sp [-1];
8172 temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
8174 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
8175 MONO_ADD_INS (bblock, store);
8177 NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
8182 case CEE_REFANYVAL: {
8183 int context_used = 0;
8188 token = read32 (ip + 1);
8189 klass = mono_class_get_full (image, token, generic_context);
8190 CHECK_TYPELOAD (klass);
8191 mono_class_init (klass);
8193 if (cfg->generic_sharing_context) {
8194 context_used = mono_class_check_context_used (klass);
8195 if (context_used && cfg->compile_aot)
8196 GENERIC_SHARING_FAILURE (*ip);
8202 MONO_INST_NEW (cfg, ins, OP_REFANYVAL_REG);
8203 ins->type = STACK_MP;
8204 ins->inst_left = *sp;
8208 ins->inst_right = get_runtime_generic_context_ptr (cfg, method,
8210 token, MINI_TOKEN_SOURCE_CLASS, generic_context,
8211 rgctx, MONO_RGCTX_INFO_KLASS, ip);
8213 MONO_INST_NEW (cfg, ins, *ip);
8214 ins->type = STACK_MP;
8215 ins->inst_left = *sp;
8217 ins->inst_newa_class = klass;
8223 case CEE_MKREFANY: {
8225 int context_used = 0;
8230 token = read32 (ip + 1);
8231 klass = mono_class_get_full (image, token, generic_context);
8232 CHECK_TYPELOAD (klass);
8233 mono_class_init (klass);
8235 if (cfg->generic_sharing_context) {
8236 context_used = mono_class_check_context_used (klass);
8237 if (context_used && cfg->compile_aot)
8238 GENERIC_SHARING_FAILURE (CEE_MKREFANY);
8241 loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
8243 MonoInst *rgctx, *klass_type, *klass_klass, *loc_load;
8246 klass_klass = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
8247 token, MINI_TOKEN_SOURCE_CLASS, generic_context,
8248 rgctx, MONO_RGCTX_INFO_KLASS, ip);
8250 klass_type = get_runtime_generic_context_ptr (cfg, method, bblock, klass,
8251 token, MINI_TOKEN_SOURCE_CLASS, generic_context,
8252 rgctx, MONO_RGCTX_INFO_TYPE, ip);
8254 NEW_TEMPLOADA (cfg, loc_load, loc->inst_c0);
8256 MONO_INST_NEW (cfg, ins, OP_MKREFANY_REGS);
8257 NEW_GROUP (cfg, ins->inst_left, klass_type, klass_klass);
8258 NEW_GROUP (cfg, ins->inst_right, *sp, loc_load);
8260 MonoInst *klassconst;
8262 NEW_PCONST (cfg, klassconst, klass);
8264 MONO_INST_NEW (cfg, ins, *ip);
8265 NEW_TEMPLOADA (cfg, ins->inst_right, loc->inst_c0);
8266 NEW_GROUP (cfg, ins->inst_left, *sp, klassconst);
8269 MONO_ADD_INS (bblock, ins);
8271 NEW_TEMPLOAD (cfg, *sp, loc->inst_c0);
8278 MonoClass *handle_class;
8279 int context_used = 0;
8281 CHECK_STACK_OVF (1);
8284 n = read32 (ip + 1);
8286 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8287 handle = mono_method_get_wrapper_data (method, n);
8288 handle_class = mono_method_get_wrapper_data (method, n + 1);
8289 if (handle_class == mono_defaults.typehandle_class)
8290 handle = &((MonoClass*)handle)->byval_arg;
8293 handle = mono_ldtoken (image, n, &handle_class, generic_context);
8297 mono_class_init (handle_class);
8299 if (cfg->generic_sharing_context) {
8300 if (handle_class == mono_defaults.typehandle_class) {
8301 /* If we get a MONO_TYPE_CLASS
8302 then we need to provide the
8304 instantiation of it. */
8305 if (mono_type_get_type (handle) == MONO_TYPE_CLASS)
8308 context_used = mono_class_check_context_used (mono_class_from_mono_type (handle));
8309 } else if (handle_class == mono_defaults.fieldhandle_class)
8310 context_used = mono_class_check_context_used (((MonoClassField*)handle)->parent);
8311 else if (handle_class == mono_defaults.methodhandle_class)
8312 context_used = mono_method_check_context_used (handle);
8314 g_assert_not_reached ();
8316 if (context_used & MONO_GENERIC_CONTEXT_USED_METHOD)
8317 GENERIC_SHARING_FAILURE (CEE_LDTOKEN);
8320 if (cfg->opt & MONO_OPT_SHARED) {
8322 MonoInst *res, *store, *addr, *vtvar, *iargs [3];
8324 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
8326 NEW_IMAGECONST (cfg, iargs [0], image);
8327 NEW_ICONST (cfg, iargs [1], n);
8328 if (cfg->generic_sharing_context) {
8332 iargs [2] = get_runtime_generic_context_method (cfg, method, bblock, method,
8333 generic_context, rgctx, MONO_RGCTX_INFO_METHOD, ip);
8334 temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper_generic_shared,
8337 NEW_PCONST (cfg, iargs [2], generic_context);
8338 temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
8340 NEW_TEMPLOAD (cfg, res, temp);
8341 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
8342 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
8343 MONO_ADD_INS (bblock, store);
8344 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
8346 if ((ip + 10 < end) && ip_in_bb (cfg, bblock, ip + 5) &&
8347 handle_class == mono_defaults.typehandle_class &&
8348 ((ip [5] == CEE_CALL) || (ip [5] == CEE_CALLVIRT)) &&
8349 (cmethod = mini_get_method (cfg, method, read32 (ip + 6), NULL, generic_context)) &&
8350 (cmethod->klass == mono_defaults.monotype_class->parent) &&
8351 (strcmp (cmethod->name, "GetTypeFromHandle") == 0)) {
8352 MonoClass *tclass = mono_class_from_mono_type (handle);
8353 mono_class_init (tclass);
8355 MonoInst *this, *rgctx;
8357 g_assert (!cfg->compile_aot);
8358 if (!(method->flags & METHOD_ATTRIBUTE_STATIC))
8359 NEW_ARGLOAD (cfg, this, 0);
8360 rgctx = get_runtime_generic_context (cfg, method, this, ip);
8361 ins = get_runtime_generic_context_ptr (cfg, method, bblock, tclass,
8362 token, MINI_TOKEN_SOURCE_CLASS, generic_context,
8363 rgctx, MONO_RGCTX_INFO_REFLECTION_TYPE, ip);
8364 } else if (cfg->compile_aot) {
8365 NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n);
8367 NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
8369 ins->type = STACK_OBJ;
8370 ins->klass = cmethod->klass;
8373 MonoInst *store, *addr, *vtvar;
8375 GENERIC_SHARING_FAILURE (CEE_LDTOKEN);
8377 if (cfg->compile_aot)
8378 NEW_LDTOKENCONST (cfg, ins, image, n);
8380 NEW_PCONST (cfg, ins, handle);
8381 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
8382 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
8383 NEW_INDSTORE (cfg, store, addr, ins, &mono_defaults.int_class->byval_arg);
8384 MONO_ADD_INS (bblock, store);
8385 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
8401 case CEE_ADD_OVF_UN:
8403 case CEE_MUL_OVF_UN:
8405 case CEE_SUB_OVF_UN:
8408 if (mono_find_jit_opcode_emulation (ins->opcode)) {
8410 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
8414 case CEE_ENDFINALLY:
8415 MONO_INST_NEW (cfg, ins, OP_ENDFINALLY);
8416 MONO_ADD_INS (bblock, ins);
8418 start_new_bblock = 1;
8421 * Control will leave the method so empty the stack, otherwise
8422 * the next basic block will start with a nonempty stack.
8424 while (sp != stack_start) {
8425 MONO_INST_NEW (cfg, ins, CEE_POP);
8428 MONO_ADD_INS (bblock, ins);
8435 if (*ip == CEE_LEAVE) {
8437 target = ip + 5 + (gint32)read32(ip + 1);
8440 target = ip + 2 + (signed char)(ip [1]);
8443 /* empty the stack */
8444 while (sp != stack_start) {
8445 MONO_INST_NEW (cfg, ins, CEE_POP);
8448 MONO_ADD_INS (bblock, ins);
8452 * If this leave statement is in a catch block, check for a
8453 * pending exception, and rethrow it if necessary.
8455 for (i = 0; i < header->num_clauses; ++i) {
8456 MonoExceptionClause *clause = &header->clauses [i];
8459 * Use <= in the final comparison to handle clauses with multiple
8460 * leave statements, like in bug #78024.
8461 * The ordering of the exception clauses guarantees that we find the
8464 if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && (clause->flags == MONO_EXCEPTION_CLAUSE_NONE) && (ip - header->code + ((*ip == CEE_LEAVE) ? 5 : 2)) <= (clause->handler_offset + clause->handler_len)) {
8468 NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
8470 temp = mono_emit_jit_icall (cfg, bblock, mono_thread_get_undeniable_exception, NULL, ip);
8471 NEW_TEMPLOAD (cfg, *sp, temp);
8473 MONO_INST_NEW (cfg, ins, OP_THROW_OR_NULL);
8474 ins->inst_left = *sp;
8475 ins->inst_right = load;
8476 MONO_ADD_INS (bblock, ins);
8480 if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
8482 for (tmp = handlers; tmp; tmp = tmp->next) {
8484 link_bblock (cfg, bblock, tblock);
8485 MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
8486 ins->inst_target_bb = tblock;
8487 MONO_ADD_INS (bblock, ins);
8489 g_list_free (handlers);
8492 MONO_INST_NEW (cfg, ins, OP_BR);
8493 MONO_ADD_INS (bblock, ins);
8494 GET_BBLOCK (cfg, tblock, target);
8495 link_bblock (cfg, bblock, tblock);
8496 CHECK_BBLOCK (target, ip, tblock);
8497 ins->inst_target_bb = tblock;
8498 start_new_bblock = 1;
8500 if (*ip == CEE_LEAVE)
8509 MONO_INST_NEW (cfg, ins, *ip);
8511 handle_loaded_temps (cfg, bblock, stack_start, sp);
8512 MONO_ADD_INS (bblock, ins);
8514 ins->inst_i0 = sp [0];
8515 ins->inst_i1 = sp [1];
8523 /* trampoline mono specific opcodes */
8524 case MONO_CUSTOM_PREFIX: {
8526 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
8531 case CEE_MONO_ICALL: {
8534 MonoJitICallInfo *info;
8536 token = read32 (ip + 2);
8537 func = mono_method_get_wrapper_data (method, token);
8538 info = mono_find_jit_icall_by_addr (func);
8540 g_error ("An attempt has been made to perform an icall to address %p, "
8541 "but the address has not been registered as an icall\n", info);
8542 g_assert_not_reached ();
8545 CHECK_STACK (info->sig->param_count);
8546 sp -= info->sig->param_count;
8548 temp = mono_emit_jit_icall (cfg, bblock, info->func, sp, ip);
8549 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
8550 NEW_TEMPLOAD (cfg, *sp, temp);
8555 inline_costs += 10 * num_calls++;
8559 case CEE_MONO_LDPTR: {
8562 CHECK_STACK_OVF (1);
8564 token = read32 (ip + 2);
8566 ptr = mono_method_get_wrapper_data (method, token);
8567 if (cfg->compile_aot && cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
8568 MonoMethod *wrapped = mono_marshal_method_from_wrapper (cfg->method);
8570 if (wrapped && ptr != NULL && mono_lookup_internal_call (wrapped) == ptr) {
8571 NEW_AOTCONST (cfg, ins, MONO_PATCH_INFO_ICALL_ADDR, wrapped);
8577 NEW_PCONST (cfg, ins, ptr);
8580 inline_costs += 10 * num_calls++;
8581 /* Can't embed random pointers into AOT code */
8582 cfg->disable_aot = 1;
8585 case CEE_MONO_VTADDR:
8588 MONO_INST_NEW (cfg, ins, OP_VTADDR);
8589 ins->type = STACK_MP;
8590 ins->inst_left = *sp;
8594 case CEE_MONO_NEWOBJ: {
8595 MonoInst *iargs [2];
8597 CHECK_STACK_OVF (1);
8599 token = read32 (ip + 2);
8600 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
8601 mono_class_init (klass);
8602 NEW_DOMAINCONST (cfg, iargs [0]);
8603 NEW_CLASSCONST (cfg, iargs [1], klass);
8604 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
8605 NEW_TEMPLOAD (cfg, *sp, temp);
8608 inline_costs += 10 * num_calls++;
8611 case CEE_MONO_OBJADDR:
8614 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
8615 ins->type = STACK_MP;
8616 ins->inst_left = *sp;
8620 case CEE_MONO_LDNATIVEOBJ:
8623 token = read32 (ip + 2);
8624 klass = mono_method_get_wrapper_data (method, token);
8625 g_assert (klass->valuetype);
8626 mono_class_init (klass);
8627 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
8631 case CEE_MONO_RETOBJ:
8632 g_assert (cfg->ret);
8633 g_assert (mono_method_signature (method)->pinvoke);
8638 token = read32 (ip + 2);
8639 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
8641 NEW_RETLOADA (cfg, ins);
8642 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE, FALSE);
8644 if (sp != stack_start)
8647 MONO_INST_NEW (cfg, ins, OP_BR);
8648 ins->inst_target_bb = end_bblock;
8649 MONO_ADD_INS (bblock, ins);
8650 link_bblock (cfg, bblock, end_bblock);
8651 start_new_bblock = 1;
8654 case CEE_MONO_CISINST:
8655 case CEE_MONO_CCASTCLASS: {
8660 token = read32 (ip + 2);
8661 /* Needed by the code generated in inssel.brg */
8662 mono_get_got_var (cfg);
8664 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
8665 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_CISINST) ? OP_CISINST : OP_CCASTCLASS);
8666 ins->type = STACK_I4;
8667 ins->inst_left = *sp;
8668 ins->inst_newa_class = klass;
8669 *sp++ = emit_tree (cfg, bblock, ins, ip + 6);
8673 case CEE_MONO_SAVE_LMF:
8674 case CEE_MONO_RESTORE_LMF:
8675 #ifdef MONO_ARCH_HAVE_LMF_OPS
8676 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_SAVE_LMF) ? OP_SAVE_LMF : OP_RESTORE_LMF);
8677 MONO_ADD_INS (bblock, ins);
8678 cfg->need_lmf_area = TRUE;
8682 case CEE_MONO_CLASSCONST:
8683 CHECK_STACK_OVF (1);
8685 token = read32 (ip + 2);
8686 NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
8689 inline_costs += 10 * num_calls++;
8691 case CEE_MONO_NOT_TAKEN:
8692 bblock->out_of_line = TRUE;
8696 CHECK_STACK_OVF (1);
8698 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
8699 ins->inst_offset = (gint32)read32 (ip + 2);
8700 ins->type = STACK_PTR;
8705 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
8714 /* somewhat similar to LDTOKEN */
8715 MonoInst *addr, *vtvar;
8716 CHECK_STACK_OVF (1);
8717 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL);
8719 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
8720 MONO_INST_NEW (cfg, ins, OP_ARGLIST);
8721 ins->inst_left = addr;
8722 MONO_ADD_INS (bblock, ins);
8723 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
8736 * The following transforms:
8737 * CEE_CEQ into OP_CEQ
8738 * CEE_CGT into OP_CGT
8739 * CEE_CGT_UN into OP_CGT_UN
8740 * CEE_CLT into OP_CLT
8741 * CEE_CLT_UN into OP_CLT_UN
8743 MONO_INST_NEW (cfg, cmp, (OP_CEQ - CEE_CEQ) + ip [1]);
8745 MONO_INST_NEW (cfg, ins, cmp->opcode);
8747 cmp->inst_i0 = sp [0];
8748 cmp->inst_i1 = sp [1];
8751 ins->type = STACK_I4;
8753 #if MONO_ARCH_SOFT_FLOAT
8754 if (sp [0]->type == STACK_R8) {
8755 cmp->type = STACK_I4;
8756 *sp++ = emit_tree (cfg, bblock, cmp, ip + 2);
8761 if ((sp [0]->type == STACK_I8) || ((sizeof (gpointer) == 8) && ((sp [0]->type == STACK_PTR) || (sp [0]->type == STACK_OBJ) || (sp [0]->type == STACK_MP))))
8762 cmp->opcode = OP_LCOMPARE;
8764 cmp->opcode = OP_COMPARE;
8766 /* spill it to reduce the expression complexity
8767 * and workaround bug 54209
8769 if (cmp->inst_left->type == STACK_I8) {
8771 *sp++ = emit_tree (cfg, bblock, ins, ip + 2);
8778 MonoMethod *cil_method, *ctor_method;
8782 CHECK_STACK_OVF (1);
8784 n = read32 (ip + 2);
8785 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
8788 mono_class_init (cmethod->klass);
8790 if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
8791 GENERIC_SHARING_FAILURE (CEE_LDFTN);
8793 is_shared = (cmethod->flags & METHOD_ATTRIBUTE_STATIC) &&
8794 (cmethod->klass->generic_class || cmethod->klass->generic_container) &&
8795 mono_class_generic_sharing_enabled (cmethod->klass);
8797 cil_method = cmethod;
8798 if (!dont_verify && !cfg->skip_visibility && !mono_method_can_access_method (method, cmethod))
8799 METHOD_ACCESS_FAILURE;
8800 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
8801 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
8803 CHECK_CFG_EXCEPTION;
8804 } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
8805 ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
8809 * Optimize the common case of ldftn+delegate creation
8811 #if defined(MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE) && !defined(HAVE_WRITE_BARRIERS)
8812 /* FIXME: SGEN support */
8813 /* FIXME: handle shared static generic methods */
8814 if (!is_shared && (sp > stack_start) && (ip + 6 + 5 < end) && ip_in_bb (cfg, bblock, ip + 6) && (ip [6] == CEE_NEWOBJ) && (ctor_method = mini_get_method (cfg, method, read32 (ip + 7), NULL, generic_context)) && (ctor_method->klass->parent == mono_defaults.multicastdelegate_class)) {
8815 MonoInst *target_ins;
8818 if (cfg->verbose_level > 3)
8819 g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
8820 target_ins = sp [-1];
8822 *sp = handle_delegate_ctor (cfg, bblock, ctor_method->klass, target_ins, cmethod, ip);
8829 handle_loaded_temps (cfg, bblock, stack_start, sp);
8832 NEW_METHODCONST (cfg, argconst, mono_marshal_get_static_rgctx_invoke (cmethod));
8834 NEW_METHODCONST (cfg, argconst, cmethod);
8835 if (method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
8836 temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
8838 temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn_nosync, &argconst, ip);
8839 NEW_TEMPLOAD (cfg, *sp, temp);
8843 inline_costs += 10 * num_calls++;
8846 case CEE_LDVIRTFTN: {
8852 n = read32 (ip + 2);
8853 cmethod = mini_get_method (cfg, method, n, NULL, generic_context);
8856 mono_class_init (cmethod->klass);
8858 if (cfg->generic_sharing_context && mono_method_check_context_used (cmethod))
8859 GENERIC_SHARING_FAILURE (CEE_LDVIRTFTN);
8861 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
8862 if (check_linkdemand (cfg, method, cmethod, bblock, ip))
8864 CHECK_CFG_EXCEPTION;
8865 } else if (mono_security_get_mode () == MONO_SECURITY_MODE_CORE_CLR) {
8866 ensure_method_is_allowed_to_call_method (cfg, method, cmethod, bblock, ip);
8869 handle_loaded_temps (cfg, bblock, stack_start, sp);
8873 NEW_METHODCONST (cfg, args [1], cmethod);
8874 temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
8875 NEW_TEMPLOAD (cfg, *sp, temp);
8879 inline_costs += 10 * num_calls++;
8883 CHECK_STACK_OVF (1);
8885 n = read16 (ip + 2);
8887 NEW_ARGLOAD (cfg, ins, n);
8888 LDARG_SOFT_FLOAT (cfg, ins, n, ip);
8893 CHECK_STACK_OVF (1);
8895 n = read16 (ip + 2);
8897 NEW_ARGLOADA (cfg, ins, n);
8904 handle_loaded_temps (cfg, bblock, stack_start, sp);
8906 n = read16 (ip + 2);
8908 NEW_ARGSTORE (cfg, ins, n, *sp);
8909 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
8911 STARG_SOFT_FLOAT (cfg, ins, n, ip);
8912 if (ins->opcode == CEE_STOBJ) {
8913 NEW_ARGLOADA (cfg, ins, n);
8914 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
8916 MONO_ADD_INS (bblock, ins);
8920 CHECK_STACK_OVF (1);
8922 n = read16 (ip + 2);
8924 NEW_LOCLOAD (cfg, ins, n);
8925 LDLOC_SOFT_FLOAT (cfg, ins, n, ip);
8930 CHECK_STACK_OVF (1);
8932 n = read16 (ip + 2);
8934 NEW_LOCLOADA (cfg, ins, n);
8942 n = read16 (ip + 2);
8944 handle_loaded_temps (cfg, bblock, stack_start, sp);
8945 NEW_LOCSTORE (cfg, ins, n, *sp);
8946 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
8948 STLOC_SOFT_FLOAT (cfg, ins, n, ip);
8949 if (ins->opcode == CEE_STOBJ) {
8950 NEW_LOCLOADA (cfg, ins, n);
8951 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE, FALSE);
8953 MONO_ADD_INS (bblock, ins);
8960 if (sp != stack_start)
8962 if (cfg->method != method)
8964 * Inlining this into a loop in a parent could lead to
8965 * stack overflows which is different behavior than the
8966 * non-inlined case, thus disable inlining in this case.
8968 goto inline_failure;
8969 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
8970 ins->inst_left = *sp;
8971 ins->type = STACK_PTR;
8973 cfg->flags |= MONO_CFG_HAS_ALLOCA;
8974 if (header->init_locals)
8975 ins->flags |= MONO_INST_INIT;
8979 /* FIXME: set init flag if locals init is set in this method */
8981 case CEE_ENDFILTER: {
8982 MonoExceptionClause *clause, *nearest;
8983 int cc, nearest_num;
8987 if ((sp != stack_start) || (sp [0]->type != STACK_I4))
8989 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
8990 ins->inst_left = *sp;
8991 MONO_ADD_INS (bblock, ins);
8992 start_new_bblock = 1;
8997 for (cc = 0; cc < header->num_clauses; ++cc) {
8998 clause = &header->clauses [cc];
8999 if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
9000 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
9001 (!nearest || (clause->data.filter_offset < nearest->data.filter_offset))) {
9007 if ((ip - header->code) != nearest->handler_offset)
9012 case CEE_UNALIGNED_:
9013 ins_flag |= MONO_INST_UNALIGNED;
9014 /* FIXME: record alignment? we can assume 1 for now */
9019 ins_flag |= MONO_INST_VOLATILE;
9023 ins_flag |= MONO_INST_TAILCALL;
9024 cfg->flags |= MONO_CFG_HAS_TAIL;
9025 /* Can't inline tail calls at this time */
9026 inline_costs += 100000;
9033 token = read32 (ip + 2);
9034 klass = mini_get_class (method, token, generic_context);
9035 CHECK_TYPELOAD (klass);
9037 if (generic_class_is_reference_type (cfg, klass)) {
9038 MonoInst *store, *load;
9039 NEW_PCONST (cfg, load, NULL);
9040 load->type = STACK_OBJ;
9041 load->klass = klass;
9042 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
9043 handle_loaded_temps (cfg, bblock, stack_start, sp);
9044 MONO_ADD_INS (bblock, store);
9045 store->inst_i0 = sp [0];
9046 store->inst_i1 = load;
9048 GENERIC_SHARING_FAILURE (CEE_INITOBJ);
9049 handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
9054 case CEE_CONSTRAINED_:
9055 /* FIXME: implement */
9057 token = read32 (ip + 2);
9058 constrained_call = mono_class_get_full (image, token, generic_context);
9059 CHECK_TYPELOAD (constrained_call);
9064 MonoInst *iargs [3];
9067 if ((cfg->opt & MONO_OPT_INTRINS) && (ip [1] == CEE_CPBLK) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5)) {
9069 NEW_MEMCPY (cfg, copy, sp [0], sp [1], n, 0);
9070 MONO_ADD_INS (bblock, copy);
9077 handle_loaded_temps (cfg, bblock, stack_start, sp);
9078 if (ip [1] == CEE_CPBLK) {
9079 MonoMethod *memcpy_method = get_memcpy_method ();
9080 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
9082 MonoMethod *memset_method = get_memset_method ();
9083 mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
9092 ins_flag |= MONO_INST_NOTYPECHECK;
9094 ins_flag |= MONO_INST_NORANGECHECK;
9095 /* we ignore the no-nullcheck for now since we
9096 * really do it explicitly only when doing callvirt->call
9102 int handler_offset = -1;
9104 for (i = 0; i < header->num_clauses; ++i) {
9105 MonoExceptionClause *clause = &header->clauses [i];
9106 if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY))
9107 handler_offset = clause->handler_offset;
9110 bblock->flags |= BB_EXCEPTION_UNSAFE;
9112 g_assert (handler_offset != -1);
9114 NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
9115 MONO_INST_NEW (cfg, ins, OP_RETHROW);
9116 ins->inst_left = load;
9117 MONO_ADD_INS (bblock, ins);
9119 link_bblock (cfg, bblock, end_bblock);
9120 start_new_bblock = 1;
9125 GENERIC_SHARING_FAILURE (CEE_SIZEOF);
9127 CHECK_STACK_OVF (1);
9129 token = read32 (ip + 2);
9130 /* FIXXME: handle generics. */
9131 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
9132 MonoType *type = mono_type_create_from_typespec (image, token);
9133 token = mono_type_size (type, &ialign);
9135 MonoClass *klass = mono_class_get_full (image, token, generic_context);
9136 CHECK_TYPELOAD (klass);
9137 mono_class_init (klass);
9138 token = mono_class_value_size (klass, &align);
9140 NEW_ICONST (cfg, ins, token);
9144 case CEE_REFANYTYPE:
9146 MONO_INST_NEW (cfg, ins, OP_REFANYTYPE);
9148 ins->type = STACK_MP;
9149 ins->inst_left = *sp;
9150 ins->type = STACK_VTYPE;
9151 ins->klass = mono_defaults.typehandle_class;
9160 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
9165 g_error ("opcode 0x%02x not handled", *ip);
9168 if (start_new_bblock != 1)
9171 bblock->cil_length = ip - bblock->cil_code;
9172 bblock->next_bb = end_bblock;
9174 if (cfg->method == method && cfg->domainvar) {
9176 MonoInst *get_domain;
9178 if (! (get_domain = mono_arch_get_domain_intrinsic (cfg))) {
9181 MONO_INST_NEW_CALL (cfg, call, OP_CALL);
9182 call->signature = helper_sig_domain_get;
9183 call->inst.type = STACK_PTR;
9184 call->fptr = mono_domain_get;
9185 get_domain = (MonoInst*)call;
9188 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
9189 MONO_ADD_INS (init_localsbb, store);
9192 if (cfg->method == method && cfg->got_var)
9193 mono_emit_load_got_addr (cfg);
9195 if (header->init_locals) {
9197 cfg->ip = header->code;
9198 for (i = 0; i < header->num_locals; ++i) {
9199 MonoType *ptype = header->locals [i];
9200 int t = ptype->type;
9201 if (t == MONO_TYPE_VALUETYPE && ptype->data.klass->enumtype)
9202 t = ptype->data.klass->enum_basetype->type;
9204 NEW_PCONST (cfg, ins, NULL);
9205 NEW_LOCSTORE (cfg, store, i, ins);
9206 MONO_ADD_INS (init_localsbb, store);
9207 } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
9208 NEW_ICONST (cfg, ins, 0);
9209 NEW_LOCSTORE (cfg, store, i, ins);
9210 MONO_ADD_INS (init_localsbb, store);
9211 } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
9212 MONO_INST_NEW (cfg, ins, OP_I8CONST);
9213 ins->type = STACK_I8;
9215 NEW_LOCSTORE (cfg, store, i, ins);
9216 MONO_ADD_INS (init_localsbb, store);
9217 } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
9218 #ifdef MONO_ARCH_SOFT_FLOAT
9219 /* FIXME: handle init of R4 */
9221 MONO_INST_NEW (cfg, ins, OP_R8CONST);
9222 ins->type = STACK_R8;
9223 ins->inst_p0 = (void*)&r8_0;
9224 NEW_LOCSTORE (cfg, store, i, ins);
9225 MONO_ADD_INS (init_localsbb, store);
9227 } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
9228 ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (ptype))) {
9229 NEW_LOCLOADA (cfg, ins, i);
9230 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (ptype), NULL, NULL);
9232 NEW_PCONST (cfg, ins, NULL);
9233 NEW_LOCSTORE (cfg, store, i, ins);
9234 MONO_ADD_INS (init_localsbb, store);
9241 /* resolve backward branches in the middle of an existing basic block */
9242 for (tmp = bb_recheck; tmp; tmp = tmp->next) {
9244 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
9245 tblock = find_previous (cfg->cil_offset_to_bb, header->code_size, start_bblock, bblock->cil_code);
9246 if (tblock != start_bblock) {
9248 split_bblock (cfg, tblock, bblock);
9249 l = bblock->cil_code - header->code;
9250 bblock->cil_length = tblock->cil_length - l;
9251 tblock->cil_length = l;
9253 g_print ("recheck failed.\n");
9257 if (cfg->method == method) {
9259 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9260 bb->region = mono_find_block_region (cfg, bb->real_offset);
9262 mono_create_spvar_for_region (cfg, bb->region);
9263 if (cfg->verbose_level > 2)
9264 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
9268 g_slist_free (class_inits);
9269 dont_inline = g_list_remove (dont_inline, method);
9271 if (inline_costs < 0) {
9274 /* Method is too large */
9275 mname = mono_method_full_name (method, TRUE);
9276 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
9277 cfg->exception_message = g_strdup_printf ("Method %s is too complex.", mname);
9282 return inline_costs;
9285 g_assert (cfg->exception_type != MONO_EXCEPTION_NONE);
9286 g_slist_free (class_inits);
9287 dont_inline = g_list_remove (dont_inline, method);
9291 g_slist_free (class_inits);
9292 dont_inline = g_list_remove (dont_inline, method);
9296 g_slist_free (class_inits);
9297 dont_inline = g_list_remove (dont_inline, method);
9298 cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
9302 g_slist_free (class_inits);
9303 dont_inline = g_list_remove (dont_inline, method);
9304 set_exception_type_from_invalid_il (cfg, method, ip);
9309 mono_print_tree (MonoInst *tree) {
9315 arity = mono_burg_arity [tree->opcode];
9317 printf (" %s%s", arity?"(":"", mono_inst_name (tree->opcode));
9319 switch (tree->opcode) {
9321 printf ("[%d]", (int)tree->inst_c0);
9324 printf ("[%lld]", (long long)tree->inst_l);
9327 printf ("[%f]", *(double*)tree->inst_p0);
9330 printf ("[%f]", *(float*)tree->inst_p0);
9334 printf ("[%d]", (int)tree->inst_c0);
9337 if (tree->inst_offset < 0)
9338 printf ("[-0x%x(%s)]", (int)(-tree->inst_offset), mono_arch_regname (tree->inst_basereg));
9340 printf ("[0x%x(%s)]", (int)(tree->inst_offset), mono_arch_regname (tree->inst_basereg));
9343 printf ("[%s]", mono_arch_regname (tree->dreg));
9346 printf ("[%s]", tree->inst_newa_class->name);
9347 mono_print_tree (tree->inst_newa_len);
9358 case OP_VOIDCALLVIRT:
9359 case OP_TRAMPCALL_VTABLE: {
9360 MonoCallInst *call = (MonoCallInst*)tree;
9362 printf ("[%s]", call->method->name);
9363 else if (call->fptr) {
9364 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (call->fptr);
9366 printf ("[%s]", info->name);
9372 printf ("[%d (", (int)tree->inst_c0);
9373 for (i = 0; i < tree->inst_phi_args [0]; i++) {
9376 printf ("%d", tree->inst_phi_args [i + 1]);
9387 case OP_LOAD_MEMBASE:
9388 case OP_LOADI4_MEMBASE:
9389 case OP_LOADU4_MEMBASE:
9390 case OP_LOADU1_MEMBASE:
9391 case OP_LOADI1_MEMBASE:
9392 case OP_LOADU2_MEMBASE:
9393 case OP_LOADI2_MEMBASE:
9394 printf ("[%s] <- [%s + 0x%x]", mono_arch_regname (tree->dreg), mono_arch_regname (tree->inst_basereg), (int)tree->inst_offset);
9397 case OP_CALL_HANDLER:
9398 printf ("[B%d]", tree->inst_target_bb->block_num);
9408 case OP_VOIDCALL_REG:
9409 mono_print_tree (tree->inst_left);
9421 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
9422 mono_print_tree (tree->inst_left);
9425 if (!mono_arch_print_tree(tree, arity)) {
9427 mono_print_tree (tree->inst_left);
9429 mono_print_tree (tree->inst_right);
9440 mono_print_tree_nl (MonoInst *tree)
9442 mono_print_tree (tree);
9447 create_helper_signature (void)
9449 helper_sig_domain_get = mono_create_icall_signature ("ptr");
9450 helper_sig_class_init_trampoline = mono_create_icall_signature ("void");
9451 helper_sig_generic_class_init_trampoline = mono_create_icall_signature ("void");
9452 helper_sig_rgctx_lazy_fetch_trampoline = mono_create_icall_signature ("ptr ptr");
9456 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
9459 MonoMethod *wrapper;
9460 gconstpointer trampoline;
9461 MonoDomain *domain = mono_get_root_domain ();
9463 if (callinfo->wrapper) {
9464 return callinfo->wrapper;
9467 if (callinfo->trampoline)
9468 return callinfo->trampoline;
9471 * We use the lock on the root domain instead of the JIT lock to protect
9472 * callinfo->trampoline, since we do a lot of stuff inside the critical section.
9474 mono_domain_lock (domain);
9476 if (callinfo->trampoline) {
9477 mono_domain_unlock (domain);
9478 return callinfo->trampoline;
9481 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
9482 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
9485 trampoline = mono_create_ftnptr (domain, mono_create_jit_trampoline_in_domain (domain, wrapper));
9486 mono_register_jit_icall_wrapper (callinfo, trampoline);
9488 callinfo->trampoline = trampoline;
9490 mono_domain_unlock (domain);
9492 return callinfo->trampoline;
9496 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
9498 if (!domain->dynamic_code_hash)
9499 domain->dynamic_code_hash = g_hash_table_new (NULL, NULL);
9500 g_hash_table_insert (domain->dynamic_code_hash, method, ji);
9503 static MonoJitDynamicMethodInfo*
9504 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
9506 MonoJitDynamicMethodInfo *res;
9508 if (domain->dynamic_code_hash)
9509 res = g_hash_table_lookup (domain->dynamic_code_hash, method);
9521 static inline GSList*
9522 g_slist_prepend_mempool (MonoMemPool *mp, GSList *list,
9527 new_list = mono_mempool_alloc (mp, sizeof (GSList));
9528 new_list->data = data;
9529 new_list->next = list;
9535 * mono_allocate_stack_slots_full:
9537 * Allocate stack slots for all non register allocated variables using a
9538 * linear scan algorithm.
9539 * Returns: an array of stack offsets.
9540 * STACK_SIZE is set to the amount of stack space needed.
9541 * STACK_ALIGN is set to the alignment needed by the locals area.
9544 mono_allocate_stack_slots_full (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
9546 int i, slot, offset, size;
9551 GList *vars = NULL, *l;
9552 StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
9556 scalar_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
9557 vtype_stack_slots = NULL;
9560 offsets = mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
9561 for (i = 0; i < cfg->num_varinfo; ++i)
9564 for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
9565 inst = cfg->varinfo [i];
9566 vmv = MONO_VARINFO (cfg, i);
9568 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
9571 vars = g_list_prepend (vars, vmv);
9574 vars = mono_varlist_sort (cfg, vars, 0);
9577 for (l = vars; l; l = l->next) {
9579 inst = cfg->varinfo [vmv->idx];
9581 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
9582 * pinvoke wrappers when they call functions returning structures */
9583 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF)
9584 size = mono_class_native_size (inst->inst_vtype->data.klass, &align);
9588 size = mono_type_size (inst->inst_vtype, &ialign);
9592 t = mono_type_get_underlying_type (inst->inst_vtype);
9594 slot_info = &scalar_stack_slots [MONO_TYPE_I];
9597 case MONO_TYPE_GENERICINST:
9598 if (!mono_type_generic_inst_is_valuetype (t)) {
9599 slot_info = &scalar_stack_slots [t->type];
9603 case MONO_TYPE_VALUETYPE:
9604 if (!vtype_stack_slots)
9605 vtype_stack_slots = mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * 256);
9606 for (i = 0; i < nvtypes; ++i)
9607 if (t->data.klass == vtype_stack_slots [i].vtype)
9610 slot_info = &vtype_stack_slots [i];
9612 g_assert (nvtypes < 256);
9613 vtype_stack_slots [nvtypes].vtype = t->data.klass;
9614 slot_info = &vtype_stack_slots [nvtypes];
9618 case MONO_TYPE_CLASS:
9619 case MONO_TYPE_OBJECT:
9620 case MONO_TYPE_ARRAY:
9621 case MONO_TYPE_SZARRAY:
9622 case MONO_TYPE_STRING:
9626 #if SIZEOF_VOID_P == 4
9631 /* Share non-float stack slots of the same size */
9632 slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
9635 slot_info = &scalar_stack_slots [t->type];
9640 if (cfg->comp_done & MONO_COMP_LIVENESS) {
9641 //printf ("START %2d %08x %08x\n", vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
9643 /* expire old intervals in active */
9644 while (slot_info->active) {
9645 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
9647 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
9650 //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);
9652 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
9653 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
9657 * This also handles the case when the variable is used in an
9658 * exception region, as liveness info is not computed there.
9661 * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
9664 if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
9665 if (slot_info->slots) {
9666 slot = GPOINTER_TO_INT (slot_info->slots->data);
9668 slot_info->slots = slot_info->slots->next;
9671 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
9676 static int count = 0;
9680 if (count == atoi (getenv ("COUNT")))
9681 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
9682 if (count > atoi (getenv ("COUNT")))
9685 mono_print_tree_nl (inst);
9690 if (cfg->disable_reuse_stack_slots)
9693 if (slot == 0xffffff) {
9695 * Allways allocate valuetypes to sizeof (gpointer) to allow more
9696 * efficient copying (and to work around the fact that OP_MEMCPY
9697 * and OP_MEMSET ignores alignment).
9699 if (MONO_TYPE_ISSTRUCT (t))
9700 align = sizeof (gpointer);
9704 offset += align - 1;
9705 offset &= ~(align - 1);
9709 offset += align - 1;
9710 offset &= ~(align - 1);
9715 if (*stack_align == 0)
9716 *stack_align = align;
9719 offsets [vmv->idx] = slot;
9722 for (i = 0; i < MONO_TYPE_PINNED; ++i) {
9723 if (scalar_stack_slots [i].active)
9724 g_list_free (scalar_stack_slots [i].active);
9726 for (i = 0; i < nvtypes; ++i) {
9727 if (vtype_stack_slots [i].active)
9728 g_list_free (vtype_stack_slots [i].active);
9731 mono_jit_stats.locals_stack_size += offset;
9733 *stack_size = offset;
9738 mono_allocate_stack_slots (MonoCompile *m, guint32 *stack_size, guint32 *stack_align)
9740 return mono_allocate_stack_slots_full (m, TRUE, stack_size, stack_align);
9744 mono_register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, gboolean no_throw)
9746 MonoJitICallInfo *info;
9747 MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
9749 if (!emul_opcode_map)
9750 emul_opcode_map = g_new0 (MonoJitICallInfo*, OP_LAST + 1);
9752 g_assert (!sig->hasthis);
9753 g_assert (sig->param_count < 3);
9755 info = mono_register_jit_icall (func, name, sig, no_throw);
9757 emul_opcode_map [opcode] = info;
9761 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
9763 MonoMethodSignature *sig;
9766 sig = mono_create_icall_signature (sigstr);
9770 mono_register_jit_icall (func, name, sig, save);
9774 decompose_foreach (MonoInst *tree, gpointer data)
9776 static MonoJitICallInfo *newarr_info = NULL;
9777 static MonoJitICallInfo *newarr_specific_info = NULL;
9778 MonoJitICallInfo *info;
9781 switch (tree->opcode) {
9783 MonoCompile *cfg = data;
9784 MonoInst *iargs [3];
9787 newarr_info = mono_find_jit_icall_by_addr (mono_array_new);
9788 g_assert (newarr_info);
9789 newarr_specific_info = mono_find_jit_icall_by_addr (mono_array_new_specific);
9790 g_assert (newarr_specific_info);
9793 if (cfg->opt & MONO_OPT_SHARED) {
9794 NEW_DOMAINCONST (cfg, iargs [0]);
9795 NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
9796 iargs [2] = tree->inst_newa_len;
9801 MonoVTable *vtable = mono_class_vtable (cfg->domain, mono_array_class_get (tree->inst_newa_class, 1));
9804 NEW_VTABLECONST (cfg, iargs [0], vtable);
9805 iargs [1] = tree->inst_newa_len;
9807 info = newarr_specific_info;
9810 mono_emulate_opcode (cfg, tree, iargs, info);
9812 /* Need to decompose arguments after the the opcode is decomposed */
9813 for (i = 0; i < info->sig->param_count; ++i)
9814 dec_foreach (iargs [i], cfg);
9817 #ifdef MONO_ARCH_SOFT_FLOAT
9828 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
9829 MonoCompile *cfg = data;
9830 MonoInst *iargs [2];
9832 iargs [0] = tree->inst_i0;
9833 iargs [1] = tree->inst_i1;
9835 mono_emulate_opcode (cfg, tree, iargs, info);
9837 dec_foreach (iargs [0], cfg);
9838 dec_foreach (iargs [1], cfg);
9841 g_assert_not_reached ();
9850 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
9851 MonoCompile *cfg = data;
9852 MonoInst *iargs [2];
9854 /* the args are in the compare opcode ... */
9855 iargs [0] = tree->inst_i0;
9856 iargs [1] = tree->inst_i1;
9858 mono_emulate_opcode (cfg, tree, iargs, info);
9860 dec_foreach (iargs [0], cfg);
9861 dec_foreach (iargs [1], cfg);
9864 g_assert_not_reached ();
9876 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
9878 switch (mono_burg_arity [tree->opcode]) {
9881 mono_inst_foreach (tree->inst_left, func, data);
9884 mono_inst_foreach (tree->inst_left, func, data);
9885 mono_inst_foreach (tree->inst_right, func, data);
9888 g_assert_not_reached ();
9895 mono_print_bb_code (MonoBasicBlock *bb)
9899 MONO_BB_FOR_EACH_INS (bb, c) {
9900 mono_print_tree (c);
9906 print_dfn (MonoCompile *cfg) {
9911 g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
9913 for (i = 0; i < cfg->num_bblocks; ++i) {
9916 bb = cfg->bblocks [i];
9917 /*if (bb->cil_code) {
9918 char* code1, *code2;
9919 code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
9920 if (bb->last_ins->cil_code)
9921 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
9923 code2 = g_strdup ("");
9925 code1 [strlen (code1) - 1] = 0;
9926 code = g_strdup_printf ("%s -> %s", code1, code2);
9930 code = g_strdup ("\n");
9931 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
9932 MONO_BB_FOR_EACH_INS (bb, c) {
9933 mono_print_tree (c);
9937 g_print ("\tprev:");
9938 for (j = 0; j < bb->in_count; ++j) {
9939 g_print (" BB%d", bb->in_bb [j]->block_num);
9941 g_print ("\t\tsucc:");
9942 for (j = 0; j < bb->out_count; ++j) {
9943 g_print (" BB%d", bb->out_bb [j]->block_num);
9945 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
9948 g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
9951 mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
9953 mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
9961 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
9963 MONO_ADD_INS (bb, inst);
9967 mono_destroy_compile (MonoCompile *cfg)
9969 //mono_mempool_stats (cfg->mempool);
9970 mono_free_loop_info (cfg);
9972 mono_regstate_free (cfg->rs);
9974 g_hash_table_destroy (cfg->spvars);
9976 g_hash_table_destroy (cfg->exvars);
9977 mono_mempool_destroy (cfg->mempool);
9978 g_list_free (cfg->ldstr_list);
9979 g_hash_table_destroy (cfg->token_info_hash);
9981 g_free (cfg->varinfo);
9983 g_free (cfg->exception_message);
9987 #ifdef HAVE_KW_THREAD
9988 static __thread gpointer mono_lmf_addr MONO_TLS_FAST;
9989 #ifdef MONO_ARCH_ENABLE_MONO_LMF_VAR
9991 * When this is defined, the current lmf is stored in this tls variable instead of in
9994 static __thread gpointer mono_lmf MONO_TLS_FAST;
9999 mono_get_jit_tls_key (void)
10001 return mono_jit_tls_id;
10005 mono_get_jit_tls_offset (void)
10007 #ifdef HAVE_KW_THREAD
10009 MONO_THREAD_VAR_OFFSET (mono_jit_tls, offset);
10017 mono_get_lmf_tls_offset (void)
10019 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
10021 MONO_THREAD_VAR_OFFSET(mono_lmf,offset);
10029 mono_get_lmf_addr_tls_offset (void)
10032 MONO_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
10037 mono_get_lmf (void)
10039 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
10042 MonoJitTlsData *jit_tls;
10044 if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
10045 return jit_tls->lmf;
10047 g_assert_not_reached ();
10053 mono_get_lmf_addr (void)
10055 #ifdef HAVE_KW_THREAD
10056 return mono_lmf_addr;
10058 MonoJitTlsData *jit_tls;
10060 if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
10061 return &jit_tls->lmf;
10063 g_assert_not_reached ();
10068 /* Called by native->managed wrappers */
10070 mono_jit_thread_attach (MonoDomain *domain)
10072 #ifdef HAVE_KW_THREAD
10073 if (!mono_lmf_addr) {
10074 mono_thread_attach (domain);
10077 if (!TlsGetValue (mono_jit_tls_id))
10078 mono_thread_attach (domain);
10080 if (mono_domain_get () != domain)
10081 mono_domain_set (domain, TRUE);
10085 * mono_thread_abort:
10086 * @obj: exception object
10088 * abort the thread, print exception information and stack trace
10091 mono_thread_abort (MonoObject *obj)
10093 /* MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id); */
10095 /* handle_remove should be eventually called for this thread, too
10096 g_free (jit_tls);*/
10098 if ((mono_runtime_unhandled_exception_policy_get () == MONO_UNHANLED_POLICY_LEGACY) ||
10099 (obj->vtable->klass == mono_defaults.threadabortexception_class)) {
10100 mono_thread_exit ();
10102 exit (mono_environment_exitcode_get ());
10107 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
10109 MonoJitTlsData *jit_tls;
10112 jit_tls = TlsGetValue (mono_jit_tls_id);
10116 jit_tls = g_new0 (MonoJitTlsData, 1);
10118 TlsSetValue (mono_jit_tls_id, jit_tls);
10120 #ifdef HAVE_KW_THREAD
10121 mono_jit_tls = jit_tls;
10124 jit_tls->abort_func = abort_func;
10125 jit_tls->end_of_stack = stack_start;
10127 lmf = g_new0 (MonoLMF, 1);
10128 #ifdef MONO_ARCH_INIT_TOP_LMF_ENTRY
10129 MONO_ARCH_INIT_TOP_LMF_ENTRY (lmf);
10134 jit_tls->first_lmf = lmf;
10136 #if defined(HAVE_KW_THREAD) && defined(MONO_ARCH_ENABLE_MONO_LMF_VAR)
10137 /* jit_tls->lmf is unused */
10139 mono_lmf_addr = &mono_lmf;
10141 #if defined(HAVE_KW_THREAD)
10142 mono_lmf_addr = &jit_tls->lmf;
10145 jit_tls->lmf = lmf;
10148 mono_arch_setup_jit_tls_data (jit_tls);
10149 mono_setup_altstack (jit_tls);
10155 mono_thread_start_cb (gsize tid, gpointer stack_start, gpointer func)
10157 MonoThread *thread;
10158 void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
10159 thread = mono_thread_current ();
10160 mono_debugger_thread_created (tid, thread, jit_tls);
10162 thread->jit_data = jit_tls;
10165 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
10168 mono_thread_abort_dummy (MonoObject *obj)
10170 if (mono_thread_attach_aborted_cb)
10171 mono_thread_attach_aborted_cb (obj);
10173 mono_thread_abort (obj);
10177 mono_thread_attach_cb (gsize tid, gpointer stack_start)
10179 MonoThread *thread;
10180 void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
10181 thread = mono_thread_current ();
10182 mono_debugger_thread_created (tid, thread, (MonoJitTlsData *) jit_tls);
10184 thread->jit_data = jit_tls;
10185 if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
10186 setup_stat_profiler ();
10190 mini_thread_cleanup (MonoThread *thread)
10192 MonoJitTlsData *jit_tls = thread->jit_data;
10195 mono_debugger_thread_cleanup (jit_tls);
10196 mono_arch_free_jit_tls_data (jit_tls);
10198 mono_free_altstack (jit_tls);
10199 g_free (jit_tls->first_lmf);
10201 thread->jit_data = NULL;
10202 TlsSetValue (mono_jit_tls_id, NULL);
10207 mono_create_tls_get (MonoCompile *cfg, int offset)
10209 #ifdef MONO_ARCH_HAVE_TLS_GET
10215 MONO_INST_NEW (cfg, ins, OP_TLS_GET);
10216 ins->dreg = mono_regstate_next_int (cfg->rs);
10217 ins->inst_offset = offset;
10225 mono_get_jit_tls_intrinsic (MonoCompile *cfg)
10227 return mono_create_tls_get (cfg, mono_get_jit_tls_offset ());
10231 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
10233 MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
10237 ji->data.target = target;
10238 ji->next = cfg->patch_info;
10240 cfg->patch_info = ji;
10244 mono_remove_patch_info (MonoCompile *cfg, int ip)
10246 MonoJumpInfo **ji = &cfg->patch_info;
10249 if ((*ji)->ip.i == ip)
10252 ji = &((*ji)->next);
10257 * mono_patch_info_dup_mp:
10259 * Make a copy of PATCH_INFO, allocating memory from the mempool MP.
10262 mono_patch_info_dup_mp (MonoMemPool *mp, MonoJumpInfo *patch_info)
10264 MonoJumpInfo *res = mono_mempool_alloc (mp, sizeof (MonoJumpInfo));
10265 memcpy (res, patch_info, sizeof (MonoJumpInfo));
10267 switch (patch_info->type) {
10268 case MONO_PATCH_INFO_RVA:
10269 case MONO_PATCH_INFO_LDSTR:
10270 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
10271 case MONO_PATCH_INFO_LDTOKEN:
10272 case MONO_PATCH_INFO_DECLSEC:
10273 res->data.token = mono_mempool_alloc (mp, sizeof (MonoJumpInfoToken));
10274 memcpy (res->data.token, patch_info->data.token, sizeof (MonoJumpInfoToken));
10276 case MONO_PATCH_INFO_SWITCH:
10277 res->data.table = mono_mempool_alloc (mp, sizeof (MonoJumpInfoBBTable));
10278 memcpy (res->data.table, patch_info->data.table, sizeof (MonoJumpInfoBBTable));
10288 mono_patch_info_hash (gconstpointer data)
10290 const MonoJumpInfo *ji = (MonoJumpInfo*)data;
10292 switch (ji->type) {
10293 case MONO_PATCH_INFO_RVA:
10294 case MONO_PATCH_INFO_LDSTR:
10295 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
10296 case MONO_PATCH_INFO_LDTOKEN:
10297 case MONO_PATCH_INFO_DECLSEC:
10298 return (ji->type << 8) | ji->data.token->token;
10299 case MONO_PATCH_INFO_VTABLE:
10300 case MONO_PATCH_INFO_CLASS:
10301 case MONO_PATCH_INFO_IID:
10302 case MONO_PATCH_INFO_ADJUSTED_IID:
10303 return (ji->type << 8) | (gssize)ji->data.klass;
10304 case MONO_PATCH_INFO_FIELD:
10305 case MONO_PATCH_INFO_SFLDA:
10306 return (ji->type << 8) | (gssize)ji->data.field;
10307 case MONO_PATCH_INFO_METHODCONST:
10308 case MONO_PATCH_INFO_METHOD:
10309 case MONO_PATCH_INFO_METHOD_JUMP:
10310 return (ji->type << 8) | (gssize)ji->data.method;
10311 case MONO_PATCH_INFO_IMAGE:
10312 return (ji->type << 8) | (gssize)ji->data.image;
10314 return (ji->type << 8);
10319 * mono_patch_info_equal:
10321 * This might fail to recognize equivalent patches, i.e. floats, so its only
10322 * usable in those cases where this is not a problem, i.e. sharing GOT slots
10326 mono_patch_info_equal (gconstpointer ka, gconstpointer kb)
10328 const MonoJumpInfo *ji1 = (MonoJumpInfo*)ka;
10329 const MonoJumpInfo *ji2 = (MonoJumpInfo*)kb;
10331 if (ji1->type != ji2->type)
10334 switch (ji1->type) {
10335 case MONO_PATCH_INFO_RVA:
10336 case MONO_PATCH_INFO_LDSTR:
10337 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
10338 case MONO_PATCH_INFO_LDTOKEN:
10339 case MONO_PATCH_INFO_DECLSEC:
10340 if ((ji1->data.token->image != ji2->data.token->image) ||
10341 (ji1->data.token->token != ji2->data.token->token))
10345 if (ji1->data.name != ji2->data.name)
10354 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
10356 unsigned char *ip = patch_info->ip.i + code;
10357 gconstpointer target = NULL;
10359 switch (patch_info->type) {
10360 case MONO_PATCH_INFO_BB:
10361 target = patch_info->data.bb->native_offset + code;
10363 case MONO_PATCH_INFO_ABS:
10364 target = patch_info->data.target;
10366 case MONO_PATCH_INFO_LABEL:
10367 target = patch_info->data.inst->inst_c0 + code;
10369 case MONO_PATCH_INFO_IP:
10372 case MONO_PATCH_INFO_METHOD_REL:
10373 target = code + patch_info->data.offset;
10375 case MONO_PATCH_INFO_INTERNAL_METHOD: {
10376 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
10378 g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
10379 g_assert_not_reached ();
10381 target = mono_icall_get_wrapper (mi);
10384 case MONO_PATCH_INFO_METHOD_JUMP: {
10387 /* get the trampoline to the method from the domain */
10388 target = mono_create_jump_trampoline (domain, patch_info->data.method, TRUE);
10389 if (!domain->jump_target_hash)
10390 domain->jump_target_hash = g_hash_table_new (NULL, NULL);
10391 list = g_hash_table_lookup (domain->jump_target_hash, patch_info->data.method);
10392 list = g_slist_prepend (list, ip);
10393 g_hash_table_insert (domain->jump_target_hash, patch_info->data.method, list);
10396 case MONO_PATCH_INFO_METHOD:
10397 if (patch_info->data.method == method) {
10400 /* get the trampoline to the method from the domain */
10401 if (method && method->wrapper_type == MONO_WRAPPER_STATIC_RGCTX_INVOKE)
10402 target = mono_ldftn_nosync (patch_info->data.method);
10404 target = mono_create_jit_trampoline (patch_info->data.method);
10407 case MONO_PATCH_INFO_SWITCH: {
10408 gpointer *jump_table;
10411 if (method && method->dynamic) {
10412 jump_table = mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
10414 mono_domain_lock (domain);
10415 jump_table = mono_code_manager_reserve (domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
10416 mono_domain_unlock (domain);
10419 for (i = 0; i < patch_info->data.table->table_size; i++) {
10420 jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
10422 target = jump_table;
10425 case MONO_PATCH_INFO_METHODCONST:
10426 case MONO_PATCH_INFO_CLASS:
10427 case MONO_PATCH_INFO_IMAGE:
10428 case MONO_PATCH_INFO_FIELD:
10429 target = patch_info->data.target;
10431 case MONO_PATCH_INFO_IID:
10432 mono_class_init (patch_info->data.klass);
10433 target = GINT_TO_POINTER ((int)patch_info->data.klass->interface_id);
10435 case MONO_PATCH_INFO_ADJUSTED_IID:
10436 mono_class_init (patch_info->data.klass);
10437 target = GINT_TO_POINTER ((int)(-((patch_info->data.klass->interface_id + 1) * SIZEOF_VOID_P)));
10439 case MONO_PATCH_INFO_VTABLE:
10440 target = mono_class_vtable (domain, patch_info->data.klass);
10443 case MONO_PATCH_INFO_CLASS_INIT: {
10444 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.klass);
10447 target = mono_create_class_init_trampoline (vtable);
10450 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
10451 target = mono_create_delegate_trampoline (patch_info->data.klass);
10453 case MONO_PATCH_INFO_SFLDA: {
10454 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
10457 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && (method && mono_class_needs_cctor_run (vtable->klass, method)))
10458 /* Done by the generated code */
10462 mono_runtime_class_init (vtable);
10464 target = (char*)vtable->data + patch_info->data.field->offset;
10467 case MONO_PATCH_INFO_RVA:
10468 target = mono_image_rva_map (patch_info->data.token->image, patch_info->data.token->token);
10470 case MONO_PATCH_INFO_R4:
10471 case MONO_PATCH_INFO_R8:
10472 target = patch_info->data.target;
10474 case MONO_PATCH_INFO_EXC_NAME:
10475 target = patch_info->data.name;
10477 case MONO_PATCH_INFO_LDSTR:
10479 mono_ldstr (domain, patch_info->data.token->image,
10480 mono_metadata_token_index (patch_info->data.token->token));
10482 case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
10484 MonoClass *handle_class;
10486 handle = mono_ldtoken (patch_info->data.token->image,
10487 patch_info->data.token->token, &handle_class, NULL);
10488 mono_class_init (handle_class);
10489 mono_class_init (mono_class_from_mono_type (handle));
10492 mono_type_get_object (domain, handle);
10495 case MONO_PATCH_INFO_LDTOKEN: {
10497 MonoClass *handle_class;
10499 handle = mono_ldtoken (patch_info->data.token->image,
10500 patch_info->data.token->token, &handle_class, NULL);
10501 mono_class_init (handle_class);
10506 case MONO_PATCH_INFO_DECLSEC:
10507 target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
10509 case MONO_PATCH_INFO_ICALL_ADDR:
10510 target = mono_lookup_internal_call (patch_info->data.method);
10512 case MONO_PATCH_INFO_BB_OVF:
10513 case MONO_PATCH_INFO_EXC_OVF:
10514 case MONO_PATCH_INFO_GOT_OFFSET:
10515 case MONO_PATCH_INFO_NONE:
10518 g_assert_not_reached ();
10521 return (gpointer)target;
10525 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
10526 MonoJitICallInfo *info;
10528 decompose_foreach (tree, cfg);
10530 switch (mono_burg_arity [tree->opcode]) {
10533 dec_foreach (tree->inst_left, cfg);
10535 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
10536 MonoInst *iargs [2];
10538 iargs [0] = tree->inst_left;
10540 mono_emulate_opcode (cfg, tree, iargs, info);
10546 #ifdef MONO_ARCH_BIGMUL_INTRINS
10547 if (tree->opcode == OP_LMUL
10548 && (cfg->opt & MONO_OPT_INTRINS)
10549 && (tree->inst_left->opcode == CEE_CONV_I8
10550 || tree->inst_left->opcode == CEE_CONV_U8)
10551 && tree->inst_left->inst_left->type == STACK_I4
10552 && (tree->inst_right->opcode == CEE_CONV_I8
10553 || tree->inst_right->opcode == CEE_CONV_U8)
10554 && tree->inst_right->inst_left->type == STACK_I4
10555 && tree->inst_left->opcode == tree->inst_right->opcode) {
10556 tree->opcode = (tree->inst_left->opcode == CEE_CONV_I8 ? OP_BIGMUL: OP_BIGMUL_UN);
10557 tree->inst_left = tree->inst_left->inst_left;
10558 tree->inst_right = tree->inst_right->inst_left;
10559 dec_foreach (tree, cfg);
10562 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
10563 MonoInst *iargs [2];
10565 iargs [0] = tree->inst_i0;
10566 iargs [1] = tree->inst_i1;
10568 mono_emulate_opcode (cfg, tree, iargs, info);
10570 dec_foreach (iargs [0], cfg);
10571 dec_foreach (iargs [1], cfg);
10574 dec_foreach (tree->inst_left, cfg);
10575 dec_foreach (tree->inst_right, cfg);
10579 g_assert_not_reached ();
10584 decompose_pass (MonoCompile *cfg) {
10585 MonoBasicBlock *bb;
10587 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
10590 cfg->prev_ins = NULL;
10591 MONO_BB_FOR_EACH_INS (cfg->cbb, tree) {
10592 dec_foreach (tree, cfg);
10593 cfg->prev_ins = tree;
10599 nullify_basic_block (MonoBasicBlock *bb)
10605 bb->next_bb = NULL;
10606 MONO_INST_LIST_INIT (&bb->ins_list);
10607 bb->cil_code = NULL;
10611 replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
10615 for (i = 0; i < bb->out_count; i++) {
10616 MonoBasicBlock *ob = bb->out_bb [i];
10619 if (bb->out_count > 1) {
10620 bb->out_bb [i] = bb->out_bb [bb->out_count - 1];
10624 bb->out_bb [i] = repl;
10631 replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
10635 for (i = 0; i < bb->in_count; i++) {
10636 MonoBasicBlock *ib = bb->in_bb [i];
10639 if (bb->in_count > 1) {
10640 bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
10644 bb->in_bb [i] = repl;
10651 replace_out_block_in_code (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl) {
10654 MONO_BB_FOR_EACH_INS (bb, inst) {
10655 if (inst->opcode == OP_CALL_HANDLER) {
10656 if (inst->inst_target_bb == orig)
10657 inst->inst_target_bb = repl;
10661 inst = mono_inst_list_last (&bb->ins_list);
10665 switch (inst->opcode) {
10667 if (inst->inst_target_bb == orig)
10668 inst->inst_target_bb = repl;
10672 int n = GPOINTER_TO_INT (inst->klass);
10673 for (i = 0; i < n; i++ ) {
10674 if (inst->inst_many_bb [i] == orig)
10675 inst->inst_many_bb [i] = repl;
10689 if (inst->inst_true_bb == orig)
10690 inst->inst_true_bb = repl;
10691 if (inst->inst_false_bb == orig)
10692 inst->inst_false_bb = repl;
10700 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
10704 for (i = 0; i < bb->out_count; i++) {
10705 MonoBasicBlock *ob = bb->out_bb [i];
10706 for (j = 0; j < ob->in_count; j++) {
10707 if (ob->in_bb [j] == orig) {
10708 ob->in_bb [j] = repl;
10716 * Check if a bb is useless (is just made of NOPs and ends with an
10717 * unconditional branch, or nothing).
10718 * If it is so, unlink it from the CFG and nullify it, and return TRUE.
10719 * Otherwise, return FALSE;
10722 remove_block_if_useless (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *previous_bb) {
10723 MonoBasicBlock *target_bb = NULL;
10726 /* Do not touch handlers */
10727 if (bb->region != -1) {
10728 bb->not_useless = TRUE;
10732 MONO_BB_FOR_EACH_INS (bb, inst) {
10733 switch (inst->opcode) {
10737 target_bb = inst->inst_target_bb;
10740 bb->not_useless = TRUE;
10745 if (target_bb == NULL) {
10746 if ((bb->out_count == 1) && (bb->out_bb [0] == bb->next_bb)) {
10747 target_bb = bb->next_bb;
10749 /* Do not touch empty BBs that do not "fall through" to their next BB (like the exit BB) */
10754 /* Do not touch BBs following a switch (they are the "default" branch) */
10755 inst = mono_inst_list_last (&previous_bb->ins_list);
10756 if (inst && inst->opcode == OP_SWITCH)
10759 /* Do not touch BBs following the entry BB and jumping to something that is not */
10760 /* thiry "next" bb (the entry BB cannot contain the branch) */
10761 if ((previous_bb == cfg->bb_entry) && (bb->next_bb != target_bb)) {
10766 * Do not touch BBs following a try block as the code in
10767 * mini_method_compile needs them to compute the length of the try block.
10769 if (MONO_BBLOCK_IS_IN_REGION (previous_bb, MONO_REGION_TRY))
10772 /* Check that there is a target BB, and that bb is not an empty loop (Bug 75061) */
10773 if ((target_bb != NULL) && (target_bb != bb)) {
10774 MonoInst *last_ins;
10777 if (cfg->verbose_level > 1) {
10778 printf ("remove_block_if_useless, removed BB%d\n", bb->block_num);
10781 /* unlink_bblock () modifies the bb->in_bb array so can't use a for loop here */
10782 while (bb->in_count) {
10783 MonoBasicBlock *in_bb = bb->in_bb [0];
10784 mono_unlink_bblock (cfg, in_bb, bb);
10785 link_bblock (cfg, in_bb, target_bb);
10786 replace_out_block_in_code (in_bb, bb, target_bb);
10789 mono_unlink_bblock (cfg, bb, target_bb);
10791 last_ins = mono_inst_list_last (&previous_bb->ins_list);
10793 if ((previous_bb != cfg->bb_entry) &&
10794 (previous_bb->region == bb->region) &&
10795 ((last_ins == NULL) ||
10796 ((last_ins->opcode != OP_BR) &&
10797 (!(MONO_IS_COND_BRANCH_OP (last_ins))) &&
10798 (last_ins->opcode != OP_SWITCH)))) {
10799 for (i = 0; i < previous_bb->out_count; i++) {
10800 if (previous_bb->out_bb [i] == target_bb) {
10802 MONO_INST_NEW (cfg, jump, OP_BR);
10803 MONO_ADD_INS (previous_bb, jump);
10804 jump->cil_code = previous_bb->cil_code;
10805 jump->inst_target_bb = target_bb;
10811 previous_bb->next_bb = bb->next_bb;
10812 nullify_basic_block (bb);
10821 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn)
10823 MonoInst *last_ins;
10825 bb->out_count = bbn->out_count;
10826 bb->out_bb = bbn->out_bb;
10828 replace_basic_block (bb, bbn, bb);
10830 last_ins = mono_inst_list_last (&bb->ins_list);
10832 /* Nullify branch at the end of bb */
10833 if (last_ins && MONO_IS_BRANCH_OP (last_ins))
10834 last_ins->opcode = OP_NOP;
10836 MONO_INST_LIST_SPLICE_TAIL_INIT (&bbn->ins_list, &bb->ins_list);
10838 bb->next_bb = bbn->next_bb;
10839 nullify_basic_block (bbn);
10843 move_basic_block_to_end (MonoCompile *cfg, MonoBasicBlock *bb)
10845 MonoBasicBlock *bbn, *next;
10846 MonoInst *last_ins;
10848 next = bb->next_bb;
10850 /* Find the previous */
10851 for (bbn = cfg->bb_entry; bbn->next_bb && bbn->next_bb != bb; bbn = bbn->next_bb)
10853 if (bbn->next_bb) {
10854 bbn->next_bb = bb->next_bb;
10857 /* Find the last */
10858 for (bbn = cfg->bb_entry; bbn->next_bb; bbn = bbn->next_bb)
10861 bb->next_bb = NULL;
10863 last_ins = mono_inst_list_last (&bb->ins_list);
10866 if (next && (!last_ins || (last_ins->opcode != OP_NOT_REACHED))) {
10869 MONO_INST_NEW (cfg, ins, OP_BR);
10870 MONO_ADD_INS (bb, ins);
10871 link_bblock (cfg, bb, next);
10872 ins->inst_target_bb = next;
10876 /* checks that a and b represent the same instructions, conservatively,
10877 * it can return FALSE also for two trees that are equal.
10878 * FIXME: also make sure there are no side effects.
10881 same_trees (MonoInst *a, MonoInst *b)
10884 if (a->opcode != b->opcode)
10886 arity = mono_burg_arity [a->opcode];
10888 if (a->ssa_op == b->ssa_op && a->ssa_op == MONO_SSA_LOAD && a->inst_i0 == b->inst_i0)
10890 return same_trees (a->inst_left, b->inst_left);
10891 } else if (arity == 2) {
10892 return same_trees (a->inst_left, b->inst_left) && same_trees (a->inst_right, b->inst_right);
10893 } else if (arity == 0) {
10894 switch (a->opcode) {
10896 return a->inst_c0 == b->inst_c0;
10905 get_unsigned_condbranch (int opcode)
10908 case CEE_BLE: return CEE_BLE_UN;
10909 case CEE_BLT: return CEE_BLT_UN;
10910 case CEE_BGE: return CEE_BGE_UN;
10911 case CEE_BGT: return CEE_BGT_UN;
10913 g_assert_not_reached ();
10918 tree_is_unsigned (MonoInst* ins) {
10919 switch (ins->opcode) {
10921 return (int)ins->inst_c0 >= 0;
10922 /* array lengths are positive as are string sizes */
10929 case CEE_CONV_OVF_U1:
10930 case CEE_CONV_OVF_U2:
10931 case CEE_CONV_OVF_U4:
10942 /* check if an unsigned compare can be used instead of two signed compares
10943 * for (val < 0 || val > limit) conditionals.
10944 * Returns TRUE if the optimization has been applied.
10945 * Note that this can't be applied if the second arg is not positive...
10948 try_unsigned_compare (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *bb_last)
10950 MonoBasicBlock *truet, *falset;
10951 MonoInst *cmp_inst = bb_last->inst_left;
10953 if (!cmp_inst->inst_right->inst_c0 == 0)
10955 truet = bb_last->inst_true_bb;
10956 falset = bb_last->inst_false_bb;
10957 if (falset->in_count != 1)
10959 condb = mono_inst_list_last (&falset->ins_list);
10960 /* target bb must have one instruction */
10961 if (!condb || (condb->node.next != &falset->ins_list))
10963 if ((((condb->opcode == CEE_BLE || condb->opcode == CEE_BLT) && (condb->inst_false_bb == truet))
10964 || ((condb->opcode == CEE_BGE || condb->opcode == CEE_BGT) && (condb->inst_true_bb == truet)))
10965 && same_trees (cmp_inst->inst_left, condb->inst_left->inst_left)) {
10966 if (!tree_is_unsigned (condb->inst_left->inst_right))
10968 condb->opcode = get_unsigned_condbranch (condb->opcode);
10969 /* change the original condbranch to just point to the new unsigned check */
10970 bb_last->opcode = OP_BR;
10971 bb_last->inst_target_bb = falset;
10972 replace_out_block (bb, truet, NULL);
10973 replace_in_block (truet, bb, NULL);
10980 * Optimizes the branches on the Control Flow Graph
10984 optimize_branches (MonoCompile *cfg)
10986 int i, changed = FALSE;
10987 MonoBasicBlock *bb, *bbn;
10988 guint32 niterations;
10991 * Some crazy loops could cause the code below to go into an infinite
10992 * loop, see bug #53003 for an example. To prevent this, we put an upper
10993 * bound on the number of iterations.
10995 if (cfg->num_bblocks > 1000)
10996 niterations = cfg->num_bblocks * 2;
10998 niterations = 1000;
11001 MonoBasicBlock *previous_bb;
11005 /* we skip the entry block (exit is handled specially instead ) */
11006 for (previous_bb = cfg->bb_entry, bb = cfg->bb_entry->next_bb; bb; previous_bb = bb, bb = bb->next_bb) {
11007 MonoInst *last_ins;
11009 /* dont touch code inside exception clauses */
11010 if (bb->region != -1)
11013 if (!bb->not_useless && remove_block_if_useless (cfg, bb, previous_bb)) {
11018 if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
11019 if (cfg->verbose_level > 2)
11020 g_print ("nullify block triggered %d\n", bbn->block_num);
11022 bb->next_bb = bbn->next_bb;
11024 for (i = 0; i < bbn->out_count; i++)
11025 replace_in_block (bbn->out_bb [i], bbn, NULL);
11027 nullify_basic_block (bbn);
11031 last_ins = mono_inst_list_last (&bb->ins_list);
11032 if (bb->out_count == 1) {
11033 bbn = bb->out_bb [0];
11035 /* conditional branches where true and false targets are the same can be also replaced with OP_BR */
11036 if (last_ins && MONO_IS_COND_BRANCH_OP (last_ins)) {
11038 MONO_INST_NEW (cfg, pop, CEE_POP);
11039 pop->inst_left = last_ins->inst_left->inst_left;
11040 mono_add_ins_to_end (bb, pop);
11041 MONO_INST_NEW (cfg, pop, CEE_POP);
11042 pop->inst_left = last_ins->inst_left->inst_right;
11043 mono_add_ins_to_end (bb, pop);
11044 last_ins->opcode = OP_BR;
11045 last_ins->inst_target_bb = last_ins->inst_true_bb;
11047 if (cfg->verbose_level > 2)
11048 g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count);
11051 if (bb->region == bbn->region && bb->next_bb == bbn) {
11052 /* the block are in sequence anyway ... */
11054 /* branches to the following block can be removed */
11055 if (last_ins && last_ins->opcode == OP_BR) {
11056 last_ins->opcode = OP_NOP;
11058 if (cfg->verbose_level > 2)
11059 g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
11062 if (bbn->in_count == 1) {
11064 if (bbn != cfg->bb_exit) {
11065 if (cfg->verbose_level > 2)
11066 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
11067 merge_basic_blocks (bb, bbn);
11072 //mono_print_bb_code (bb);
11076 if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
11077 if (cfg->verbose_level > 2) {
11078 g_print ("nullify block triggered %d\n", bbn->block_num);
11080 bb->next_bb = bbn->next_bb;
11082 for (i = 0; i < bbn->out_count; i++)
11083 replace_in_block (bbn->out_bb [i], bbn, NULL);
11085 nullify_basic_block (bbn);
11090 if (bb->out_count == 1) {
11091 bbn = bb->out_bb [0];
11093 if (last_ins && last_ins->opcode == OP_BR) {
11094 MonoInst *bbn_code;
11096 bbn = last_ins->inst_target_bb;
11097 bbn_code = mono_inst_list_first (&bbn->ins_list);
11098 if (bb->region == bbn->region && bbn_code &&
11099 bbn_code->opcode == OP_BR &&
11100 bbn_code->inst_target_bb->region == bb->region) {
11101 if (cfg->verbose_level > 2)
11102 g_print ("in %s branch to branch triggered %d -> %d -> %d\n", cfg->method->name,
11103 bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num);
11105 replace_in_block (bbn, bb, NULL);
11106 replace_out_block (bb, bbn, bbn_code->inst_target_bb);
11107 link_bblock (cfg, bb, bbn_code->inst_target_bb);
11108 last_ins->inst_target_bb = bbn_code->inst_target_bb;
11113 } else if (bb->out_count == 2) {
11114 if (last_ins && MONO_IS_COND_BRANCH_NOFP (last_ins)) {
11115 int branch_result = mono_eval_cond_branch (last_ins);
11116 MonoBasicBlock *taken_branch_target = NULL, *untaken_branch_target = NULL;
11117 MonoInst *bbn_code;
11119 if (branch_result == BRANCH_TAKEN) {
11120 taken_branch_target = last_ins->inst_true_bb;
11121 untaken_branch_target = last_ins->inst_false_bb;
11122 } else if (branch_result == BRANCH_NOT_TAKEN) {
11123 taken_branch_target = last_ins->inst_false_bb;
11124 untaken_branch_target = last_ins->inst_true_bb;
11126 if (taken_branch_target) {
11127 /* if mono_eval_cond_branch () is ever taken to handle
11128 * non-constant values to compare, issue a pop here.
11130 last_ins->opcode = OP_BR;
11131 last_ins->inst_target_bb = taken_branch_target;
11132 mono_unlink_bblock (cfg, bb, untaken_branch_target);
11136 bbn = last_ins->inst_true_bb;
11137 bbn_code = mono_inst_list_first (&bbn->ins_list);
11138 if (bb->region == bbn->region && bbn_code && bbn_code->opcode == OP_BR &&
11139 bbn_code->inst_target_bb->region == bb->region) {
11140 if (cfg->verbose_level > 2)
11141 g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n",
11142 bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num,
11146 * Unlink, then relink bblocks to avoid various
11147 * tricky situations when the two targets of the branch
11148 * are equal, or will become equal after the change.
11150 mono_unlink_bblock (cfg, bb, last_ins->inst_true_bb);
11151 mono_unlink_bblock (cfg, bb, last_ins->inst_false_bb);
11153 last_ins->inst_true_bb = bbn_code->inst_target_bb;
11155 link_bblock (cfg, bb, last_ins->inst_true_bb);
11156 link_bblock (cfg, bb, last_ins->inst_false_bb);
11162 bbn = last_ins->inst_false_bb;
11163 bbn_code = mono_inst_list_first (&bbn->ins_list);
11164 if (bb->region == bbn->region && bbn_code && bbn_code->opcode == OP_BR &&
11165 bbn_code->inst_target_bb->region == bb->region) {
11166 if (cfg->verbose_level > 2)
11167 g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n",
11168 bb->block_num, bbn->block_num, bbn_code->inst_target_bb->block_num,
11171 mono_unlink_bblock (cfg, bb, last_ins->inst_true_bb);
11172 mono_unlink_bblock (cfg, bb, last_ins->inst_false_bb);
11174 last_ins->inst_false_bb = bbn_code->inst_target_bb;
11176 link_bblock (cfg, bb, last_ins->inst_true_bb);
11177 link_bblock (cfg, bb, last_ins->inst_false_bb);
11184 /* detect and optimize to unsigned compares checks like: if (v < 0 || v > limit */
11185 if (last_ins && last_ins->opcode == CEE_BLT && last_ins->inst_left->inst_right->opcode == OP_ICONST) {
11186 if (try_unsigned_compare (cfg, bb, last_ins)) {
11187 /*g_print ("applied in bb %d (->%d) %s\n", bb->block_num, last_ins->inst_target_bb->block_num, mono_method_full_name (cfg->method, TRUE));*/
11193 if (last_ins && MONO_IS_COND_BRANCH_NOFP (last_ins)) {
11194 if (last_ins->inst_false_bb->out_of_line && (bb->region == last_ins->inst_false_bb->region)) {
11195 /* Reverse the branch */
11196 last_ins->opcode = reverse_branch_op (last_ins->opcode);
11197 bbn = last_ins->inst_false_bb;
11198 last_ins->inst_false_bb = last_ins->inst_true_bb;
11199 last_ins->inst_true_bb = bbn;
11201 move_basic_block_to_end (cfg, last_ins->inst_true_bb);
11202 if (cfg->verbose_level > 2)
11203 g_print ("cbranch to throw block triggered %d.\n",
11209 } while (changed && (niterations > 0));
11214 mono_compile_create_vars (MonoCompile *cfg)
11216 MonoMethodSignature *sig;
11217 MonoMethodHeader *header;
11220 header = mono_method_get_header (cfg->method);
11222 sig = mono_method_signature (cfg->method);
11224 if (!MONO_TYPE_IS_VOID (sig->ret)) {
11225 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
11226 cfg->ret->opcode = OP_RETARG;
11227 cfg->ret->inst_vtype = sig->ret;
11228 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
11230 if (cfg->verbose_level > 2)
11231 g_print ("creating vars\n");
11233 cfg->args = mono_mempool_alloc0 (cfg->mempool, (sig->param_count + sig->hasthis) * sizeof (MonoInst*));
11236 cfg->args [0] = mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
11238 for (i = 0; i < sig->param_count; ++i) {
11239 cfg->args [i + sig->hasthis] = mono_compile_create_var (cfg, sig->params [i], OP_ARG);
11240 if (sig->params [i]->byref) {
11241 cfg->disable_ssa = TRUE;
11245 cfg->locals_start = cfg->num_varinfo;
11247 if (cfg->verbose_level > 2)
11248 g_print ("creating locals\n");
11250 for (i = 0; i < header->num_locals; ++i)
11251 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
11252 if (cfg->verbose_level > 2)
11253 g_print ("locals done\n");
11255 mono_arch_create_vars (cfg);
11259 mono_print_code (MonoCompile *cfg)
11261 MonoBasicBlock *bb;
11263 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11266 if (!MONO_INST_LIST_EMPTY (&bb->ins_list))
11267 g_print ("CODE BLOCK %d (nesting %d):\n",
11268 bb->block_num, bb->nesting);
11270 MONO_BB_FOR_EACH_INS (bb, tree) {
11271 mono_print_tree (tree);
11277 extern const char * const mono_burg_rule_string [];
11280 emit_state (MonoCompile *cfg, MBState *state, int goal)
11282 MBState *kids [10];
11283 int ern = mono_burg_rule (state, goal);
11284 const guint16 *nts = mono_burg_nts_data + mono_burg_nts [ern];
11286 //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
11290 // state->reg1 = state->reg2; /* chain rule */
11292 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
11295 state->reg1 = mono_regstate_next_int (cfg->rs);
11296 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
11298 case MB_NTERM_lreg:
11299 state->reg1 = mono_regstate_next_int (cfg->rs);
11300 state->reg2 = mono_regstate_next_int (cfg->rs);
11302 case MB_NTERM_freg:
11303 #ifdef MONO_ARCH_SOFT_FLOAT
11304 state->reg1 = mono_regstate_next_int (cfg->rs);
11305 state->reg2 = mono_regstate_next_int (cfg->rs);
11307 state->reg1 = mono_regstate_next_float (cfg->rs);
11311 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
11313 * Enabling this might cause bugs to surface in the local register
11314 * allocators on some architectures like x86.
11316 if ((state->tree->ssa_op == MONO_SSA_STORE) && (state->left->tree->opcode == OP_REGVAR)) {
11317 /* Do not optimize away reg-reg moves */
11318 if (! ((state->right->tree->ssa_op == MONO_SSA_LOAD) && (state->right->left->tree->opcode == OP_REGVAR))) {
11319 state->right->reg1 = state->left->tree->dreg;
11328 mono_burg_kids (state, ern, kids);
11330 emit_state (cfg, kids [0], nts [0]);
11332 emit_state (cfg, kids [1], nts [1]);
11334 emit_state (cfg, kids [2], nts [2]);
11336 g_assert (!nts [4]);
11337 emit_state (cfg, kids [3], nts [3]);
11343 // g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
11344 mono_burg_emit (ern, state, state->tree, cfg);
11347 #define DEBUG_SELECTION
11350 mini_select_instructions (MonoCompile *cfg)
11352 MonoBasicBlock *bb;
11354 cfg->state_pool = mono_mempool_new ();
11355 cfg->rs = mono_regstate_new ();
11357 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11358 MonoInst *last_ins = mono_inst_list_last (&bb->ins_list);
11360 if (last_ins && MONO_IS_COND_BRANCH_OP (last_ins) &&
11361 bb->next_bb != last_ins->inst_false_bb) {
11363 /* we are careful when inverting, since bugs like #59580
11364 * could show up when dealing with NaNs.
11366 if (MONO_IS_COND_BRANCH_NOFP(last_ins) && bb->next_bb == last_ins->inst_true_bb) {
11367 MonoBasicBlock *tmp = last_ins->inst_true_bb;
11368 last_ins->inst_true_bb = last_ins->inst_false_bb;
11369 last_ins->inst_false_bb = tmp;
11371 last_ins->opcode = reverse_branch_op (last_ins->opcode);
11373 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
11374 inst->opcode = OP_BR;
11375 inst->inst_target_bb = last_ins->inst_false_bb;
11376 mono_bblock_add_inst (bb, inst);
11381 #ifdef DEBUG_SELECTION
11382 if (cfg->verbose_level >= 4) {
11383 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11385 g_print ("DUMP BLOCK %d:\n", bb->block_num);
11387 MONO_BB_FOR_EACH_INS (bb, tree) {
11388 mono_print_tree (tree);
11395 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11396 MonoInst *tree, *n;
11400 MONO_INST_LIST_INIT (&head);
11401 if (MONO_INST_LIST_EMPTY (&bb->ins_list))
11403 MONO_INST_LIST_SPLICE_INIT (&bb->ins_list, &head);
11406 mono_regstate_reset (cfg->rs);
11408 #ifdef DEBUG_SELECTION
11409 if (cfg->verbose_level >= 3)
11410 g_print ("LABEL BLOCK %d:\n", bb->block_num);
11412 MONO_INST_LIST_FOR_EACH_ENTRY_SAFE (tree, n, &head, node) {
11413 #ifdef DEBUG_SELECTION
11414 if (cfg->verbose_level >= 3) {
11415 mono_print_tree (tree);
11420 cfg->ip = tree->cil_code;
11421 if (!(mbstate = mono_burg_label (tree, cfg))) {
11422 g_warning ("unable to label tree %p", tree);
11423 mono_print_tree (tree);
11425 g_assert_not_reached ();
11427 emit_state (cfg, mbstate, MB_NTERM_stmt);
11429 bb->max_vreg = cfg->rs->next_vreg;
11431 mono_mempool_empty (cfg->state_pool);
11433 mono_mempool_destroy (cfg->state_pool);
11439 * mono_normalize_opcodes:
11441 * Replace CEE_ and OP_ opcodes with the corresponding OP_I or OP_L opcodes.
11444 static gint16 *remap_table;
11446 #if SIZEOF_VOID_P == 8
11447 #define REMAP_OPCODE(opcode) OP_L ## opcode
11449 #define REMAP_OPCODE(opcode) OP_I ## opcode
11452 static G_GNUC_UNUSED void
11453 mono_normalize_opcodes (MonoCompile *cfg, MonoBasicBlock *bb)
11457 if (!remap_table) {
11458 remap_table = g_new0 (gint16, OP_LAST);
11460 #if SIZEOF_VOID_P == 8
11461 remap_table [CEE_CONV_U8] = OP_ZEXT_I4;
11462 remap_table [CEE_CONV_U] = OP_ZEXT_I4;
11463 remap_table [CEE_CONV_I8] = OP_SEXT_I4;
11464 remap_table [CEE_CONV_I] = OP_SEXT_I4;
11465 remap_table [CEE_CONV_OVF_U4] = OP_LCONV_TO_OVF_U4;
11466 remap_table [CEE_CONV_OVF_I4_UN] = OP_LCONV_TO_OVF_I4_UN;
11469 remap_table [CEE_CONV_R4] = OP_ICONV_TO_R4;
11470 remap_table [CEE_CONV_R8] = OP_ICONV_TO_R8;
11471 remap_table [CEE_CONV_I4] = OP_MOVE;
11472 remap_table [CEE_CONV_U4] = OP_MOVE;
11473 remap_table [CEE_CONV_I1] = REMAP_OPCODE (CONV_TO_I1);
11474 remap_table [CEE_CONV_I2] = REMAP_OPCODE (CONV_TO_I2);
11475 remap_table [CEE_CONV_U1] = REMAP_OPCODE (CONV_TO_U1);
11476 remap_table [CEE_CONV_U2] = REMAP_OPCODE (CONV_TO_U2);
11477 remap_table [CEE_CONV_R_UN] = REMAP_OPCODE (CONV_TO_R_UN);
11478 remap_table [CEE_ADD] = REMAP_OPCODE (ADD);
11479 remap_table [CEE_SUB] = REMAP_OPCODE (SUB);
11480 remap_table [CEE_MUL] = REMAP_OPCODE (MUL);
11481 remap_table [CEE_DIV] = REMAP_OPCODE (DIV);
11482 remap_table [CEE_REM] = REMAP_OPCODE (REM);
11483 remap_table [CEE_DIV_UN] = REMAP_OPCODE (DIV_UN);
11484 remap_table [CEE_REM_UN] = REMAP_OPCODE (REM_UN);
11485 remap_table [CEE_AND] = REMAP_OPCODE (AND);
11486 remap_table [CEE_OR] = REMAP_OPCODE (OR);
11487 remap_table [CEE_XOR] = REMAP_OPCODE (XOR);
11488 remap_table [CEE_SHL] = REMAP_OPCODE (SHL);
11489 remap_table [CEE_SHR] = REMAP_OPCODE (SHR);
11490 remap_table [CEE_SHR_UN] = REMAP_OPCODE (SHR_UN);
11491 remap_table [CEE_NOT] = REMAP_OPCODE (NOT);
11492 remap_table [CEE_NEG] = REMAP_OPCODE (NEG);
11493 remap_table [CEE_CALL] = OP_CALL;
11494 remap_table [CEE_BEQ] = REMAP_OPCODE (BEQ);
11495 remap_table [CEE_BNE_UN] = REMAP_OPCODE (BNE_UN);
11496 remap_table [CEE_BLT] = REMAP_OPCODE (BLT);
11497 remap_table [CEE_BLT_UN] = REMAP_OPCODE (BLT_UN);
11498 remap_table [CEE_BGT] = REMAP_OPCODE (BGT);
11499 remap_table [CEE_BGT_UN] = REMAP_OPCODE (BGT_UN);
11500 remap_table [CEE_BGE] = REMAP_OPCODE (BGE);
11501 remap_table [CEE_BGE_UN] = REMAP_OPCODE (BGE_UN);
11502 remap_table [CEE_BLE] = REMAP_OPCODE (BLE);
11503 remap_table [CEE_BLE_UN] = REMAP_OPCODE (BLE_UN);
11504 remap_table [CEE_ADD_OVF] = REMAP_OPCODE (ADD_OVF);
11505 remap_table [CEE_ADD_OVF_UN] = REMAP_OPCODE (ADD_OVF_UN);
11506 remap_table [CEE_SUB_OVF] = REMAP_OPCODE (SUB_OVF);
11507 remap_table [CEE_SUB_OVF_UN] = REMAP_OPCODE (SUB_OVF_UN);
11508 remap_table [CEE_MUL_OVF] = REMAP_OPCODE (MUL_OVF);
11509 remap_table [CEE_MUL_OVF_UN] = REMAP_OPCODE (MUL_OVF_UN);
11512 MONO_BB_FOR_EACH_INS (bb, ins) {
11513 int remapped = remap_table [ins->opcode];
11515 ins->opcode = remapped;
11520 mono_codegen (MonoCompile *cfg)
11522 MonoJumpInfo *patch_info;
11523 MonoBasicBlock *bb;
11524 int i, max_epilog_size;
11527 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11528 cfg->spill_count = 0;
11529 /* we reuse dfn here */
11530 /* bb->dfn = bb_count++; */
11531 #ifdef MONO_ARCH_ENABLE_NORMALIZE_OPCODES
11532 mono_normalize_opcodes (cfg, bb);
11535 mono_arch_lowering_pass (cfg, bb);
11537 if (cfg->opt & MONO_OPT_PEEPHOLE)
11538 mono_arch_peephole_pass_1 (cfg, bb);
11540 mono_local_regalloc (cfg, bb);
11542 if (cfg->opt & MONO_OPT_PEEPHOLE)
11543 mono_arch_peephole_pass_2 (cfg, bb);
11546 if (cfg->prof_options & MONO_PROFILE_COVERAGE)
11547 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
11549 code = mono_arch_emit_prolog (cfg);
11551 if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
11552 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
11554 cfg->code_len = code - cfg->native_code;
11555 cfg->prolog_end = cfg->code_len;
11557 mono_debug_open_method (cfg);
11559 /* emit code all basic blocks */
11560 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11561 bb->native_offset = cfg->code_len;
11562 mono_arch_output_basic_block (cfg, bb);
11564 if (bb == cfg->bb_exit) {
11565 cfg->epilog_begin = cfg->code_len;
11567 if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
11568 code = cfg->native_code + cfg->code_len;
11569 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
11570 cfg->code_len = code - cfg->native_code;
11571 g_assert (cfg->code_len < cfg->code_size);
11574 mono_arch_emit_epilog (cfg);
11578 mono_arch_emit_exceptions (cfg);
11580 max_epilog_size = 0;
11582 code = cfg->native_code + cfg->code_len;
11584 /* we always allocate code in cfg->domain->code_mp to increase locality */
11585 cfg->code_size = cfg->code_len + max_epilog_size;
11586 /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
11588 if (cfg->method->dynamic) {
11589 /* Allocate the code into a separate memory pool so it can be freed */
11590 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
11591 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
11592 mono_domain_lock (cfg->domain);
11593 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
11594 mono_domain_unlock (cfg->domain);
11596 code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size);
11598 mono_domain_lock (cfg->domain);
11599 code = mono_code_manager_reserve (cfg->domain->code_mp, cfg->code_size);
11600 mono_domain_unlock (cfg->domain);
11603 memcpy (code, cfg->native_code, cfg->code_len);
11604 g_free (cfg->native_code);
11605 cfg->native_code = code;
11606 code = cfg->native_code + cfg->code_len;
11608 /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
11609 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
11610 switch (patch_info->type) {
11611 case MONO_PATCH_INFO_ABS: {
11612 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
11614 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
11615 if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) &&
11616 strstr (cfg->method->name, info->name))
11618 * This is an icall wrapper, and this is a call to the
11619 * wrapped function.
11623 /* for these array methods we currently register the same function pointer
11624 * since it's a vararg function. But this means that mono_find_jit_icall_by_addr ()
11625 * will return the incorrect one depending on the order they are registered.
11626 * See tests/test-arr.cs
11628 if (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL) {
11629 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
11630 patch_info->data.name = info->name;
11635 MonoVTable *vtable = mono_find_class_init_trampoline_by_addr (patch_info->data.target);
11637 patch_info->type = MONO_PATCH_INFO_CLASS_INIT;
11638 patch_info->data.klass = vtable->klass;
11640 MonoClass *klass = mono_find_delegate_trampoline_by_addr (patch_info->data.target);
11642 patch_info->type = MONO_PATCH_INFO_DELEGATE_TRAMPOLINE;
11643 patch_info->data.klass = klass;
11649 case MONO_PATCH_INFO_SWITCH: {
11651 if (cfg->method->dynamic) {
11652 table = mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
11654 mono_domain_lock (cfg->domain);
11655 table = mono_code_manager_reserve (cfg->domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
11656 mono_domain_unlock (cfg->domain);
11659 if (!cfg->compile_aot)
11660 /* In the aot case, the patch already points to the correct location */
11661 patch_info->ip.i = patch_info->ip.label->inst_c0;
11662 for (i = 0; i < patch_info->data.table->table_size; i++) {
11663 table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
11665 patch_info->data.table->table = (MonoBasicBlock**)table;
11674 #ifdef VALGRIND_JIT_REGISTER_MAP
11675 if (valgrind_register){
11676 char* nm = mono_method_full_name (cfg->method, TRUE);
11677 VALGRIND_JIT_REGISTER_MAP (nm, cfg->native_code, cfg->native_code + cfg->code_len);
11682 if (cfg->verbose_level > 0) {
11683 char* nm = mono_method_full_name (cfg->method, TRUE);
11684 g_print ("Method %s emitted at %p to %p (code length %d) [%s]\n",
11686 cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
11690 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
11691 mono_arch_save_unwind_info (cfg);
11694 mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
11696 if (cfg->method->dynamic) {
11697 mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
11699 mono_domain_lock (cfg->domain);
11700 mono_code_manager_commit (cfg->domain->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
11701 mono_domain_unlock (cfg->domain);
11704 mono_arch_flush_icache (cfg->native_code, cfg->code_len);
11706 mono_debug_close_method (cfg);
11712 remove_critical_edges (MonoCompile *cfg) {
11713 MonoBasicBlock *bb;
11714 MonoBasicBlock *previous_bb;
11716 if (cfg->verbose_level > 3) {
11717 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11718 MonoInst *last_ins;
11720 printf ("remove_critical_edges %s, BEFORE BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
11721 for (i = 0; i < bb->in_count; i++) {
11722 printf (" %d", bb->in_bb [i]->block_num);
11724 printf (") (out:");
11725 for (i = 0; i < bb->out_count; i++) {
11726 printf (" %d", bb->out_bb [i]->block_num);
11729 last_ins = mono_inst_list_last (&bb->ins_list);
11732 mono_print_tree (last_ins);
11738 for (previous_bb = cfg->bb_entry, bb = previous_bb->next_bb; bb != NULL; previous_bb = previous_bb->next_bb, bb = bb->next_bb) {
11739 if (bb->in_count > 1) {
11741 for (in_bb_index = 0; in_bb_index < bb->in_count; in_bb_index++) {
11742 MonoBasicBlock *in_bb = bb->in_bb [in_bb_index];
11743 if (in_bb->out_count > 1) {
11744 MonoBasicBlock *new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
11745 MONO_INST_LIST_INIT (&new_bb->ins_list);
11746 new_bb->block_num = cfg->num_bblocks++;
11747 // new_bb->real_offset = bb->real_offset;
11748 new_bb->region = bb->region;
11750 /* Do not alter the CFG while altering the BB list */
11751 if (previous_bb->region == bb->region) {
11752 if (previous_bb != cfg->bb_entry) {
11753 MonoInst *last_ins;
11754 /* If previous_bb "followed through" to bb, */
11755 /* keep it linked with a OP_BR */
11756 last_ins = mono_inst_list_last (&previous_bb->ins_list);
11757 if ((last_ins == NULL) ||
11758 ((last_ins->opcode != OP_BR) &&
11759 (!(MONO_IS_COND_BRANCH_OP (last_ins))) &&
11760 (last_ins->opcode != OP_SWITCH))) {
11762 /* Make sure previous_bb really falls through bb */
11763 for (i = 0; i < previous_bb->out_count; i++) {
11764 if (previous_bb->out_bb [i] == bb) {
11766 MONO_INST_NEW (cfg, jump, OP_BR);
11767 MONO_ADD_INS (previous_bb, jump);
11768 jump->cil_code = previous_bb->cil_code;
11769 jump->inst_target_bb = bb;
11775 /* We cannot add any inst to the entry BB, so we must */
11776 /* put a new BB in the middle to hold the OP_BR */
11778 MonoBasicBlock *new_bb_after_entry = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
11779 MONO_INST_LIST_INIT (&new_bb_after_entry->ins_list);
11780 new_bb_after_entry->block_num = cfg->num_bblocks++;
11781 // new_bb_after_entry->real_offset = bb->real_offset;
11782 new_bb_after_entry->region = bb->region;
11784 MONO_INST_NEW (cfg, jump, OP_BR);
11785 MONO_ADD_INS (new_bb_after_entry, jump);
11786 jump->cil_code = bb->cil_code;
11787 jump->inst_target_bb = bb;
11789 previous_bb->next_bb = new_bb_after_entry;
11790 previous_bb = new_bb_after_entry;
11792 if (cfg->verbose_level > 2) {
11793 printf ("remove_critical_edges %s, added helper BB%d jumping to BB%d\n", mono_method_full_name (cfg->method, TRUE), new_bb_after_entry->block_num, bb->block_num);
11798 /* Insert new_bb in the BB list */
11799 previous_bb->next_bb = new_bb;
11800 new_bb->next_bb = bb;
11801 previous_bb = new_bb;
11803 /* Setup in_bb and out_bb */
11804 new_bb->in_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
11805 new_bb->in_bb [0] = in_bb;
11806 new_bb->in_count = 1;
11807 new_bb->out_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
11808 new_bb->out_bb [0] = bb;
11809 new_bb->out_count = 1;
11811 /* Relink in_bb and bb to (from) new_bb */
11812 replace_out_block (in_bb, bb, new_bb);
11813 replace_out_block_in_code (in_bb, bb, new_bb);
11814 replace_in_block (bb, in_bb, new_bb);
11816 if (cfg->verbose_level > 2) {
11817 printf ("remove_critical_edges %s, removed critical edge from BB%d to BB%d (added BB%d)\n", mono_method_full_name (cfg->method, TRUE), in_bb->block_num, bb->block_num, new_bb->block_num);
11824 if (cfg->verbose_level > 3) {
11825 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
11826 MonoInst *last_ins;
11828 printf ("remove_critical_edges %s, AFTER BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
11829 for (i = 0; i < bb->in_count; i++) {
11830 printf (" %d", bb->in_bb [i]->block_num);
11832 printf (") (out:");
11833 for (i = 0; i < bb->out_count; i++) {
11834 printf (" %d", bb->out_bb [i]->block_num);
11837 last_ins = mono_inst_list_last (&bb->ins_list);
11840 mono_print_tree (last_ins);
11848 * mini_method_compile:
11849 * @method: the method to compile
11850 * @opts: the optimization flags to use
11851 * @domain: the domain where the method will be compiled in
11852 * @run_cctors: whether we should run type ctors if possible
11853 * @compile_aot: whether this is an AOT compilation
11854 * @parts: debug flag
11856 * Returns: a MonoCompile* pointer. Caller must check the exception_type
11857 * field in the returned struct to see if compilation succeded.
11860 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
11862 MonoMethodHeader *header;
11865 MonoJitInfo *jinfo;
11866 int dfn = 0, i, code_size_ratio;
11867 gboolean deadce_has_run = FALSE;
11868 gboolean try_generic_shared;
11869 MonoMethod *method_to_compile;
11870 int generic_info_size;
11872 mono_jit_stats.methods_compiled++;
11873 if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
11874 mono_profiler_method_jit (method);
11875 if (MONO_PROBE_METHOD_COMPILE_BEGIN_ENABLED ())
11876 MONO_PROBE_METHOD_COMPILE_BEGIN (method);
11879 /* We are passed the original generic method definition */
11880 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
11881 (opts & MONO_OPT_GSHARED) && (method->is_generic || method->klass->generic_container);
11883 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
11884 (opts & MONO_OPT_GSHARED) && mono_method_is_generic_sharable_impl (method);
11886 if (opts & MONO_OPT_GSHARED) {
11887 if (try_generic_shared)
11888 mono_stats.generics_sharable_methods++;
11889 else if (mono_method_is_generic_impl (method))
11890 mono_stats.generics_unsharable_methods++;
11894 if (try_generic_shared) {
11895 MonoMethod *declaring_method;
11896 MonoGenericContext *shared_context;
11899 declaring_method = method;
11901 declaring_method = mono_method_get_declaring_generic_method (method);
11902 g_assert (method->klass->generic_class->container_class == declaring_method->klass);
11905 if (declaring_method->is_generic)
11906 shared_context = &(mono_method_get_generic_container (declaring_method)->context);
11908 shared_context = &declaring_method->klass->generic_container->context;
11910 method_to_compile = mono_class_inflate_generic_method (declaring_method, shared_context);
11911 g_assert (method_to_compile);
11913 method_to_compile = method;
11916 cfg = g_new0 (MonoCompile, 1);
11917 cfg->method = method_to_compile;
11918 cfg->mempool = mono_mempool_new ();
11920 cfg->prof_options = mono_profiler_get_events ();
11921 cfg->run_cctors = run_cctors;
11922 cfg->domain = domain;
11923 cfg->verbose_level = mini_verbose;
11924 cfg->compile_aot = compile_aot;
11925 cfg->skip_visibility = method->skip_visibility;
11926 if (try_generic_shared)
11927 cfg->generic_sharing_context = (MonoGenericSharingContext*)&cfg->generic_sharing_context;
11928 cfg->token_info_hash = g_hash_table_new (NULL, NULL);
11930 /* The debugger has no liveness information, so avoid sharing registers/stack slots */
11931 if (mono_debug_using_mono_debugger () || debug_options.mdb_optimizations) {
11932 cfg->disable_reuse_registers = TRUE;
11933 cfg->disable_reuse_stack_slots = TRUE;
11935 * This decreases the change the debugger will read registers/stack slots which are
11936 * not yet initialized.
11938 cfg->disable_initlocals_opt = TRUE;
11940 /* Temporarily disable this when running in the debugger until we have support
11941 * for this in the debugger. */
11942 cfg->disable_omit_fp = TRUE;
11944 // cfg->opt |= MONO_OPT_SHARED;
11945 cfg->opt &= ~MONO_OPT_INLINE;
11946 cfg->opt &= ~MONO_OPT_COPYPROP;
11947 cfg->opt &= ~MONO_OPT_CONSPROP;
11950 header = mono_method_get_header (method_to_compile);
11952 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
11953 cfg->exception_message = g_strdup_printf ("Missing or incorrect header for method %s", cfg->method->name);
11954 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
11955 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
11956 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
11957 mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
11961 ip = (guint8 *)header->code;
11963 if (cfg->verbose_level > 2) {
11964 if (cfg->generic_sharing_context)
11965 g_print ("converting shared method %s\n", mono_method_full_name (method, TRUE));
11967 g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
11971 * create MonoInst* which represents arguments and local variables
11973 mono_compile_create_vars (cfg);
11975 if ((i = mono_method_to_ir (cfg, method_to_compile, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
11976 if (try_generic_shared && cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
11978 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
11979 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
11982 mono_destroy_compile (cfg);
11983 try_generic_shared = FALSE;
11984 goto restart_compile;
11986 g_assert (cfg->exception_type != MONO_EXCEPTION_GENERIC_SHARING_FAILED);
11988 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
11989 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
11990 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
11991 mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
11992 /* cfg contains the details of the failure, so let the caller cleanup */
11996 mono_jit_stats.basic_blocks += cfg->num_bblocks;
11997 mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
11999 if ((cfg->num_varinfo > 2000) && !cfg->compile_aot) {
12001 * we disable some optimizations if there are too many variables
12002 * because JIT time may become too expensive. The actual number needs
12003 * to be tweaked and eventually the non-linear algorithms should be fixed.
12005 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
12006 cfg->disable_ssa = TRUE;
12009 /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
12011 if (cfg->opt & MONO_OPT_BRANCH)
12012 optimize_branches (cfg);
12014 if (cfg->opt & MONO_OPT_SSAPRE) {
12015 remove_critical_edges (cfg);
12018 /* Depth-first ordering on basic blocks */
12019 cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
12021 df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
12022 if (cfg->num_bblocks != dfn + 1) {
12023 MonoBasicBlock *bb;
12025 cfg->num_bblocks = dfn + 1;
12027 if (!header->clauses) {
12028 /* remove unreachable code, because the code in them may be
12029 * inconsistent (access to dead variables for example) */
12030 for (bb = cfg->bb_entry; bb;) {
12031 MonoBasicBlock *bbn = bb->next_bb;
12033 if (bbn && bbn->region == -1 && !bbn->dfn) {
12034 if (cfg->verbose_level > 1)
12035 g_print ("found unreachable code in BB%d\n", bbn->block_num);
12036 bb->next_bb = bbn->next_bb;
12037 nullify_basic_block (bbn);
12045 if (cfg->opt & MONO_OPT_LOOP) {
12046 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
12047 mono_compute_natural_loops (cfg);
12050 /* after method_to_ir */
12052 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
12053 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
12057 //#define DEBUGSSA "logic_run"
12058 #define DEBUGSSA_CLASS "Tests"
12061 if (!header->num_clauses && !cfg->disable_ssa) {
12062 mono_local_cprop (cfg);
12063 #ifndef DISABLE_SSA
12064 mono_ssa_compute (cfg);
12069 /* fixme: add all optimizations which requires SSA */
12070 if (cfg->opt & (MONO_OPT_SSA | MONO_OPT_ABCREM | MONO_OPT_SSAPRE)) {
12071 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
12072 mono_local_cprop (cfg);
12073 #ifndef DISABLE_SSA
12074 mono_ssa_compute (cfg);
12077 if (cfg->verbose_level >= 2) {
12084 /* after SSA translation */
12086 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
12087 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
12091 if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
12092 if (cfg->comp_done & MONO_COMP_SSA) {
12093 #ifndef DISABLE_SSA
12094 mono_ssa_cprop (cfg);
12097 mono_local_cprop (cfg);
12101 #ifndef DISABLE_SSA
12102 if (cfg->comp_done & MONO_COMP_SSA) {
12103 //mono_ssa_deadce (cfg);
12105 //mono_ssa_strength_reduction (cfg);
12107 if (cfg->opt & MONO_OPT_SSAPRE) {
12108 mono_perform_ssapre (cfg);
12109 //mono_local_cprop (cfg);
12112 if (cfg->opt & MONO_OPT_DEADCE) {
12113 mono_ssa_deadce (cfg);
12114 deadce_has_run = TRUE;
12117 if ((cfg->flags & MONO_CFG_HAS_LDELEMA) && (cfg->opt & MONO_OPT_ABCREM))
12118 mono_perform_abc_removal (cfg);
12120 mono_ssa_remove (cfg);
12122 if (cfg->opt & MONO_OPT_BRANCH)
12123 optimize_branches (cfg);
12127 /* after SSA removal */
12129 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
12130 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
12134 if (cfg->verbose_level > 4) {
12135 printf ("BEFORE DECOMPSE START\n");
12136 mono_print_code (cfg);
12137 printf ("BEFORE DECOMPSE END\n");
12140 decompose_pass (cfg);
12142 if (cfg->got_var) {
12145 g_assert (cfg->got_var_allocated);
12148 * Allways allocate the GOT var to a register, because keeping it
12149 * in memory will increase the number of live temporaries in some
12150 * code created by inssel.brg, leading to the well known spills+
12151 * branches problem. Testcase: mcs crash in
12152 * System.MonoCustomAttrs:GetCustomAttributes.
12154 regs = mono_arch_get_global_int_regs (cfg);
12156 cfg->got_var->opcode = OP_REGVAR;
12157 cfg->got_var->dreg = GPOINTER_TO_INT (regs->data);
12158 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
12160 g_list_free (regs);
12163 /* todo: remove code when we have verified that the liveness for try/catch blocks
12167 * Currently, this can't be commented out since exception blocks are not
12168 * processed during liveness analysis.
12170 mono_liveness_handle_exception_clauses (cfg);
12172 if (cfg->opt & MONO_OPT_LINEARS) {
12173 GList *vars, *regs;
12175 /* For now, compute aliasing info only if needed for deadce... */
12176 if ((cfg->opt & MONO_OPT_DEADCE) && (! deadce_has_run) && (header->num_clauses == 0)) {
12177 cfg->aliasing_info = mono_build_aliasing_information (cfg);
12180 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
12181 cfg->comp_done &= ~MONO_COMP_LIVENESS;
12182 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
12183 mono_analyze_liveness (cfg);
12185 if (cfg->aliasing_info != NULL) {
12186 mono_aliasing_deadce (cfg->aliasing_info);
12187 deadce_has_run = TRUE;
12190 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
12191 regs = mono_arch_get_global_int_regs (cfg);
12193 regs = g_list_delete_link (regs, regs);
12194 mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
12197 if (cfg->aliasing_info != NULL) {
12198 mono_destroy_aliasing_information (cfg->aliasing_info);
12199 cfg->aliasing_info = NULL;
12203 //mono_print_code (cfg);
12207 /* variables are allocated after decompose, since decompose could create temps */
12208 mono_arch_allocate_vars (cfg);
12210 if (cfg->opt & MONO_OPT_CFOLD)
12211 mono_constant_fold (cfg);
12213 mini_select_instructions (cfg);
12215 mono_codegen (cfg);
12216 if (cfg->verbose_level >= 2) {
12217 char *id = mono_method_full_name (cfg->method, FALSE);
12218 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
12222 if (cfg->generic_sharing_context)
12223 generic_info_size = sizeof (MonoGenericJitInfo);
12225 generic_info_size = 0;
12227 if (cfg->method->dynamic) {
12228 jinfo = g_malloc0 (sizeof (MonoJitInfo) + (header->num_clauses * sizeof (MonoJitExceptionInfo)) +
12229 generic_info_size);
12231 /* we access cfg->domain->mp */
12232 mono_domain_lock (cfg->domain);
12233 jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo) +
12234 (header->num_clauses * sizeof (MonoJitExceptionInfo)) +
12235 generic_info_size);
12236 mono_domain_unlock (cfg->domain);
12239 jinfo->method = method;
12240 jinfo->code_start = cfg->native_code;
12241 jinfo->code_size = cfg->code_len;
12242 jinfo->used_regs = cfg->used_int_regs;
12243 jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
12244 jinfo->cas_inited = FALSE; /* initialization delayed at the first stalk walk using this method */
12245 jinfo->num_clauses = header->num_clauses;
12248 * Static methods only get a generic JIT info if they use the
12249 * rgctx variable (which they are forced to if they have any
12250 * open catch clauses).
12252 if (cfg->generic_sharing_context &&
12253 (cfg->rgctx_var || !(method_to_compile->flags & METHOD_ATTRIBUTE_STATIC))) {
12255 MonoGenericJitInfo *gi;
12257 jinfo->has_generic_jit_info = 1;
12259 gi = mono_jit_info_get_generic_jit_info (jinfo);
12262 gi->generic_sharing_context = cfg->generic_sharing_context;
12264 if (method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) {
12265 inst = cfg->rgctx_var;
12266 g_assert (inst->opcode == OP_REGOFFSET);
12268 inst = cfg->args [0];
12271 if (inst->opcode == OP_REGVAR) {
12272 gi->this_in_reg = 1;
12273 gi->this_reg = inst->dreg;
12275 //g_print ("this in reg %d\n", inst->dreg);
12277 g_assert (inst->opcode == OP_REGOFFSET);
12279 g_assert (inst->inst_basereg == X86_EBP);
12280 #elif defined(__x86_64__)
12281 g_assert (inst->inst_basereg == X86_EBP || inst->inst_basereg == X86_ESP);
12283 g_assert (inst->inst_offset >= G_MININT32 && inst->inst_offset <= G_MAXINT32);
12285 gi->this_in_reg = 0;
12286 gi->this_reg = inst->inst_basereg;
12287 gi->this_offset = inst->inst_offset;
12289 //g_print ("this at offset %d\n", inst->inst_offset);
12293 if (header->num_clauses) {
12296 for (i = 0; i < header->num_clauses; i++) {
12297 MonoExceptionClause *ec = &header->clauses [i];
12298 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
12299 MonoBasicBlock *tblock;
12302 ei->flags = ec->flags;
12304 exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
12305 ei->exvar_offset = exvar ? exvar->inst_offset : 0;
12307 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
12308 tblock = cfg->cil_offset_to_bb [ec->data.filter_offset];
12310 ei->data.filter = cfg->native_code + tblock->native_offset;
12312 ei->data.catch_class = ec->data.catch_class;
12315 tblock = cfg->cil_offset_to_bb [ec->try_offset];
12317 ei->try_start = cfg->native_code + tblock->native_offset;
12318 g_assert (tblock->native_offset);
12319 tblock = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
12321 ei->try_end = cfg->native_code + tblock->native_offset;
12322 g_assert (tblock->native_offset);
12323 tblock = cfg->cil_offset_to_bb [ec->handler_offset];
12325 ei->handler_start = cfg->native_code + tblock->native_offset;
12329 cfg->jit_info = jinfo;
12330 #if defined(__arm__)
12331 mono_arch_fixup_jinfo (cfg);
12334 mono_domain_lock (cfg->domain);
12335 mono_jit_info_table_add (cfg->domain, jinfo);
12337 if (cfg->method->dynamic)
12338 mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = jinfo;
12339 mono_domain_unlock (cfg->domain);
12341 /* collect statistics */
12342 mono_jit_stats.allocated_code_size += cfg->code_len;
12343 code_size_ratio = cfg->code_len;
12344 if (code_size_ratio > mono_jit_stats.biggest_method_size) {
12345 mono_jit_stats.biggest_method_size = code_size_ratio;
12346 mono_jit_stats.biggest_method = method;
12348 code_size_ratio = (code_size_ratio * 100) / mono_method_get_header (method)->code_size;
12349 if (code_size_ratio > mono_jit_stats.max_code_size_ratio) {
12350 mono_jit_stats.max_code_size_ratio = code_size_ratio;
12351 mono_jit_stats.max_ratio_method = method;
12353 mono_jit_stats.native_code_size += cfg->code_len;
12355 if (MONO_PROBE_METHOD_COMPILE_END_ENABLED ())
12356 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
12357 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
12358 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
12363 static MonoJitInfo*
12364 lookup_generic_method (MonoDomain *domain, MonoMethod *method)
12366 MonoMethod *open_method;
12368 if (!mono_method_is_generic_sharable_impl (method))
12371 open_method = mono_method_get_declaring_generic_method (method);
12373 return mono_domain_lookup_shared_generic (domain, open_method);
12376 static MonoJitInfo*
12377 lookup_method (MonoDomain *domain, MonoMethod *method)
12379 MonoJitInfo *ji = mono_internal_hash_table_lookup (&domain->jit_code_hash, method);
12384 return lookup_generic_method (domain, method);
12388 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt)
12391 gpointer code = NULL;
12393 MonoVTable *vtable;
12395 #ifdef MONO_USE_AOT_COMPILER
12396 if ((opt & MONO_OPT_AOT) && !(mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)) {
12397 MonoDomain *domain = mono_domain_get ();
12399 mono_class_init (method->klass);
12401 mono_domain_lock (domain);
12402 if ((code = mono_aot_get_method (domain, method))) {
12403 mono_domain_unlock (domain);
12404 vtable = mono_class_vtable (domain, method->klass);
12406 mono_runtime_class_init (vtable);
12410 mono_domain_unlock (domain);
12414 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
12415 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
12417 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
12419 if (!piinfo->addr) {
12420 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
12421 piinfo->addr = mono_lookup_internal_call (method);
12422 else if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
12423 #ifdef PLATFORM_WIN32
12424 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);
12426 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);
12429 mono_lookup_pinvoke_call (method, NULL, NULL);
12431 nm = mono_marshal_get_native_wrapper (method, check_for_pending_exc);
12432 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12434 //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE)
12435 //mono_debug_add_wrapper (method, nm);
12436 } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
12437 const char *name = method->name;
12440 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
12441 if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
12442 MonoJitICallInfo *mi = mono_find_jit_icall_by_name ("mono_delegate_ctor");
12444 return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper (mi));
12445 } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
12446 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
12447 return mono_create_delegate_trampoline (method->klass);
12449 nm = mono_marshal_get_delegate_invoke (method, NULL);
12450 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12452 } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
12453 nm = mono_marshal_get_delegate_begin_invoke (method);
12454 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12455 } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
12456 nm = mono_marshal_get_delegate_end_invoke (method);
12457 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
12463 cfg = mini_method_compile (method, opt, target_domain, TRUE, FALSE, 0);
12465 switch (cfg->exception_type) {
12466 case MONO_EXCEPTION_NONE: break;
12467 case MONO_EXCEPTION_TYPE_LOAD:
12468 case MONO_EXCEPTION_MISSING_FIELD:
12469 case MONO_EXCEPTION_MISSING_METHOD:
12470 case MONO_EXCEPTION_FILE_NOT_FOUND: {
12471 /* Throw a type load exception if needed */
12472 MonoLoaderError *error = mono_loader_get_last_error ();
12476 ex = mono_loader_error_prepare_exception (error);
12478 if (cfg->exception_ptr) {
12479 ex = mono_class_get_exception_for_failure (cfg->exception_ptr);
12481 if (cfg->exception_type == MONO_EXCEPTION_MISSING_FIELD)
12482 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingFieldException", cfg->exception_message);
12483 else if (cfg->exception_type == MONO_EXCEPTION_MISSING_METHOD)
12484 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingMethodException", cfg->exception_message);
12485 else if (cfg->exception_type == MONO_EXCEPTION_TYPE_LOAD)
12486 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "TypeLoadException", cfg->exception_message);
12487 else if (cfg->exception_type == MONO_EXCEPTION_FILE_NOT_FOUND)
12488 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FileNotFoundException", cfg->exception_message);
12490 g_assert_not_reached ();
12493 mono_destroy_compile (cfg);
12494 mono_raise_exception (ex);
12497 case MONO_EXCEPTION_INVALID_PROGRAM: {
12498 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", cfg->exception_message);
12499 mono_destroy_compile (cfg);
12500 mono_raise_exception (ex);
12503 case MONO_EXCEPTION_UNVERIFIABLE_IL: {
12504 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.Security", "VerificationException", cfg->exception_message);
12505 mono_destroy_compile (cfg);
12506 mono_raise_exception (ex);
12509 case MONO_EXCEPTION_METHOD_ACCESS: {
12510 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MethodAccessException", cfg->exception_message);
12511 mono_destroy_compile (cfg);
12512 mono_raise_exception (ex);
12515 case MONO_EXCEPTION_FIELD_ACCESS: {
12516 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "FieldAccessException", cfg->exception_message);
12517 mono_destroy_compile (cfg);
12518 mono_raise_exception (ex);
12521 /* this can only be set if the security manager is active */
12522 case MONO_EXCEPTION_SECURITY_LINKDEMAND: {
12523 MonoSecurityManager* secman = mono_security_manager_get_methods ();
12524 MonoObject *exc = NULL;
12527 args [0] = &cfg->exception_data;
12528 args [1] = &method;
12529 mono_runtime_invoke (secman->linkdemandsecurityexception, NULL, args, &exc);
12531 mono_destroy_compile (cfg);
12534 mono_raise_exception ((MonoException*)exc);
12537 g_assert_not_reached ();
12540 mono_domain_lock (target_domain);
12542 /* Check if some other thread already did the job. In this case, we can
12543 discard the code this thread generated. */
12545 if ((info = lookup_method (target_domain, method))) {
12546 /* We can't use a domain specific method in another domain */
12547 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
12548 code = info->code_start;
12549 // printf("Discarding code for method %s\n", method->name);
12553 if (code == NULL) {
12554 mono_internal_hash_table_insert (&target_domain->jit_code_hash, method, cfg->jit_info);
12555 code = cfg->native_code;
12557 if (cfg->generic_sharing_context && mono_method_is_generic_sharable_impl (method)) {
12558 /* g_print ("inserting method %s.%s.%s\n", method->klass->name_space, method->klass->name, method->name); */
12559 mono_domain_register_shared_generic (target_domain,
12560 mono_method_get_declaring_generic_method (method), cfg->jit_info);
12561 mono_stats.generics_shared_methods++;
12565 mono_destroy_compile (cfg);
12567 if (target_domain->jump_target_hash) {
12568 MonoJumpInfo patch_info;
12569 GSList *list, *tmp;
12570 list = g_hash_table_lookup (target_domain->jump_target_hash, method);
12572 patch_info.next = NULL;
12573 patch_info.ip.i = 0;
12574 patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
12575 patch_info.data.method = method;
12576 g_hash_table_remove (target_domain->jump_target_hash, method);
12578 for (tmp = list; tmp; tmp = tmp->next)
12579 mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info, TRUE);
12580 g_slist_free (list);
12583 mono_domain_unlock (target_domain);
12585 vtable = mono_class_vtable (target_domain, method->klass);
12587 MonoException *exc;
12588 exc = mono_class_get_exception_for_failure (method->klass);
12590 mono_raise_exception (exc);
12592 mono_runtime_class_init (vtable);
12597 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt)
12599 MonoDomain *target_domain, *domain = mono_domain_get ();
12602 MonoJitICallInfo *callinfo = NULL;
12605 * ICALL wrappers are handled specially, since there is only one copy of them
12606 * shared by all appdomains.
12608 if ((method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (strstr (method->name, "__icall_wrapper_") == method->name)) {
12609 const char *icall_name;
12611 icall_name = method->name + strlen ("__icall_wrapper_");
12612 g_assert (icall_name);
12613 callinfo = mono_find_jit_icall_by_name (icall_name);
12614 g_assert (callinfo);
12616 /* Must be domain neutral since there is only one copy */
12617 opt |= MONO_OPT_SHARED;
12620 if (opt & MONO_OPT_SHARED)
12621 target_domain = mono_get_root_domain ();
12623 target_domain = domain;
12625 mono_domain_lock (target_domain);
12627 if ((info = lookup_method (target_domain, method))) {
12628 /* We can't use a domain specific method in another domain */
12629 if (! ((domain != target_domain) && !info->domain_neutral)) {
12630 MonoVTable *vtable;
12632 mono_domain_unlock (target_domain);
12633 mono_jit_stats.methods_lookups++;
12634 vtable = mono_class_vtable (domain, method->klass);
12635 mono_runtime_class_init (vtable);
12636 return mono_create_ftnptr (target_domain, info->code_start);
12640 mono_domain_unlock (target_domain);
12641 p = mono_create_ftnptr (target_domain, mono_jit_compile_method_inner (method, target_domain, opt));
12645 if (!callinfo->wrapper) {
12646 callinfo->wrapper = p;
12647 mono_register_jit_icall_wrapper (callinfo, p);
12648 mono_debug_add_icall_wrapper (method, callinfo);
12650 mono_jit_unlock ();
12657 mono_jit_compile_method (MonoMethod *method)
12659 return mono_jit_compile_method_with_opt (method, default_opt);
12663 invalidated_delegate_trampoline (char *desc)
12665 g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
12666 "See http://www.go-mono.com/delegate.html for an explanation and ways to fix this.",
12671 * mono_jit_free_method:
12673 * Free all memory allocated by the JIT for METHOD.
12676 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
12678 MonoJitDynamicMethodInfo *ji;
12679 gboolean destroy = TRUE;
12681 g_assert (method->dynamic);
12683 mono_domain_lock (domain);
12684 ji = mono_dynamic_code_hash_lookup (domain, method);
12685 mono_domain_unlock (domain);
12689 mono_domain_lock (domain);
12690 g_hash_table_remove (domain->dynamic_code_hash, method);
12691 mono_internal_hash_table_remove (&domain->jit_code_hash, method);
12692 g_hash_table_remove (domain->jump_trampoline_hash, method);
12693 mono_domain_unlock (domain);
12695 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
12696 if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
12698 * Instead of freeing the code, change it to call an error routine
12699 * so people can fix their code.
12701 char *type = mono_type_full_name (&method->klass->byval_arg);
12702 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
12705 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
12711 * This needs to be done before freeing code_mp, since the code address is the
12712 * key in the table, so if we free the code_mp first, another thread can grab the
12713 * same code address and replace our entry in the table.
12715 mono_jit_info_table_remove (domain, ji->ji);
12718 mono_code_manager_destroy (ji->code_mp);
12723 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
12725 MonoDomain *target_domain;
12728 if (default_opt & MONO_OPT_SHARED)
12729 target_domain = mono_get_root_domain ();
12731 target_domain = domain;
12733 mono_domain_lock (target_domain);
12735 if ((info = lookup_method (target_domain, method))) {
12736 /* We can't use a domain specific method in another domain */
12737 if (! ((domain != target_domain) && !info->domain_neutral)) {
12738 mono_domain_unlock (target_domain);
12739 mono_jit_stats.methods_lookups++;
12740 return info->code_start;
12744 mono_domain_unlock (target_domain);
12750 * mono_jit_runtime_invoke:
12751 * @method: the method to invoke
12752 * @obj: this pointer
12753 * @params: array of parameter values.
12754 * @exc: used to catch exceptions objects
12757 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
12759 MonoMethod *to_compile;
12760 MonoMethod *invoke;
12761 MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
12762 void* compiled_method;
12763 MonoVTable *vtable;
12765 if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
12766 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
12770 if ((method->flags & METHOD_ATTRIBUTE_STATIC) &&
12771 mono_class_generic_sharing_enabled (method->klass) &&
12772 mono_method_is_generic_sharable_impl (method)) {
12773 to_compile = mono_marshal_get_static_rgctx_invoke (method);
12775 to_compile = method;
12778 invoke = mono_marshal_get_runtime_invoke (method);
12779 runtime_invoke = mono_jit_compile_method (invoke);
12781 /* We need this here becuase mono_marshal_get_runtime_invoke can be place
12782 * the helper method in System.Object and not the target class
12784 vtable = mono_class_vtable (mono_domain_get (), method->klass);
12786 mono_runtime_class_init (vtable);
12788 if (method->klass->rank && (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) &&
12789 (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)) {
12791 * Array Get/Set/Address methods. The JIT implements them using inline code
12792 * inside the runtime invoke wrappers, so no need to compile them.
12794 compiled_method = NULL;
12796 compiled_method = mono_jit_compile_method (to_compile);
12798 return runtime_invoke (obj, params, exc, compiled_method);
12801 #ifdef MONO_GET_CONTEXT
12802 #define GET_CONTEXT MONO_GET_CONTEXT
12805 #ifndef GET_CONTEXT
12806 #ifdef PLATFORM_WIN32
12807 #define GET_CONTEXT \
12808 struct sigcontext *ctx = (struct sigcontext*)_dummy;
12810 #ifdef MONO_ARCH_USE_SIGACTION
12811 #define GET_CONTEXT \
12812 void *ctx = context;
12813 #elif defined(__sparc__)
12814 #define GET_CONTEXT \
12815 void *ctx = sigctx;
12817 #define GET_CONTEXT \
12818 void **_p = (void **)&_dummy; \
12819 struct sigcontext *ctx = (struct sigcontext *)++_p;
12824 #ifdef MONO_ARCH_USE_SIGACTION
12825 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, siginfo_t *info, void *context)
12826 #elif defined(__sparc__)
12827 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, void *sigctx)
12829 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy)
12833 SIG_HANDLER_SIGNATURE (sigfpe_signal_handler)
12835 MonoException *exc = NULL;
12836 #ifndef MONO_ARCH_USE_SIGACTION
12841 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
12842 if (mono_arch_is_int_overflow (ctx, info))
12843 exc = mono_get_exception_arithmetic ();
12845 exc = mono_get_exception_divide_by_zero ();
12847 exc = mono_get_exception_divide_by_zero ();
12850 mono_arch_handle_exception (ctx, exc, FALSE);
12854 SIG_HANDLER_SIGNATURE (sigill_signal_handler)
12856 MonoException *exc;
12859 exc = mono_get_exception_execution_engine ("SIGILL");
12861 mono_arch_handle_exception (ctx, exc, FALSE);
12865 SIG_HANDLER_SIGNATURE (sigsegv_signal_handler)
12867 #ifndef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12868 MonoException *exc = NULL;
12872 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12873 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
12877 #ifdef MONO_ARCH_USE_SIGACTION
12878 if (debug_options.collect_pagefault_stats) {
12879 if (mono_raw_buffer_is_pagefault (info->si_addr)) {
12880 mono_raw_buffer_handle_pagefault (info->si_addr);
12883 if (mono_aot_is_pagefault (info->si_addr)) {
12884 mono_aot_handle_pagefault (info->si_addr);
12890 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context (ctx));
12892 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
12893 /* we got a stack overflow in the soft-guard pages
12894 * There are two cases:
12895 * 1) managed code caused the overflow: we unprotect the soft-guard page
12896 * and let the arch-specific code trigger the exception handling mechanism
12897 * in the thread stack. The soft-guard pages will be protected again as the stack is unwound.
12898 * 2) unmanaged code caused the overflow: we unprotect the soft-guard page
12899 * and hope we can continue with those enabled, at least until the hard-guard page
12900 * is hit. The alternative to continuing here is to just print a message and abort.
12901 * We may add in the future the code to protect the pages again in the codepath
12902 * when we return from unmanaged to managed code.
12904 if (jit_tls->stack_ovf_guard_size && (guint8*)info->si_addr >= (guint8*)jit_tls->stack_ovf_guard_base &&
12905 (guint8*)info->si_addr < (guint8*)jit_tls->stack_ovf_guard_base + jit_tls->stack_ovf_guard_size) {
12906 mono_mprotect (jit_tls->stack_ovf_guard_base, jit_tls->stack_ovf_guard_size, MONO_MMAP_READ|MONO_MMAP_WRITE|MONO_MMAP_EXEC);
12908 mono_arch_handle_altstack_exception (ctx, info->si_addr, TRUE);
12910 /* We print a message: after this even managed stack overflows
12911 * may crash the runtime
12913 fprintf (stderr, "Stack overflow in unmanaged: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
12917 /* The hard-guard page has been hit: there is not much we can do anymore
12918 * Print a hopefully clear message and abort.
12920 if (jit_tls->stack_size &&
12921 ABS ((guint8*)info->si_addr - ((guint8*)jit_tls->end_of_stack - jit_tls->stack_size)) < 32768) {
12922 const char *method;
12923 /* we don't do much now, but we can warn the user with a useful message */
12924 fprintf (stderr, "Stack overflow: IP: %p, fault addr: %p\n", mono_arch_ip_from_context (ctx), (gpointer)info->si_addr);
12925 if (ji && ji->method)
12926 method = mono_method_full_name (ji->method, TRUE);
12928 method = "Unmanaged";
12929 fprintf (stderr, "At %s\n", method);
12932 mono_arch_handle_altstack_exception (ctx, info->si_addr, FALSE);
12937 mono_handle_native_sigsegv (SIGSEGV, ctx);
12940 mono_arch_handle_exception (ctx, exc, FALSE);
12944 #ifndef PLATFORM_WIN32
12947 SIG_HANDLER_SIGNATURE (sigabrt_signal_handler)
12952 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
12954 mono_handle_native_sigsegv (SIGABRT, ctx);
12959 SIG_HANDLER_SIGNATURE (sigusr1_signal_handler)
12961 gboolean running_managed;
12962 MonoException *exc;
12963 MonoThread *thread = mono_thread_current ();
12968 if (thread->thread_dump_requested) {
12969 thread->thread_dump_requested = FALSE;
12971 mono_print_thread_dump (ctx);
12976 * This is an async signal, so the code below must not call anything which
12977 * is not async safe. That includes the pthread locking functions. If we
12978 * know that we interrupted managed code, then locking is safe.
12980 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
12981 running_managed = ji != NULL;
12983 exc = mono_thread_request_interruption (running_managed);
12986 mono_arch_handle_exception (ctx, exc, FALSE);
12989 #if defined(__i386__) || defined(__x86_64__)
12990 #define FULL_STAT_PROFILER_BACKTRACE 1
12991 #define CURRENT_FRAME_GET_BASE_POINTER(f) (* (gpointer*)(f))
12992 #define CURRENT_FRAME_GET_RETURN_ADDRESS(f) (* (((gpointer*)(f)) + 1))
12993 #if MONO_ARCH_STACK_GROWS_UP
12994 #define IS_BEFORE_ON_STACK <
12995 #define IS_AFTER_ON_STACK >
12997 #define IS_BEFORE_ON_STACK >
12998 #define IS_AFTER_ON_STACK <
13001 #define FULL_STAT_PROFILER_BACKTRACE 0
13004 #if defined(__ia64__) || defined(__sparc__) || defined(sparc) || defined(__s390__) || defined(s390)
13007 SIG_HANDLER_SIGNATURE (sigprof_signal_handler)
13015 SIG_HANDLER_SIGNATURE (sigprof_signal_handler)
13017 int call_chain_depth = mono_profiler_stat_get_call_chain_depth ();
13020 if (call_chain_depth == 0) {
13021 mono_profiler_stat_hit (mono_arch_ip_from_context (ctx), ctx);
13023 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
13024 int current_frame_index = 1;
13025 MonoContext mono_context;
13026 #if FULL_STAT_PROFILER_BACKTRACE
13027 guchar *current_frame;
13028 guchar *stack_bottom;
13031 MonoDomain *domain;
13033 guchar *ips [call_chain_depth + 1];
13035 mono_arch_sigctx_to_monoctx (ctx, &mono_context);
13036 ips [0] = MONO_CONTEXT_GET_IP (&mono_context);
13038 if (jit_tls != NULL) {
13039 #if FULL_STAT_PROFILER_BACKTRACE
13040 stack_bottom = jit_tls->end_of_stack;
13041 stack_top = MONO_CONTEXT_GET_SP (&mono_context);
13042 current_frame = MONO_CONTEXT_GET_BP (&mono_context);
13044 while ((current_frame_index <= call_chain_depth) &&
13045 (stack_bottom IS_BEFORE_ON_STACK (guchar*) current_frame) &&
13046 ((guchar*) current_frame IS_BEFORE_ON_STACK stack_top)) {
13047 ips [current_frame_index] = CURRENT_FRAME_GET_RETURN_ADDRESS (current_frame);
13048 current_frame_index ++;
13049 stack_top = current_frame;
13050 current_frame = CURRENT_FRAME_GET_BASE_POINTER (current_frame);
13053 domain = mono_domain_get ();
13054 if (domain != NULL) {
13055 MonoLMF *lmf = NULL;
13058 MonoContext new_mono_context;
13060 ji = mono_arch_find_jit_info (domain, jit_tls, &res, NULL, &mono_context,
13061 &new_mono_context, NULL, &lmf, &native_offset, NULL);
13062 while ((ji != NULL) && (current_frame_index <= call_chain_depth)) {
13063 ips [current_frame_index] = MONO_CONTEXT_GET_IP (&new_mono_context);
13064 current_frame_index ++;
13065 mono_context = new_mono_context;
13066 ji = mono_arch_find_jit_info (domain, jit_tls, &res, NULL, &mono_context,
13067 &new_mono_context, NULL, &lmf, &native_offset, NULL);
13074 mono_profiler_stat_call_chain (current_frame_index, & ips [0], ctx);
13081 SIG_HANDLER_SIGNATURE (sigquit_signal_handler)
13085 printf ("Full thread dump:\n");
13087 mono_threads_request_thread_dump ();
13090 * print_thread_dump () skips the current thread, since sending a signal
13091 * to it would invoke the signal handler below the sigquit signal handler,
13092 * and signal handlers don't create an lmf, so the stack walk could not
13095 mono_print_thread_dump (ctx);
13099 SIG_HANDLER_SIGNATURE (sigusr2_signal_handler)
13101 gboolean enabled = mono_trace_is_enabled ();
13103 mono_trace_enable (!enabled);
13109 SIG_HANDLER_SIGNATURE (sigint_signal_handler)
13111 MonoException *exc;
13114 exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
13116 mono_arch_handle_exception (ctx, exc, FALSE);
13119 #ifdef PLATFORM_MACOSX
13122 * This code disables the CrashReporter of MacOS X by installing
13123 * a dummy Mach exception handler.
13127 * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/exc_server.html
13131 exc_server (mach_msg_header_t *request_msg,
13132 mach_msg_header_t *reply_msg);
13135 * The exception message
13138 mach_msg_base_t msg; /* common mach message header */
13139 char payload [1024]; /* opaque */
13140 } mach_exception_msg_t;
13142 /* The exception port */
13143 static mach_port_t mach_exception_port = VM_MAP_NULL;
13146 * Implicitly called by exc_server. Must be public.
13148 * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/catch_exception_raise.html
13151 catch_exception_raise (
13152 mach_port_t exception_port,
13153 mach_port_t thread,
13155 exception_type_t exception,
13156 exception_data_t code,
13157 mach_msg_type_number_t code_count)
13159 /* consume the exception */
13160 return KERN_FAILURE;
13164 * Exception thread handler.
13168 mach_exception_thread (void *arg)
13171 mach_exception_msg_t request;
13172 mach_exception_msg_t reply;
13173 mach_msg_return_t result;
13175 /* receive from "mach_exception_port" */
13176 result = mach_msg (&request.msg.header,
13177 MACH_RCV_MSG | MACH_RCV_LARGE,
13180 mach_exception_port,
13181 MACH_MSG_TIMEOUT_NONE,
13184 g_assert (result == MACH_MSG_SUCCESS);
13186 /* dispatch to catch_exception_raise () */
13187 exc_server (&request.msg.header, &reply.msg.header);
13189 /* send back to sender */
13190 result = mach_msg (&reply.msg.header,
13192 reply.msg.header.msgh_size,
13195 MACH_MSG_TIMEOUT_NONE,
13198 g_assert (result == MACH_MSG_SUCCESS);
13204 macosx_register_exception_handler ()
13207 pthread_attr_t attr;
13210 if (mach_exception_port != VM_MAP_NULL)
13213 task = mach_task_self ();
13215 /* create the "mach_exception_port" with send & receive rights */
13216 g_assert (mach_port_allocate (task, MACH_PORT_RIGHT_RECEIVE,
13217 &mach_exception_port) == KERN_SUCCESS);
13218 g_assert (mach_port_insert_right (task, mach_exception_port, mach_exception_port,
13219 MACH_MSG_TYPE_MAKE_SEND) == KERN_SUCCESS);
13221 /* create the exception handler thread */
13222 g_assert (!pthread_attr_init (&attr));
13223 g_assert (!pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED));
13224 g_assert (!pthread_create (&thread, &attr, mach_exception_thread, NULL));
13225 pthread_attr_destroy (&attr);
13228 * register "mach_exception_port" as a receiver for the
13229 * EXC_BAD_ACCESS exception
13231 * http://darwinsource.opendarwin.org/10.4.3/xnu-792.6.22/osfmk/man/task_set_exception_ports.html
13233 g_assert (task_set_exception_ports (task, EXC_MASK_BAD_ACCESS,
13234 mach_exception_port,
13236 MACHINE_THREAD_STATE) == KERN_SUCCESS);
13240 #ifndef PLATFORM_WIN32
13242 add_signal_handler (int signo, gpointer handler)
13244 struct sigaction sa;
13246 #ifdef MONO_ARCH_USE_SIGACTION
13247 sa.sa_sigaction = handler;
13248 sigemptyset (&sa.sa_mask);
13249 sa.sa_flags = SA_SIGINFO;
13250 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
13251 if (signo == SIGSEGV)
13252 sa.sa_flags |= SA_ONSTACK;
13255 sa.sa_handler = handler;
13256 sigemptyset (&sa.sa_mask);
13259 g_assert (sigaction (signo, &sa, NULL) != -1);
13263 remove_signal_handler (int signo)
13265 struct sigaction sa;
13267 sa.sa_handler = SIG_DFL;
13268 sigemptyset (&sa.sa_mask);
13271 g_assert (sigaction (signo, &sa, NULL) != -1);
13276 mono_runtime_install_handlers (void)
13278 #ifdef PLATFORM_WIN32
13280 win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
13281 win32_seh_set_handler(SIGILL, sigill_signal_handler);
13282 win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
13283 if (debug_options.handle_sigint)
13284 win32_seh_set_handler(SIGINT, sigint_signal_handler);
13286 #else /* !PLATFORM_WIN32 */
13289 #ifdef PLATFORM_MACOSX
13290 macosx_register_exception_handler ();
13293 if (debug_options.handle_sigint)
13294 add_signal_handler (SIGINT, sigint_signal_handler);
13296 add_signal_handler (SIGFPE, sigfpe_signal_handler);
13297 add_signal_handler (SIGQUIT, sigquit_signal_handler);
13298 add_signal_handler (SIGILL, sigill_signal_handler);
13299 add_signal_handler (SIGBUS, sigsegv_signal_handler);
13300 if (mono_jit_trace_calls != NULL)
13301 add_signal_handler (SIGUSR2, sigusr2_signal_handler);
13303 add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
13304 signal (SIGPIPE, SIG_IGN);
13306 add_signal_handler (SIGABRT, sigabrt_signal_handler);
13308 /* catch SIGSEGV */
13309 add_signal_handler (SIGSEGV, sigsegv_signal_handler);
13310 #endif /* PLATFORM_WIN32 */
13314 mono_runtime_cleanup_handlers (void)
13316 #ifdef PLATFORM_WIN32
13317 win32_seh_cleanup();
13319 if (debug_options.handle_sigint)
13320 remove_signal_handler (SIGINT);
13322 remove_signal_handler (SIGFPE);
13323 remove_signal_handler (SIGQUIT);
13324 remove_signal_handler (SIGILL);
13325 remove_signal_handler (SIGBUS);
13326 if (mono_jit_trace_calls != NULL)
13327 remove_signal_handler (SIGUSR2);
13329 remove_signal_handler (mono_thread_get_abort_signal ());
13331 remove_signal_handler (SIGABRT);
13333 remove_signal_handler (SIGSEGV);
13334 #endif /* PLATFORM_WIN32 */
13338 #ifdef HAVE_LINUX_RTC_H
13339 #include <linux/rtc.h>
13340 #include <sys/ioctl.h>
13342 static int rtc_fd = -1;
13345 enable_rtc_timer (gboolean enable)
13348 flags = fcntl (rtc_fd, F_GETFL);
13350 perror ("getflags");
13357 if (fcntl (rtc_fd, F_SETFL, flags) == -1) {
13358 perror ("setflags");
13365 #ifdef PLATFORM_WIN32
13366 static HANDLE win32_main_thread;
13367 static MMRESULT win32_timer;
13369 static void CALLBACK
13370 win32_time_proc (UINT uID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
13374 context.ContextFlags = CONTEXT_CONTROL;
13375 if (GetThreadContext (win32_main_thread, &context)) {
13377 mono_profiler_stat_hit ((guchar *) context.Rip, &context);
13379 mono_profiler_stat_hit ((guchar *) context.Eip, &context);
13386 setup_stat_profiler (void)
13389 struct itimerval itval;
13390 static int inited = 0;
13391 #ifdef HAVE_LINUX_RTC_H
13392 const char *rtc_freq;
13393 if (!inited && (rtc_freq = g_getenv ("MONO_RTC"))) {
13397 freq = atoi (rtc_freq);
13400 rtc_fd = open ("/dev/rtc", O_RDONLY);
13401 if (rtc_fd == -1) {
13402 perror ("open /dev/rtc");
13405 add_signal_handler (SIGPROF, sigprof_signal_handler);
13406 if (ioctl (rtc_fd, RTC_IRQP_SET, freq) == -1) {
13407 perror ("set rtc freq");
13410 if (ioctl (rtc_fd, RTC_PIE_ON, 0) == -1) {
13411 perror ("start rtc");
13414 if (fcntl (rtc_fd, F_SETSIG, SIGPROF) == -1) {
13418 if (fcntl (rtc_fd, F_SETOWN, getpid ()) == -1) {
13422 enable_rtc_timer (TRUE);
13429 itval.it_interval.tv_usec = 999;
13430 itval.it_interval.tv_sec = 0;
13431 itval.it_value = itval.it_interval;
13432 setitimer (ITIMER_PROF, &itval, NULL);
13436 add_signal_handler (SIGPROF, sigprof_signal_handler);
13437 #elif defined (PLATFORM_WIN32)
13438 static int inited = 0;
13445 if (timeGetDevCaps (&timecaps, sizeof (timecaps)) != TIMERR_NOERROR)
13448 if ((win32_main_thread = OpenThread (READ_CONTROL | THREAD_GET_CONTEXT, FALSE, GetCurrentThreadId ())) == NULL)
13451 if (timeBeginPeriod (1) != TIMERR_NOERROR)
13454 if ((win32_timer = timeSetEvent (1, 0, win32_time_proc, 0, TIME_PERIODIC)) == 0) {
13461 /* mono_jit_create_remoting_trampoline:
13462 * @method: pointer to the method info
13464 * Creates a trampoline which calls the remoting functions. This
13465 * is used in the vtable of transparent proxies.
13467 * Returns: a pointer to the newly created code
13470 mono_jit_create_remoting_trampoline (MonoMethod *method, MonoRemotingTarget target)
13473 guint8 *addr = NULL;
13475 if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
13476 (mono_method_signature (method)->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
13477 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
13478 addr = mono_compile_method (nm);
13480 addr = mono_compile_method (method);
13482 return mono_get_addr_from_ftnptr (addr);
13485 #ifdef MONO_ARCH_HAVE_IMT
13487 mini_get_imt_trampoline (void)
13489 static gpointer tramp = NULL;
13491 tramp = mono_arch_create_specific_trampoline (MONO_FAKE_IMT_METHOD, MONO_TRAMPOLINE_GENERIC, mono_get_root_domain (), NULL);
13496 #ifdef MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
13498 mini_get_vtable_trampoline (void)
13500 static gpointer tramp = NULL;
13502 tramp = mono_arch_create_specific_trampoline (MONO_FAKE_VTABLE_METHOD, MONO_TRAMPOLINE_GENERIC, mono_get_root_domain (), NULL);
13508 mini_parse_debug_options (void)
13510 char *options = getenv ("MONO_DEBUG");
13511 gchar **args, **ptr;
13516 args = g_strsplit (options, ",", -1);
13518 for (ptr = args; ptr && *ptr; ptr++) {
13519 const char *arg = *ptr;
13521 if (!strcmp (arg, "handle-sigint"))
13522 debug_options.handle_sigint = TRUE;
13523 else if (!strcmp (arg, "keep-delegates"))
13524 debug_options.keep_delegates = TRUE;
13525 else if (!strcmp (arg, "collect-pagefault-stats"))
13526 debug_options.collect_pagefault_stats = TRUE;
13527 else if (!strcmp (arg, "break-on-unverified"))
13528 debug_options.break_on_unverified = TRUE;
13529 else if (!strcmp (arg, "no-gdb-backtrace"))
13530 debug_options.no_gdb_backtrace = TRUE;
13532 fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
13533 fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'collect-pagefault-stats', 'break-on-unverified', 'no-gdb-backtrace'\n");
13540 mini_get_debug_options (void)
13542 return &debug_options;
13546 mini_init (const char *filename, const char *runtime_version)
13548 MonoDomain *domain;
13550 MONO_PROBE_VES_INIT_BEGIN ();
13553 if (access ("/proc/self/maps", F_OK) != 0) {
13554 g_print ("Mono requires /proc to be mounted.\n");
13559 /* Happens when using the embedding interface */
13560 if (!default_opt_set)
13561 default_opt = mono_parse_default_optimizations (NULL);
13563 InitializeCriticalSection (&jit_mutex);
13565 if (!global_codeman)
13566 global_codeman = mono_code_manager_new ();
13567 jit_icall_name_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
13569 mono_arch_cpu_init ();
13573 mono_trampolines_init ();
13575 mono_exceptions_init ();
13577 if (!g_thread_supported ())
13578 g_thread_init (NULL);
13580 if (getenv ("MONO_DEBUG") != NULL)
13581 mini_parse_debug_options ();
13583 mono_gc_base_init ();
13585 mono_jit_tls_id = TlsAlloc ();
13586 setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
13590 if (default_opt & MONO_OPT_AOT)
13593 mono_runtime_install_handlers ();
13594 mono_threads_install_cleanup (mini_thread_cleanup);
13596 #ifdef MONO_ARCH_HAVE_NOTIFY_PENDING_EXC
13597 // This is experimental code so provide an env var to switch it off
13598 if (getenv ("MONO_DISABLE_PENDING_EXCEPTIONS")) {
13599 printf ("MONO_DISABLE_PENDING_EXCEPTIONS env var set.\n");
13601 check_for_pending_exc = FALSE;
13602 mono_threads_install_notify_pending_exc (mono_arch_notify_pending_exc);
13606 #define JIT_TRAMPOLINES_WORK
13607 #ifdef JIT_TRAMPOLINES_WORK
13608 mono_install_compile_method (mono_jit_compile_method);
13609 mono_install_free_method (mono_jit_free_method);
13610 mono_install_trampoline (mono_create_jit_trampoline);
13611 mono_install_jump_trampoline (mono_create_jump_trampoline);
13612 mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
13613 mono_install_delegate_trampoline (mono_create_delegate_trampoline);
13615 #define JIT_INVOKE_WORKS
13616 #ifdef JIT_INVOKE_WORKS
13617 mono_install_runtime_invoke (mono_jit_runtime_invoke);
13618 mono_install_handler (mono_arch_get_throw_exception ());
13620 mono_install_stack_walk (mono_jit_walk_stack);
13621 mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
13622 mono_install_get_class_from_name (mono_aot_get_class_from_name);
13623 mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
13625 if (debug_options.collect_pagefault_stats) {
13626 mono_raw_buffer_set_make_unreadable (TRUE);
13627 mono_aot_set_make_unreadable (TRUE);
13630 if (runtime_version)
13631 domain = mono_init_version (filename, runtime_version);
13633 domain = mono_init_from_assembly (filename, filename);
13634 #ifdef MONO_ARCH_HAVE_IMT
13635 mono_install_imt_thunk_builder (mono_arch_build_imt_thunk);
13636 mono_install_imt_trampoline (mini_get_imt_trampoline ());
13637 #if MONO_ARCH_COMMON_VTABLE_TRAMPOLINE
13638 mono_install_vtable_trampoline (mini_get_vtable_trampoline ());
13641 mono_icall_init ();
13643 mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info",
13644 ves_icall_get_frame_info);
13645 mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace",
13646 ves_icall_get_trace);
13647 mono_add_internal_call ("System.Exception::get_trace",
13648 ves_icall_System_Exception_get_trace);
13649 mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityFrame",
13650 ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
13651 mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityStack",
13652 ves_icall_System_Security_SecurityFrame_GetSecurityStack);
13653 mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers",
13654 mono_runtime_install_handlers);
13657 create_helper_signature ();
13659 #define JIT_CALLS_WORK
13660 #ifdef JIT_CALLS_WORK
13661 /* Needs to be called here since register_jit_icall depends on it */
13662 mono_marshal_init ();
13664 mono_arch_register_lowlevel_calls ();
13665 register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
13666 register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
13667 register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
13668 register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
13669 register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
13670 register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "void", TRUE);
13671 register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
13673 register_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
13674 register_icall (mono_arch_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
13675 register_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", "void ptr", TRUE);
13676 #if MONO_ARCH_HAVE_THROW_CORLIB_EXCEPTION
13677 register_icall (mono_arch_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception",
13680 register_icall (mono_thread_get_undeniable_exception, "mono_thread_get_undeniable_exception", "object", FALSE);
13681 register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "void", FALSE);
13682 register_icall (mono_thread_force_interruption_checkpoint, "mono_thread_force_interruption_checkpoint", "void", FALSE);
13683 register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
13684 register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
13687 * NOTE, NOTE, NOTE, NOTE:
13688 * when adding emulation for some opcodes, remember to also add a dummy
13689 * rule to the burg files, because we need the arity information to be correct.
13691 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
13692 mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, TRUE);
13693 mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, FALSE);
13694 mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, FALSE);
13695 mono_register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, FALSE);
13696 mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, FALSE);
13697 mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, FALSE);
13698 mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, FALSE);
13701 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
13702 mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, TRUE);
13703 mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, TRUE);
13704 mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, TRUE);
13707 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
13708 mono_register_opcode_emulation (CEE_DIV, "__emul_idiv", "int32 int32 int32", mono_idiv, FALSE);
13709 mono_register_opcode_emulation (CEE_DIV_UN, "__emul_idiv_un", "int32 int32 int32", mono_idiv_un, FALSE);
13710 mono_register_opcode_emulation (CEE_REM, "__emul_irem", "int32 int32 int32", mono_irem, FALSE);
13711 mono_register_opcode_emulation (CEE_REM_UN, "__emul_irem_un", "int32 int32 int32", mono_irem_un, FALSE);
13714 #ifdef MONO_ARCH_EMULATE_MUL_DIV
13715 mono_register_opcode_emulation (CEE_MUL_OVF, "__emul_imul_ovf", "int32 int32 int32", mono_imul_ovf, FALSE);
13716 mono_register_opcode_emulation (CEE_MUL_OVF_UN, "__emul_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, FALSE);
13717 mono_register_opcode_emulation (CEE_MUL, "__emul_imul", "int32 int32 int32", mono_imul, TRUE);
13719 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_SOFT_FLOAT)
13720 mono_register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, FALSE);
13723 mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, FALSE);
13724 mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, FALSE);
13725 mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, FALSE);
13726 mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, FALSE);
13728 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
13729 mono_register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, FALSE);
13731 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
13732 mono_register_opcode_emulation (CEE_CONV_R_UN, "__emul_conv_r_un", "double int32", mono_conv_to_r8_un, FALSE);
13734 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
13735 mono_register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, FALSE);
13737 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
13738 mono_register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, FALSE);
13740 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
13741 mono_register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", "double long", mono_lconv_to_r8_un, FALSE);
13743 #ifdef MONO_ARCH_EMULATE_FREM
13744 mono_register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, FALSE);
13747 #ifdef MONO_ARCH_SOFT_FLOAT
13748 mono_register_opcode_emulation (OP_FSUB, "__emul_fsub", "double double double", mono_fsub, FALSE);
13749 mono_register_opcode_emulation (OP_FADD, "__emul_fadd", "double double double", mono_fadd, FALSE);
13750 mono_register_opcode_emulation (OP_FMUL, "__emul_fmul", "double double double", mono_fmul, FALSE);
13751 mono_register_opcode_emulation (OP_FNEG, "__emul_fneg", "double double", mono_fneg, FALSE);
13752 mono_register_opcode_emulation (CEE_CONV_R8, "__emul_conv_r8", "double int32", mono_conv_to_r8, FALSE);
13753 mono_register_opcode_emulation (CEE_CONV_R4, "__emul_conv_r4", "double int32", mono_conv_to_r4, FALSE);
13754 mono_register_opcode_emulation (OP_FCONV_TO_R4, "__emul_fconv_to_r4", "double double", mono_fconv_r4, FALSE);
13755 mono_register_opcode_emulation (OP_FCONV_TO_I1, "__emul_fconv_to_i1", "int8 double", mono_fconv_i1, FALSE);
13756 mono_register_opcode_emulation (OP_FCONV_TO_I2, "__emul_fconv_to_i2", "int16 double", mono_fconv_i2, FALSE);
13757 mono_register_opcode_emulation (OP_FCONV_TO_I4, "__emul_fconv_to_i4", "int32 double", mono_fconv_i4, FALSE);
13758 mono_register_opcode_emulation (OP_FCONV_TO_U1, "__emul_fconv_to_u1", "uint8 double", mono_fconv_u1, FALSE);
13759 mono_register_opcode_emulation (OP_FCONV_TO_U2, "__emul_fconv_to_u2", "uint16 double", mono_fconv_u2, FALSE);
13761 mono_register_opcode_emulation (OP_FBEQ, "__emul_fcmp_eq", "uint32 double double", mono_fcmp_eq, FALSE);
13762 mono_register_opcode_emulation (OP_FBLT, "__emul_fcmp_lt", "uint32 double double", mono_fcmp_lt, FALSE);
13763 mono_register_opcode_emulation (OP_FBGT, "__emul_fcmp_gt", "uint32 double double", mono_fcmp_gt, FALSE);
13764 mono_register_opcode_emulation (OP_FBLE, "__emul_fcmp_le", "uint32 double double", mono_fcmp_le, FALSE);
13765 mono_register_opcode_emulation (OP_FBGE, "__emul_fcmp_ge", "uint32 double double", mono_fcmp_ge, FALSE);
13766 mono_register_opcode_emulation (OP_FBNE_UN, "__emul_fcmp_ne_un", "uint32 double double", mono_fcmp_ne_un, FALSE);
13767 mono_register_opcode_emulation (OP_FBLT_UN, "__emul_fcmp_lt_un", "uint32 double double", mono_fcmp_lt_un, FALSE);
13768 mono_register_opcode_emulation (OP_FBGT_UN, "__emul_fcmp_gt_un", "uint32 double double", mono_fcmp_gt_un, FALSE);
13769 mono_register_opcode_emulation (OP_FBLE_UN, "__emul_fcmp_le_un", "uint32 double double", mono_fcmp_le_un, FALSE);
13770 mono_register_opcode_emulation (OP_FBGE_UN, "__emul_fcmp_ge_un", "uint32 double double", mono_fcmp_ge_un, FALSE);
13772 mono_register_opcode_emulation (OP_FCEQ, "__emul_fcmp_ceq", "uint32 double double", mono_fceq, FALSE);
13773 mono_register_opcode_emulation (OP_FCGT, "__emul_fcmp_cgt", "uint32 double double", mono_fcgt, FALSE);
13774 mono_register_opcode_emulation (OP_FCGT_UN, "__emul_fcmp_cgt_un", "uint32 double double", mono_fcgt_un, FALSE);
13775 mono_register_opcode_emulation (OP_FCLT, "__emul_fcmp_clt", "uint32 double double", mono_fclt, FALSE);
13776 mono_register_opcode_emulation (OP_FCLT_UN, "__emul_fcmp_clt_un", "uint32 double double", mono_fclt_un, FALSE);
13778 register_icall (mono_fload_r4, "mono_fload_r4", "double ptr", FALSE);
13779 register_icall (mono_fstore_r4, "mono_fstore_r4", "void double ptr", FALSE);
13780 register_icall (mono_fload_r4_arg, "mono_fload_r4_arg", "uint32 double", FALSE);
13783 #if SIZEOF_VOID_P == 4
13784 mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, TRUE);
13787 /* other jit icalls */
13788 register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
13789 register_icall (mono_class_static_field_address , "mono_class_static_field_address",
13790 "ptr ptr ptr", FALSE);
13791 register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
13792 register_icall (mono_ldtoken_wrapper_generic_shared, "mono_ldtoken_wrapper_generic_shared",
13793 "ptr ptr ptr ptr", FALSE);
13794 register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
13795 register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
13796 register_icall (mono_helper_stelem_ref_check, "helper_stelem_ref_check", "void object object", FALSE);
13797 register_icall (mono_object_new, "mono_object_new", "object ptr ptr", FALSE);
13798 register_icall (mono_object_new_specific, "mono_object_new_specific", "object ptr", FALSE);
13799 register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
13800 register_icall (mono_array_new_specific, "mono_array_new_specific", "object ptr int32", FALSE);
13801 register_icall (mono_runtime_class_init, "mono_runtime_class_init", "void ptr", FALSE);
13802 register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
13803 register_icall (mono_ldftn_nosync, "mono_ldftn_nosync", "ptr ptr", FALSE);
13804 register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
13805 register_icall (mono_helper_compile_generic_method, "compile_generic_method", "ptr object ptr ptr ptr", FALSE);
13806 register_icall (mono_helper_ldstr, "helper_ldstr", "object ptr int", FALSE);
13807 register_icall (mono_helper_ldstr_mscorlib, "helper_ldstr_mscorlib", "object int", FALSE);
13808 register_icall (mono_helper_newobj_mscorlib, "helper_newobj_mscorlib", "object int", FALSE);
13809 register_icall (mono_value_copy, "mono_value_copy", "void ptr ptr ptr", FALSE);
13810 register_icall (mono_helper_get_rgctx_other_ptr, "get_rgctx_other_ptr", "ptr ptr ptr int32 int32 int32 int32", FALSE);
13811 register_icall (mono_object_castclass, "mono_object_castclass", "object object ptr", FALSE);
13812 register_icall (mono_break, "mono_break", NULL, TRUE);
13813 register_icall (mono_create_corlib_exception_0, "mono_create_corlib_exception_0", "object int", TRUE);
13814 register_icall (mono_create_corlib_exception_1, "mono_create_corlib_exception_1", "object int object", TRUE);
13815 register_icall (mono_create_corlib_exception_2, "mono_create_corlib_exception_2", "object int object object", TRUE);
13818 #define JIT_RUNTIME_WORKS
13819 #ifdef JIT_RUNTIME_WORKS
13820 mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
13821 mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
13824 mono_generic_sharing_init ();
13826 mono_thread_attach (domain);
13828 MONO_PROBE_VES_INIT_END ();
13833 MonoJitStats mono_jit_stats = {0};
13836 print_jit_stats (void)
13838 if (mono_jit_stats.enabled) {
13839 g_print ("Mono Jit statistics\n");
13840 g_print ("Compiled methods: %ld\n", mono_jit_stats.methods_compiled);
13841 g_print ("Methods from AOT: %ld\n", mono_jit_stats.methods_aot);
13842 g_print ("Methods cache lookup: %ld\n", mono_jit_stats.methods_lookups);
13843 g_print ("Method trampolines: %ld\n", mono_jit_stats.method_trampolines);
13844 g_print ("Basic blocks: %ld\n", mono_jit_stats.basic_blocks);
13845 g_print ("Max basic blocks: %ld\n", mono_jit_stats.max_basic_blocks);
13846 g_print ("Allocated vars: %ld\n", mono_jit_stats.allocate_var);
13847 g_print ("Analyze stack repeat: %ld\n", mono_jit_stats.analyze_stack_repeat);
13848 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
13849 g_print ("Native code size: %ld\n", mono_jit_stats.native_code_size);
13850 g_print ("Max code size ratio: %.2f (%s::%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
13851 mono_jit_stats.max_ratio_method->klass->name, mono_jit_stats.max_ratio_method->name);
13852 g_print ("Biggest method: %ld (%s::%s)\n", mono_jit_stats.biggest_method_size,
13853 mono_jit_stats.biggest_method->klass->name, mono_jit_stats.biggest_method->name);
13854 g_print ("Code reallocs: %ld\n", mono_jit_stats.code_reallocs);
13855 g_print ("Allocated code size: %ld\n", mono_jit_stats.allocated_code_size);
13856 g_print ("Inlineable methods: %ld\n", mono_jit_stats.inlineable_methods);
13857 g_print ("Inlined methods: %ld\n", mono_jit_stats.inlined_methods);
13858 g_print ("Locals stack size: %ld\n", mono_jit_stats.locals_stack_size);
13860 g_print ("\nCreated object count: %ld\n", mono_stats.new_object_count);
13861 g_print ("Delegates created: %ld\n", mono_stats.delegate_creations);
13862 g_print ("Initialized classes: %ld\n", mono_stats.initialized_class_count);
13863 g_print ("Used classes: %ld\n", mono_stats.used_class_count);
13864 g_print ("Generic vtables: %ld\n", mono_stats.generic_vtable_count);
13865 g_print ("Methods: %ld\n", mono_stats.method_count);
13866 g_print ("Static data size: %ld\n", mono_stats.class_static_data_size);
13867 g_print ("VTable data size: %ld\n", mono_stats.class_vtable_size);
13868 g_print ("Mscorlib mempool size: %d\n", mono_mempool_get_allocated (mono_defaults.corlib->mempool));
13870 g_print ("\nGeneric instances: %ld\n", mono_stats.generic_instance_count);
13871 g_print ("Initialized classes: %ld\n", mono_stats.generic_class_count);
13872 g_print ("Inflated methods: %ld / %ld\n", mono_stats.inflated_method_count_2,
13873 mono_stats.inflated_method_count);
13874 g_print ("Inflated types: %ld\n", mono_stats.inflated_type_count);
13875 g_print ("Generics metadata size: %ld\n", mono_stats.generics_metadata_size);
13876 g_print ("Generics virtual invokes: %ld\n", mono_jit_stats.generic_virtual_invocations);
13878 g_print ("Sharable generic methods: %ld\n", mono_stats.generics_sharable_methods);
13879 g_print ("Unsharable generic methods: %ld\n", mono_stats.generics_unsharable_methods);
13880 g_print ("Shared generic methods: %ld\n", mono_stats.generics_shared_methods);
13882 g_print ("Dynamic code allocs: %ld\n", mono_stats.dynamic_code_alloc_count);
13883 g_print ("Dynamic code bytes: %ld\n", mono_stats.dynamic_code_bytes_count);
13884 g_print ("Dynamic code frees: %ld\n", mono_stats.dynamic_code_frees_count);
13886 g_print ("IMT tables size: %ld\n", mono_stats.imt_tables_size);
13887 g_print ("IMT number of tables: %ld\n", mono_stats.imt_number_of_tables);
13888 g_print ("IMT number of methods: %ld\n", mono_stats.imt_number_of_methods);
13889 g_print ("IMT used slots: %ld\n", mono_stats.imt_used_slots);
13890 g_print ("IMT colliding slots: %ld\n", mono_stats.imt_slots_with_collisions);
13891 g_print ("IMT max collisions: %ld\n", mono_stats.imt_max_collisions_in_slot);
13892 g_print ("IMT methods at max col: %ld\n", mono_stats.imt_method_count_when_max_collisions);
13893 g_print ("IMT thunks size: %ld\n", mono_stats.imt_thunks_size);
13895 g_print ("JIT info table inserts: %ld\n", mono_stats.jit_info_table_insert_count);
13896 g_print ("JIT info table removes: %ld\n", mono_stats.jit_info_table_remove_count);
13897 g_print ("JIT info table lookups: %ld\n", mono_stats.jit_info_table_lookup_count);
13899 g_print ("Hazardous pointers: %ld\n", mono_stats.hazardous_pointer_count);
13900 #ifdef HAVE_SGEN_GC
13901 g_print ("Minor GC collections: %ld\n", mono_stats.minor_gc_count);
13902 g_print ("Major GC collections: %ld\n", mono_stats.major_gc_count);
13903 g_print ("Minor GC time in msecs: %lf\n", (double)mono_stats.minor_gc_time_usecs / 1000.0);
13904 g_print ("Major GC time in msecs: %lf\n", (double)mono_stats.major_gc_time_usecs / 1000.0);
13906 if (mono_security_get_mode () == MONO_SECURITY_MODE_CAS) {
13907 g_print ("\nDecl security check : %ld\n", mono_jit_stats.cas_declsec_check);
13908 g_print ("LinkDemand (user) : %ld\n", mono_jit_stats.cas_linkdemand);
13909 g_print ("LinkDemand (icall) : %ld\n", mono_jit_stats.cas_linkdemand_icall);
13910 g_print ("LinkDemand (pinvoke) : %ld\n", mono_jit_stats.cas_linkdemand_pinvoke);
13911 g_print ("LinkDemand (aptc) : %ld\n", mono_jit_stats.cas_linkdemand_aptc);
13912 g_print ("Demand (code gen) : %ld\n", mono_jit_stats.cas_demand_generation);
13914 if (debug_options.collect_pagefault_stats) {
13915 g_print ("Metadata pagefaults : %d\n", mono_raw_buffer_get_n_pagefaults ());
13916 g_print ("AOT pagefaults : %d\n", mono_aot_get_n_pagefaults ());
13922 mini_cleanup (MonoDomain *domain)
13924 #ifdef HAVE_LINUX_RTC_H
13926 enable_rtc_timer (FALSE);
13930 * mono_runtime_cleanup() and mono_domain_finalize () need to
13931 * be called early since they need the execution engine still
13932 * fully working (mono_domain_finalize may invoke managed finalizers
13933 * and mono_runtime_cleanup will wait for other threads to finish).
13935 mono_domain_finalize (domain, 2000);
13937 /* This accesses metadata so needs to be called before runtime shutdown */
13938 print_jit_stats ();
13940 mono_runtime_cleanup (domain);
13942 mono_profiler_shutdown ();
13944 mono_icall_cleanup ();
13946 mono_runtime_cleanup_handlers ();
13948 mono_domain_free (domain, TRUE);
13950 mono_debugger_cleanup ();
13952 mono_trampolines_cleanup ();
13954 mono_code_manager_destroy (global_codeman);
13955 g_hash_table_destroy (jit_icall_name_hash);
13956 g_free (emul_opcode_map);
13958 mono_arch_cleanup ();
13962 mono_trace_cleanup ();
13964 mono_counters_dump (-1, stdout);
13966 if (mono_inject_async_exc_method)
13967 mono_method_desc_free (mono_inject_async_exc_method);
13969 TlsFree(mono_jit_tls_id);
13971 DeleteCriticalSection (&jit_mutex);
13973 DeleteCriticalSection (&mono_delegate_section);
13977 mono_set_defaults (int verbose_level, guint32 opts)
13979 mini_verbose = verbose_level;
13980 default_opt = opts;
13981 default_opt_set = TRUE;
13985 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
13987 GHashTable *assemblies = (GHashTable*)user_data;
13988 MonoImage *image = mono_assembly_get_image (ass);
13989 MonoMethod *method, *invoke;
13992 if (g_hash_table_lookup (assemblies, ass))
13995 g_hash_table_insert (assemblies, ass, ass);
13997 if (mini_verbose > 0)
13998 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
14000 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
14001 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
14002 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
14006 if (mini_verbose > 1) {
14007 char * desc = mono_method_full_name (method, TRUE);
14008 g_print ("Compiling %d %s\n", count, desc);
14011 mono_compile_method (method);
14012 if (strcmp (method->name, "Finalize") == 0) {
14013 invoke = mono_marshal_get_runtime_invoke (method);
14014 mono_compile_method (invoke);
14016 if (method->klass->marshalbyref && mono_method_signature (method)->hasthis) {
14017 invoke = mono_marshal_get_remoting_invoke_with_check (method);
14018 mono_compile_method (invoke);
14022 /* Load and precompile referenced assemblies as well */
14023 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
14024 mono_assembly_load_reference (image, i);
14025 if (image->references [i])
14026 mono_precompile_assembly (image->references [i], assemblies);
14030 void mono_precompile_assemblies ()
14032 GHashTable *assemblies = g_hash_table_new (NULL, NULL);
14034 mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
14036 g_hash_table_destroy (assemblies);