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 sun // Solaris x86
18 #include <sys/types.h>
19 #include <sys/ucontext.h>
22 #ifdef HAVE_VALGRIND_MEMCHECK_H
23 #include <valgrind/memcheck.h>
26 #include <mono/metadata/assembly.h>
27 #include <mono/metadata/loader.h>
28 #include <mono/metadata/cil-coff.h>
29 #include <mono/metadata/tabledefs.h>
30 #include <mono/metadata/class.h>
31 #include <mono/metadata/object.h>
32 #include <mono/metadata/exception.h>
33 #include <mono/metadata/opcodes.h>
34 #include <mono/metadata/mono-endian.h>
35 #include <mono/metadata/tokentype.h>
36 #include <mono/metadata/tabledefs.h>
37 #include <mono/metadata/threads.h>
38 #include <mono/metadata/marshal.h>
39 #include <mono/metadata/socket-io.h>
40 #include <mono/metadata/appdomain.h>
41 #include <mono/metadata/debug-helpers.h>
42 #include <mono/io-layer/io-layer.h>
43 #include "mono/metadata/profiler.h"
44 #include <mono/metadata/profiler-private.h>
45 #include <mono/metadata/mono-config.h>
46 #include <mono/metadata/environment.h>
47 #include <mono/metadata/mono-debug.h>
48 #include <mono/metadata/monitor.h>
49 #include <mono/metadata/security-manager.h>
50 #include <mono/metadata/threads-types.h>
51 #include <mono/metadata/rawbuffer.h>
52 #include <mono/utils/mono-math.h>
53 #include <mono/utils/mono-compiler.h>
54 #include <mono/utils/mono-counters.h>
55 #include <mono/os/gc_wrapper.h>
63 #include "jit-icalls.h"
67 #define BRANCH_COST 100
68 #define INLINE_LENGTH_LIMIT 20
71 * this is used to determine when some branch optimizations are possible: we exclude FP compares
72 * because they have weird semantics with NaNs.
74 #define MONO_IS_COND_BRANCH_OP(ins) (((ins)->opcode >= CEE_BEQ && (ins)->opcode <= CEE_BLT_UN) || ((ins)->opcode >= OP_LBEQ && (ins)->opcode <= OP_LBLT_UN) || ((ins)->opcode >= OP_FBEQ && (ins)->opcode <= OP_FBLT_UN) || ((ins)->opcode >= OP_IBEQ && (ins)->opcode <= OP_IBLT_UN))
75 #define MONO_IS_COND_BRANCH_NOFP(ins) (MONO_IS_COND_BRANCH_OP(ins) && (ins)->inst_left->inst_left->type != STACK_R8)
77 #define MONO_CHECK_THIS(ins) (mono_method_signature (cfg->method)->hasthis && (ins)->ssa_op == MONO_SSA_LOAD && (ins)->inst_left->inst_c0 == 0)
79 static void setup_stat_profiler (void);
80 gboolean mono_arch_print_tree(MonoInst *tree, int arity);
81 static gpointer mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt);
82 static gpointer mono_jit_compile_method (MonoMethod *method);
83 static gpointer mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method);
84 static gpointer mono_create_jit_trampoline_in_domain (MonoDomain *domain, MonoMethod *method);
86 static void handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src,
87 const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native);
89 static void dec_foreach (MonoInst *tree, MonoCompile *cfg);
91 static int mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock,
92 int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args,
93 guint inline_offset, gboolean is_virtual_call);
95 /* helper methods signature */
96 static MonoMethodSignature *helper_sig_class_init_trampoline = NULL;
97 static MonoMethodSignature *helper_sig_domain_get = NULL;
99 static guint32 default_opt = 0;
101 guint32 mono_jit_tls_id = -1;
102 MonoTraceSpec *mono_jit_trace_calls = NULL;
103 gboolean mono_break_on_exc = FALSE;
105 gboolean mono_compile_aot = FALSE;
107 gboolean mono_use_security_manager = FALSE;
109 static int mini_verbose = 0;
111 #define mono_jit_lock() EnterCriticalSection (&jit_mutex)
112 #define mono_jit_unlock() LeaveCriticalSection (&jit_mutex)
113 static CRITICAL_SECTION jit_mutex;
115 static GHashTable *class_init_hash_addr = NULL;
117 static MonoCodeManager *global_codeman = NULL;
119 static GHashTable *jit_icall_name_hash = NULL;
121 static MonoDebugOptions debug_options;
124 * Address of the trampoline code. This is used by the debugger to check
125 * whether a method is a trampoline.
127 guint8* mono_trampoline_code [MONO_TRAMPOLINE_NUM];
130 mono_running_on_valgrind (void)
132 #ifdef HAVE_VALGRIND_MEMCHECK_H
133 if (RUNNING_ON_VALGRIND)
143 * mono_create_ftnptr:
145 * Given a function address, create a function descriptor for it.
146 * This is only needed on IA64.
149 mono_create_ftnptr (MonoDomain *domain, gpointer addr)
154 mono_domain_lock (domain);
155 desc = mono_code_manager_reserve (domain->code_mp, 2 * sizeof (gpointer));
156 mono_domain_unlock (domain);
173 find_tramp (gpointer key, gpointer value, gpointer user_data)
175 FindTrampUserData *ud = (FindTrampUserData*)user_data;
178 ud->method = (MonoMethod*)key;
182 G_GNUC_UNUSED static char*
183 get_method_from_ip (void *ip)
189 MonoDomain *domain = mono_domain_get ();
190 FindTrampUserData user_data;
192 ji = mono_jit_info_table_find (domain, ip);
195 user_data.method = NULL;
196 mono_domain_lock (domain);
197 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
198 mono_domain_unlock (domain);
199 if (user_data.method) {
200 char *mname = mono_method_full_name (user_data.method, TRUE);
201 res = g_strdup_printf ("<%p - JIT trampoline for %s>", ip, mname);
208 method = mono_method_full_name (ji->method, TRUE);
209 source = mono_debug_source_location_from_address (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), NULL, domain);
211 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);
222 return get_method_from_ip (ip);
227 mono_print_method_from_ip (void *ip)
232 MonoDomain *domain = mono_domain_get ();
233 FindTrampUserData user_data;
235 ji = mono_jit_info_table_find (domain, ip);
238 user_data.method = NULL;
239 mono_domain_lock (domain);
240 g_hash_table_foreach (domain->jit_trampoline_hash, find_tramp, &user_data);
241 mono_domain_unlock (domain);
242 if (user_data.method) {
243 char *mname = mono_method_full_name (user_data.method, TRUE);
244 printf ("IP %p is a JIT trampoline for %s\n", ip, mname);
248 g_print ("No method at %p\n", ip);
251 method = mono_method_full_name (ji->method, TRUE);
252 source = mono_debug_source_location_from_address (ji->method, (guint32)((guint8*)ip - (guint8*)ji->code_start), NULL, domain);
254 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);
257 g_print ("%s\n", source);
264 * mono_method_same_domain:
266 * Determine whenever two compiled methods are in the same domain, thus
267 * the address of the callee can be embedded in the caller.
269 gboolean mono_method_same_domain (MonoJitInfo *caller, MonoJitInfo *callee)
271 if (!caller || !callee)
275 * If the call was made from domain-neutral to domain-specific
276 * code, we can't patch the call site.
278 if (caller->domain_neutral && !callee->domain_neutral)
281 if ((caller->method->klass == mono_defaults.appdomain_class) &&
282 (strstr (caller->method->name, "InvokeInDomain"))) {
283 /* The InvokeInDomain methods change the current appdomain */
291 * mono_global_codeman_reserve:
293 * Allocate code memory from the global code manager.
295 void *mono_global_codeman_reserve (int size)
299 if (!global_codeman) {
300 /* This can happen during startup */
301 global_codeman = mono_code_manager_new ();
302 return mono_code_manager_reserve (global_codeman, size);
306 ptr = mono_code_manager_reserve (global_codeman, size);
313 mono_jump_info_token_new (MonoMemPool *mp, MonoImage *image, guint32 token)
315 MonoJumpInfoToken *res = mono_mempool_alloc0 (mp, sizeof (MonoJumpInfoToken));
322 #define MONO_INIT_VARINFO(vi,id) do { \
323 (vi)->range.first_use.pos.bid = 0xffff; \
329 * Basic blocks have two numeric identifiers:
330 * dfn: Depth First Number
331 * block_num: unique ID assigned at bblock creation
333 #define NEW_BBLOCK(cfg) (mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock)))
334 #define ADD_BBLOCK(cfg,bbhash,b) do { \
335 g_hash_table_insert (bbhash, (b)->cil_code, (b)); \
336 (b)->block_num = cfg->num_bblocks++; \
337 (b)->real_offset = real_offset; \
340 #define GET_BBLOCK(cfg,bbhash,tblock,ip) do { \
341 (tblock) = g_hash_table_lookup (bbhash, (ip)); \
343 if ((ip) >= end || (ip) < header->code) goto unverified; \
344 (tblock) = NEW_BBLOCK (cfg); \
345 (tblock)->cil_code = (ip); \
346 ADD_BBLOCK (cfg, (bbhash), (tblock)); \
350 #define CHECK_BBLOCK(target,ip,tblock) do { \
351 if ((target) < (ip) && !(tblock)->code) { \
352 bb_recheck = g_list_prepend (bb_recheck, (tblock)); \
353 if (cfg->verbose_level > 2) 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)); \
357 #define NEW_ICONST(cfg,dest,val) do { \
358 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
359 (dest)->opcode = OP_ICONST; \
360 (dest)->inst_c0 = (val); \
361 (dest)->type = STACK_I4; \
364 #define NEW_PCONST(cfg,dest,val) do { \
365 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
366 (dest)->opcode = OP_PCONST; \
367 (dest)->inst_p0 = (val); \
368 (dest)->type = STACK_PTR; \
372 #ifdef MONO_ARCH_NEED_GOT_VAR
374 #define NEW_PATCH_INFO(cfg,dest,el1,el2) do { \
375 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
376 (dest)->opcode = OP_PATCH_INFO; \
377 (dest)->inst_left = (gpointer)(el1); \
378 (dest)->inst_right = (gpointer)(el2); \
381 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do { \
382 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
383 (dest)->opcode = cfg->compile_aot ? OP_GOT_ENTRY : OP_PCONST; \
384 if (cfg->compile_aot) { \
385 MonoInst *group, *got_var, *got_loc; \
386 got_loc = mono_get_got_var (cfg); \
387 NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0); \
388 NEW_PATCH_INFO ((cfg), group, cons, patch_type); \
389 (dest)->inst_p0 = got_var; \
390 (dest)->inst_p1 = group; \
392 (dest)->inst_p0 = (cons); \
393 (dest)->inst_i1 = (gpointer)(patch_type); \
395 (dest)->type = STACK_PTR; \
398 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type) do { \
399 MonoInst *group, *got_var, *got_loc; \
400 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
401 (dest)->opcode = OP_GOT_ENTRY; \
402 got_loc = mono_get_got_var (cfg); \
403 NEW_TEMPLOAD ((cfg), got_var, got_loc->inst_c0); \
404 NEW_PATCH_INFO ((cfg), group, NULL, patch_type); \
405 group->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token)); \
406 (dest)->inst_p0 = got_var; \
407 (dest)->inst_p1 = group; \
408 (dest)->type = (stack_type); \
413 #define NEW_AOTCONST(cfg,dest,patch_type,cons) do { \
414 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
415 (dest)->opcode = cfg->compile_aot ? OP_AOTCONST : OP_PCONST; \
416 (dest)->inst_p0 = (cons); \
417 (dest)->inst_i1 = (gpointer)(patch_type); \
418 (dest)->type = STACK_PTR; \
421 #define NEW_AOTCONST_TOKEN(cfg,dest,patch_type,image,token,stack_type) do { \
422 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
423 (dest)->opcode = OP_AOTCONST; \
424 (dest)->inst_p0 = mono_jump_info_token_new ((cfg)->mempool, (image), (token)); \
425 (dest)->inst_p1 = (gpointer)(patch_type); \
426 (dest)->type = (stack_type); \
431 #define NEW_CLASSCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_CLASS, (val))
433 #define NEW_IMAGECONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_IMAGE, (val))
435 #define NEW_FIELDCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_FIELD, (val))
437 #define NEW_METHODCONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_METHODCONST, (val))
439 #define NEW_VTABLECONST(cfg,dest,vtable) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_VTABLE, cfg->compile_aot ? (gpointer)((vtable)->klass) : (vtable))
441 #define NEW_SFLDACONST(cfg,dest,val) NEW_AOTCONST ((cfg), (dest), MONO_PATCH_INFO_SFLDA, (val))
443 #define NEW_LDSTRCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDSTR, (image), (token), STACK_OBJ)
445 #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)
447 #define NEW_LDTOKENCONST(cfg,dest,image,token) NEW_AOTCONST_TOKEN ((cfg), (dest), MONO_PATCH_INFO_LDTOKEN, (image), (token), STACK_PTR)
449 #define NEW_DECLSECCONST(cfg,dest,image,entry) do { \
450 if (cfg->compile_aot) { \
451 NEW_AOTCONST_TOKEN (cfg, dest, MONO_PATCH_INFO_DECLSEC, image, (entry).index, STACK_OBJ); \
453 NEW_PCONST (cfg, args [0], (entry).blob); \
457 #define NEW_DOMAINCONST(cfg,dest) do { \
458 if (cfg->opt & MONO_OPT_SHARED) { \
459 /* avoid depending on undefined C behavior in sequence points */ \
460 MonoInst* __domain_var = mono_get_domainvar (cfg); \
461 NEW_TEMPLOAD (cfg, dest, __domain_var->inst_c0); \
463 NEW_PCONST (cfg, dest, (cfg)->domain); \
467 #define GET_VARINFO_INST(cfg,num) ((cfg)->varinfo [(num)]->inst)
469 #define NEW_ARGLOAD(cfg,dest,num) do { \
470 if (arg_array [(num)]->opcode == OP_ICONST) (dest) = arg_array [(num)]; else { \
471 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
472 (dest)->ssa_op = MONO_SSA_LOAD; \
473 (dest)->inst_i0 = arg_array [(num)]; \
474 (dest)->opcode = mono_type_to_ldind ((dest)->inst_i0->inst_vtype); \
475 type_to_eval_stack_type (param_types [(num)], (dest)); \
476 (dest)->klass = (dest)->inst_i0->klass; \
479 #define NEW_LOCLOAD(cfg,dest,num) do { \
480 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
481 (dest)->ssa_op = MONO_SSA_LOAD; \
482 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)]; \
483 (dest)->opcode = mono_type_to_ldind ((dest)->inst_i0->inst_vtype); \
484 type_to_eval_stack_type (header->locals [(num)], (dest)); \
485 (dest)->klass = (dest)->inst_i0->klass; \
488 #define NEW_LOCLOADA(cfg,dest,num) do { \
489 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
490 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN; \
491 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)]; \
492 (dest)->inst_i0->flags |= MONO_INST_INDIRECT; \
493 (dest)->opcode = OP_LDADDR; \
494 (dest)->type = STACK_MP; \
495 (dest)->klass = (dest)->inst_i0->klass; \
496 if (!MONO_TYPE_ISSTRUCT (header->locals [(num)])) \
497 (cfg)->disable_ssa = TRUE; \
500 #define NEW_RETLOADA(cfg,dest) do { \
501 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
502 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN; \
503 (dest)->inst_i0 = (cfg)->ret; \
504 (dest)->inst_i0->flags |= MONO_INST_INDIRECT; \
505 (dest)->opcode = cfg->ret_var_is_local ? OP_LDADDR : CEE_LDIND_I; \
506 (dest)->type = STACK_MP; \
507 (dest)->klass = (dest)->inst_i0->klass; \
508 (cfg)->disable_ssa = TRUE; \
511 #define NEW_ARGLOADA(cfg,dest,num) do { \
512 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
513 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
514 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN; \
515 (dest)->inst_i0 = arg_array [(num)]; \
516 (dest)->inst_i0->flags |= MONO_INST_INDIRECT; \
517 (dest)->opcode = OP_LDADDR; \
518 (dest)->type = STACK_MP; \
519 (dest)->klass = (dest)->inst_i0->klass; \
520 (cfg)->disable_ssa = TRUE; \
523 #define NEW_TEMPLOAD(cfg,dest,num) do { \
524 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
525 (dest)->ssa_op = MONO_SSA_LOAD; \
526 (dest)->inst_i0 = (cfg)->varinfo [(num)]; \
527 (dest)->opcode = mono_type_to_ldind ((dest)->inst_i0->inst_vtype); \
528 type_to_eval_stack_type ((dest)->inst_i0->inst_vtype, (dest)); \
529 (dest)->klass = (dest)->inst_i0->klass; \
532 #define NEW_TEMPLOADA(cfg,dest,num) do { \
533 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
534 (dest)->ssa_op = MONO_SSA_ADDRESS_TAKEN; \
535 (dest)->inst_i0 = (cfg)->varinfo [(num)]; \
536 (dest)->inst_i0->flags |= MONO_INST_INDIRECT; \
537 (dest)->opcode = OP_LDADDR; \
538 (dest)->type = STACK_MP; \
539 (dest)->klass = (dest)->inst_i0->klass; \
540 if (!MONO_TYPE_ISSTRUCT (cfg->varinfo [(num)]->inst_vtype)) \
541 (cfg)->disable_ssa = TRUE; \
545 #define NEW_INDLOAD(cfg,dest,addr,vtype) do { \
546 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
547 (dest)->inst_left = addr; \
548 (dest)->opcode = mono_type_to_ldind (vtype); \
549 type_to_eval_stack_type (vtype, (dest)); \
550 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/ \
553 #define NEW_INDSTORE(cfg,dest,addr,value,vtype) do { \
554 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
555 (dest)->inst_i0 = addr; \
556 (dest)->opcode = mono_type_to_stind (vtype); \
557 (dest)->inst_i1 = (value); \
558 /* FIXME: (dest)->klass = (dest)->inst_i0->klass;*/ \
561 #define NEW_TEMPSTORE(cfg,dest,num,inst) do { \
562 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
563 (dest)->ssa_op = MONO_SSA_STORE; \
564 (dest)->inst_i0 = (cfg)->varinfo [(num)]; \
565 (dest)->opcode = mono_type_to_stind ((dest)->inst_i0->inst_vtype); \
566 (dest)->inst_i1 = (inst); \
567 (dest)->klass = (dest)->inst_i0->klass; \
570 #define NEW_LOCSTORE(cfg,dest,num,inst) do { \
571 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
572 (dest)->opcode = mono_type_to_stind (header->locals [(num)]); \
573 (dest)->ssa_op = MONO_SSA_STORE; \
574 (dest)->inst_i0 = (cfg)->varinfo [locals_offset + (num)]; \
575 (dest)->inst_i1 = (inst); \
576 (dest)->klass = (dest)->inst_i0->klass; \
579 #define NEW_ARGSTORE(cfg,dest,num,inst) do { \
580 if (arg_array [(num)]->opcode == OP_ICONST) goto inline_failure; \
581 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
582 (dest)->opcode = mono_type_to_stind (param_types [(num)]); \
583 (dest)->ssa_op = MONO_SSA_STORE; \
584 (dest)->inst_i0 = arg_array [(num)]; \
585 (dest)->inst_i1 = (inst); \
586 (dest)->klass = (dest)->inst_i0->klass; \
589 #define NEW_DUMMY_USE(cfg,dest,load) do { \
590 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
591 (dest)->opcode = OP_DUMMY_USE; \
592 (dest)->inst_left = (load); \
595 #define NEW_DUMMY_STORE(cfg,dest,num) do { \
596 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
597 (dest)->inst_i0 = (cfg)->varinfo [(num)]; \
598 (dest)->opcode = OP_DUMMY_STORE; \
599 (dest)->klass = (dest)->inst_i0->klass; \
602 #define ADD_BINOP(op) do { \
603 MONO_INST_NEW (cfg, ins, (op)); \
604 ins->cil_code = ip; \
606 ins->inst_i0 = sp [0]; \
607 ins->inst_i1 = sp [1]; \
609 type_from_op (ins); \
613 #define ADD_UNOP(op) do { \
614 MONO_INST_NEW (cfg, ins, (op)); \
615 ins->cil_code = ip; \
617 ins->inst_i0 = sp [0]; \
619 type_from_op (ins); \
623 #define ADD_BINCOND(next_block) do { \
626 MONO_INST_NEW(cfg, cmp, OP_COMPARE); \
627 cmp->inst_i0 = sp [0]; \
628 cmp->inst_i1 = sp [1]; \
629 cmp->cil_code = ins->cil_code; \
630 type_from_op (cmp); \
632 ins->inst_i0 = cmp; \
633 MONO_ADD_INS (bblock, ins); \
634 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2); \
635 GET_BBLOCK (cfg, bbhash, tblock, target); \
636 link_bblock (cfg, bblock, tblock); \
637 ins->inst_true_bb = tblock; \
638 CHECK_BBLOCK (target, ip, tblock); \
639 if ((next_block)) { \
640 link_bblock (cfg, bblock, (next_block)); \
641 ins->inst_false_bb = (next_block); \
642 start_new_bblock = 1; \
644 GET_BBLOCK (cfg, bbhash, tblock, ip); \
645 link_bblock (cfg, bblock, tblock); \
646 ins->inst_false_bb = tblock; \
647 start_new_bblock = 2; \
651 /* FIXME: handle float, long ... */
652 #define ADD_UNCOND(istrue) do { \
655 MONO_INST_NEW(cfg, cmp, OP_COMPARE); \
656 cmp->inst_i0 = sp [0]; \
657 switch (cmp->inst_i0->type) { \
659 cmp->inst_i1 = zero_int64; break; \
661 cmp->inst_i1 = zero_r8; break; \
664 cmp->inst_i1 = zero_ptr; break; \
666 cmp->inst_i1 = zero_obj; break; \
668 cmp->inst_i1 = zero_int32; \
670 cmp->cil_code = ins->cil_code; \
671 type_from_op (cmp); \
673 ins->inst_i0 = cmp; \
674 ins->opcode = (istrue)? CEE_BNE_UN: CEE_BEQ; \
675 MONO_ADD_INS (bblock, ins); \
676 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof(gpointer)*2); \
677 GET_BBLOCK (cfg, bbhash, tblock, target); \
678 link_bblock (cfg, bblock, tblock); \
679 ins->inst_true_bb = tblock; \
680 CHECK_BBLOCK (target, ip, tblock); \
681 GET_BBLOCK (cfg, bbhash, tblock, ip); \
682 link_bblock (cfg, bblock, tblock); \
683 ins->inst_false_bb = tblock; \
684 start_new_bblock = 2; \
687 #define NEW_LDELEMA(cfg,dest,sp,k) do { \
688 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
689 (dest)->opcode = CEE_LDELEMA; \
690 (dest)->inst_left = (sp) [0]; \
691 (dest)->inst_right = (sp) [1]; \
692 (dest)->type = STACK_MP; \
693 (dest)->klass = (k); \
694 (cfg)->flags |= MONO_CFG_HAS_LDELEMA; \
697 #define NEW_GROUP(cfg,dest,el1,el2) do { \
698 (dest) = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoInst)); \
699 (dest)->opcode = OP_GROUP; \
700 (dest)->inst_left = (el1); \
701 (dest)->inst_right = (el2); \
706 compare_bblock (gconstpointer a, gconstpointer b)
708 const MonoBasicBlock *b1 = a;
709 const MonoBasicBlock *b2 = b;
711 return b2->cil_code - b1->cil_code;
716 * link_bblock: Links two basic blocks
718 * links two basic blocks in the control flow graph, the 'from'
719 * argument is the starting block and the 'to' argument is the block
720 * the control flow ends to after 'from'.
723 link_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
725 MonoBasicBlock **newa;
729 if (from->cil_code) {
731 g_print ("edge from IL%04x to IL_%04x\n", from->cil_code - cfg->cil_code, to->cil_code - cfg->cil_code);
733 g_print ("edge from IL%04x to exit\n", from->cil_code - cfg->cil_code);
736 g_print ("edge from entry to IL_%04x\n", to->cil_code - cfg->cil_code);
738 g_print ("edge from entry to exit\n");
742 for (i = 0; i < from->out_count; ++i) {
743 if (to == from->out_bb [i]) {
749 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count + 1));
750 for (i = 0; i < from->out_count; ++i) {
751 newa [i] = from->out_bb [i];
759 for (i = 0; i < to->in_count; ++i) {
760 if (from == to->in_bb [i]) {
766 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count + 1));
767 for (i = 0; i < to->in_count; ++i) {
768 newa [i] = to->in_bb [i];
777 * mono_unlink_bblock:
779 * Unlink two basic blocks.
782 mono_unlink_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
784 MonoBasicBlock **newa;
789 * In theory, count could only have the value 0 or 1, but some branch opts
790 * are still buggy, causing the same bblock to appear in in/out_bb multiple
794 for (i = 0; i < from->out_count; ++i) {
795 if (to == from->out_bb [i])
799 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (from->out_count - count));
801 for (i = 0; i < from->out_count; ++i) {
802 if (from->out_bb [i] != to)
803 newa [pos ++] = from->out_bb [i];
805 from->out_count -= count;
810 for (i = 0; i < to->in_count; ++i) {
811 if (from == to->in_bb [i])
815 newa = mono_mempool_alloc (cfg->mempool, sizeof (gpointer) * (to->in_count - count));
817 for (i = 0; i < to->in_count; ++i) {
818 if (to->in_bb [i] != from)
819 newa [pos ++] = to->in_bb [i];
821 to->in_count -= count;
827 * mono_find_block_region:
829 * We mark each basic block with a region ID. We use that to avoid BB
830 * optimizations when blocks are in different regions.
833 * A region token that encodes where this region is, and information
834 * about the clause owner for this block.
836 * The region encodes the try/catch/filter clause that owns this block
837 * as well as the type. -1 is a special value that represents a block
838 * that is in none of try/catch/filter.
841 mono_find_block_region (MonoCompile *cfg, int offset)
843 MonoMethod *method = cfg->method;
844 MonoMethodHeader *header = mono_method_get_header (method);
845 MonoExceptionClause *clause;
848 /* first search for handlers and filters */
849 for (i = 0; i < header->num_clauses; ++i) {
850 clause = &header->clauses [i];
851 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
852 (offset < (clause->handler_offset)))
853 return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
855 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
856 if (clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY)
857 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
859 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
863 /* search the try blocks */
864 for (i = 0; i < header->num_clauses; ++i) {
865 clause = &header->clauses [i];
866 if (MONO_OFFSET_IN_CLAUSE (clause, offset))
867 return ((i + 1) << 8) | clause->flags;
874 mono_find_final_block (MonoCompile *cfg, unsigned char *ip, unsigned char *target, int type)
876 MonoMethod *method = cfg->method;
877 MonoMethodHeader *header = mono_method_get_header (method);
878 MonoExceptionClause *clause;
879 MonoBasicBlock *handler;
883 for (i = 0; i < header->num_clauses; ++i) {
884 clause = &header->clauses [i];
885 if (MONO_OFFSET_IN_CLAUSE (clause, (ip - header->code)) &&
886 (!MONO_OFFSET_IN_CLAUSE (clause, (target - header->code)))) {
887 if (clause->flags == type) {
888 handler = g_hash_table_lookup (cfg->bb_hash, header->code + clause->handler_offset);
890 res = g_list_append (res, handler);
898 mono_find_spvar_for_region (MonoCompile *cfg, int region)
900 return g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
904 mono_create_spvar_for_region (MonoCompile *cfg, int region)
908 var = g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
912 var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
913 /* prevent it from being register allocated */
914 var->flags |= MONO_INST_INDIRECT;
916 g_hash_table_insert (cfg->spvars, GINT_TO_POINTER (region), var);
920 mono_find_exvar_for_offset (MonoCompile *cfg, int offset)
922 return g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
926 mono_create_exvar_for_offset (MonoCompile *cfg, int offset)
930 var = g_hash_table_lookup (cfg->exvars, GINT_TO_POINTER (offset));
934 var = mono_compile_create_var (cfg, &mono_defaults.object_class->byval_arg, OP_LOCAL);
935 /* prevent it from being register allocated */
936 var->flags |= MONO_INST_INDIRECT;
938 g_hash_table_insert (cfg->exvars, GINT_TO_POINTER (offset), var);
944 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
948 array [*dfn] = start;
949 /*g_print ("visit %d at %p (BB%ld)\n", *dfn, start->cil_code, start->block_num);*/
950 for (i = 0; i < start->out_count; ++i) {
951 if (start->out_bb [i]->dfn)
954 start->out_bb [i]->dfn = *dfn;
955 start->out_bb [i]->df_parent = start;
956 array [*dfn] = start->out_bb [i];
957 df_visit (start->out_bb [i], dfn, array);
963 MonoBasicBlock *best;
967 previous_foreach (gconstpointer key, gpointer val, gpointer data)
969 PrevStruct *p = data;
970 MonoBasicBlock *bb = val;
971 //printf ("FIDPREV %d %p %p %p %p %p %d %d %d\n", bb->block_num, p->code, bb, p->best, bb->cil_code, p->best->cil_code,
972 //bb->method == p->best->method, bb->cil_code < p->code, bb->cil_code > p->best->cil_code);
974 if (bb->cil_code && bb->cil_code < p->code && bb->cil_code > p->best->cil_code)
978 static MonoBasicBlock*
979 find_previous (GHashTable *bb_hash, MonoBasicBlock *start, const guchar *code) {
985 g_hash_table_foreach (bb_hash, (GHFunc)previous_foreach, &p);
990 split_bblock (MonoCompile *cfg, MonoBasicBlock *first, MonoBasicBlock *second) {
999 * FIXME: take into account all the details:
1000 * second may have been the target of more than one bblock
1002 second->out_count = first->out_count;
1003 second->out_bb = first->out_bb;
1005 for (i = 0; i < first->out_count; ++i) {
1006 bb = first->out_bb [i];
1007 for (j = 0; j < bb->in_count; ++j) {
1008 if (bb->in_bb [j] == first)
1009 bb->in_bb [j] = second;
1013 first->out_count = 0;
1014 first->out_bb = NULL;
1015 link_bblock (cfg, first, second);
1017 second->last_ins = first->last_ins;
1019 /*g_print ("start search at %p for %p\n", first->cil_code, second->cil_code);*/
1020 for (inst = first->code; inst && inst->next; inst = inst->next) {
1021 /*char *code = mono_disasm_code_one (NULL, cfg->method, inst->next->cil_code, NULL);
1022 g_print ("found %p: %s", inst->next->cil_code, code);
1024 if (inst->cil_code < second->cil_code && inst->next->cil_code >= second->cil_code) {
1025 second->code = inst->next;
1027 first->last_ins = inst;
1028 second->next_bb = first->next_bb;
1029 first->next_bb = second;
1033 if (!second->code) {
1034 g_warning ("bblock split failed in %s::%s\n", cfg->method->klass->name, cfg->method->name);
1040 reverse_branch_op (guint32 opcode)
1042 static const int reverse_map [] = {
1043 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
1044 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
1046 static const int reverse_fmap [] = {
1047 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
1048 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
1050 static const int reverse_lmap [] = {
1051 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
1052 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
1054 static const int reverse_imap [] = {
1055 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
1056 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
1059 if (opcode >= CEE_BEQ && opcode <= CEE_BLT_UN) {
1060 opcode = reverse_map [opcode - CEE_BEQ];
1061 } else if (opcode >= OP_FBEQ && opcode <= OP_FBLT_UN) {
1062 opcode = reverse_fmap [opcode - OP_FBEQ];
1063 } else if (opcode >= OP_LBEQ && opcode <= OP_LBLT_UN) {
1064 opcode = reverse_lmap [opcode - OP_LBEQ];
1065 } else if (opcode >= OP_IBEQ && opcode <= OP_IBLT_UN) {
1066 opcode = reverse_imap [opcode - OP_IBEQ];
1068 g_assert_not_reached ();
1074 mono_type_to_ldind (MonoType *type)
1080 switch (type->type) {
1082 return CEE_LDIND_I1;
1084 case MONO_TYPE_BOOLEAN:
1085 return CEE_LDIND_U1;
1087 return CEE_LDIND_I2;
1089 case MONO_TYPE_CHAR:
1090 return CEE_LDIND_U2;
1092 return CEE_LDIND_I4;
1094 return CEE_LDIND_U4;
1098 case MONO_TYPE_FNPTR:
1100 case MONO_TYPE_CLASS:
1101 case MONO_TYPE_STRING:
1102 case MONO_TYPE_OBJECT:
1103 case MONO_TYPE_SZARRAY:
1104 case MONO_TYPE_ARRAY:
1105 return CEE_LDIND_REF;
1108 return CEE_LDIND_I8;
1110 return CEE_LDIND_R4;
1112 return CEE_LDIND_R8;
1113 case MONO_TYPE_VALUETYPE:
1114 if (type->data.klass->enumtype) {
1115 type = type->data.klass->enum_basetype;
1119 case MONO_TYPE_TYPEDBYREF:
1121 case MONO_TYPE_GENERICINST:
1122 type = &type->data.generic_class->container_class->byval_arg;
1125 g_error ("unknown type 0x%02x in type_to_ldind", type->type);
1131 mono_type_to_stind (MonoType *type)
1137 switch (type->type) {
1140 case MONO_TYPE_BOOLEAN:
1141 return CEE_STIND_I1;
1144 case MONO_TYPE_CHAR:
1145 return CEE_STIND_I2;
1148 return CEE_STIND_I4;
1152 case MONO_TYPE_FNPTR:
1154 case MONO_TYPE_CLASS:
1155 case MONO_TYPE_STRING:
1156 case MONO_TYPE_OBJECT:
1157 case MONO_TYPE_SZARRAY:
1158 case MONO_TYPE_ARRAY:
1159 return CEE_STIND_REF;
1162 return CEE_STIND_I8;
1164 return CEE_STIND_R4;
1166 return CEE_STIND_R8;
1167 case MONO_TYPE_VALUETYPE:
1168 if (type->data.klass->enumtype) {
1169 type = type->data.klass->enum_basetype;
1173 case MONO_TYPE_TYPEDBYREF:
1175 case MONO_TYPE_GENERICINST:
1176 type = &type->data.generic_class->container_class->byval_arg;
1179 g_error ("unknown type 0x%02x in type_to_stind", type->type);
1185 * Returns the type used in the eval stack when @type is loaded.
1186 * FIXME: return a MonoType/MonoClass for the byref and VALUETYPE cases.
1189 type_to_eval_stack_type (MonoType *type, MonoInst *inst)
1194 inst->type = STACK_MP;
1198 klass = mono_class_from_mono_type (type);
1201 switch (type->type) {
1202 case MONO_TYPE_VOID:
1203 inst->type = STACK_INV;
1207 case MONO_TYPE_BOOLEAN:
1210 case MONO_TYPE_CHAR:
1213 inst->type = STACK_I4;
1218 case MONO_TYPE_FNPTR:
1219 inst->type = STACK_PTR;
1221 case MONO_TYPE_CLASS:
1222 case MONO_TYPE_STRING:
1223 case MONO_TYPE_OBJECT:
1224 case MONO_TYPE_SZARRAY:
1225 case MONO_TYPE_ARRAY:
1226 inst->type = STACK_OBJ;
1230 inst->type = STACK_I8;
1234 inst->type = STACK_R8;
1236 case MONO_TYPE_VALUETYPE:
1237 if (type->data.klass->enumtype) {
1238 type = type->data.klass->enum_basetype;
1241 inst->klass = klass;
1242 inst->type = STACK_VTYPE;
1245 case MONO_TYPE_TYPEDBYREF:
1246 inst->klass = mono_defaults.typed_reference_class;
1247 inst->type = STACK_VTYPE;
1249 case MONO_TYPE_GENERICINST:
1250 type = &type->data.generic_class->container_class->byval_arg;
1253 g_error ("unknown type 0x%02x in eval stack type", type->type);
1258 * The following tables are used to quickly validate the IL code in type_from_op ().
1261 bin_num_table [STACK_MAX] [STACK_MAX] = {
1262 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1263 {STACK_INV, STACK_I4, STACK_INV, STACK_PTR, STACK_INV, STACK_MP, STACK_INV, STACK_INV},
1264 {STACK_INV, STACK_INV, STACK_I8, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1265 {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_MP, STACK_INV, STACK_INV},
1266 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_R8, STACK_INV, STACK_INV, STACK_INV},
1267 {STACK_INV, STACK_MP, STACK_INV, STACK_MP, STACK_INV, STACK_PTR, STACK_INV, STACK_INV},
1268 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1269 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1274 STACK_INV, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_INV, STACK_INV, STACK_INV
1277 /* reduce the size of this table */
1279 bin_int_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_INV, 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_INV, STACK_INV, STACK_INV},
1284 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1285 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, 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}
1291 bin_comp_table [STACK_MAX] [STACK_MAX] = {
1292 /* Inv i L p F & O vt */
1294 {0, 1, 0, 1, 0, 0, 0, 0}, /* i, int32 */
1295 {0, 0, 1, 0, 0, 0, 0, 0}, /* L, int64 */
1296 {0, 1, 0, 1, 0, 2, 4, 0}, /* p, ptr */
1297 {0, 0, 0, 0, 1, 0, 0, 0}, /* F, R8 */
1298 {0, 0, 0, 2, 0, 1, 0, 0}, /* &, managed pointer */
1299 {0, 0, 0, 4, 0, 0, 3, 0}, /* O, reference */
1300 {0, 0, 0, 0, 0, 0, 0, 0}, /* vt value type */
1303 /* reduce the size of this table */
1305 shift_table [STACK_MAX] [STACK_MAX] = {
1306 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1307 {STACK_INV, STACK_I4, STACK_INV, STACK_I4, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1308 {STACK_INV, STACK_I8, STACK_INV, STACK_I8, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1309 {STACK_INV, STACK_PTR, STACK_INV, STACK_PTR, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1310 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1311 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1312 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV},
1313 {STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV, STACK_INV}
1317 * Tables to map from the non-specific opcode to the matching
1318 * type-specific opcode.
1320 /* handles from CEE_ADD to CEE_SHR_UN (CEE_REM_UN for floats) */
1321 static const guint16
1322 binops_op_map [STACK_MAX] = {
1323 0, 0, OP_LADD-CEE_ADD, OP_PADD-CEE_ADD, OP_FADD-CEE_ADD, OP_PADD-CEE_ADD
1326 /* handles from CEE_NEG to CEE_CONV_U8 */
1327 static const guint16
1328 unops_op_map [STACK_MAX] = {
1329 0, 0, OP_LNEG-CEE_NEG, OP_PNEG-CEE_NEG, OP_FNEG-CEE_NEG, OP_PNEG-CEE_NEG
1332 /* handles from CEE_CONV_U2 to CEE_SUB_OVF_UN */
1333 static const guint16
1334 ovfops_op_map [STACK_MAX] = {
1335 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
1338 /* handles from CEE_CONV_OVF_I1_UN to CEE_CONV_OVF_U_UN */
1339 static const guint16
1340 ovf2ops_op_map [STACK_MAX] = {
1341 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
1344 /* handles from CEE_CONV_OVF_I1 to CEE_CONV_OVF_U8 */
1345 static const guint16
1346 ovf3ops_op_map [STACK_MAX] = {
1347 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
1350 /* handles from CEE_CEQ to CEE_CLT_UN */
1351 static const guint16
1352 ceqops_op_map [STACK_MAX] = {
1353 0, 0, OP_LCEQ-CEE_CEQ, OP_PCEQ-CEE_CEQ, OP_FCEQ-CEE_CEQ, OP_LCEQ-CEE_CEQ
1357 * Sets ins->type (the type on the eval stack) according to the
1358 * type of the opcode and the arguments to it.
1359 * Invalid IL code is marked by setting ins->type to the invalid value STACK_INV.
1361 * FIXME: this function sets ins->type unconditionally in some cases, but
1362 * it should set it to invalid for some types (a conv.x on an object)
1365 type_from_op (MonoInst *ins) {
1366 switch (ins->opcode) {
1373 /* FIXME: check unverifiable args for STACK_MP */
1374 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1375 ins->opcode += binops_op_map [ins->type];
1382 ins->type = bin_int_table [ins->inst_i0->type] [ins->inst_i1->type];
1383 ins->opcode += binops_op_map [ins->type];
1388 ins->type = shift_table [ins->inst_i0->type] [ins->inst_i1->type];
1389 ins->opcode += binops_op_map [ins->type];
1393 /* FIXME: handle some specifics with ins->next->type */
1394 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1395 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))))
1396 ins->opcode = OP_LCOMPARE;
1403 ins->type = bin_comp_table [ins->inst_i0->type] [ins->inst_i1->type] ? STACK_I4: STACK_INV;
1404 ins->opcode += ceqops_op_map [ins->inst_i0->type];
1408 ins->type = neg_table [ins->inst_i0->type];
1409 ins->opcode += unops_op_map [ins->type];
1412 if (ins->inst_i0->type >= STACK_I4 && ins->inst_i0->type <= STACK_PTR)
1413 ins->type = ins->inst_i0->type;
1415 ins->type = STACK_INV;
1416 ins->opcode += unops_op_map [ins->type];
1422 ins->type = STACK_I4;
1423 ins->opcode += unops_op_map [ins->inst_i0->type];
1426 ins->type = STACK_R8;
1427 switch (ins->inst_i0->type) {
1432 ins->opcode = OP_LCONV_TO_R_UN;
1436 case CEE_CONV_OVF_I1:
1437 case CEE_CONV_OVF_U1:
1438 case CEE_CONV_OVF_I2:
1439 case CEE_CONV_OVF_U2:
1440 case CEE_CONV_OVF_I4:
1441 case CEE_CONV_OVF_U4:
1442 ins->type = STACK_I4;
1443 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1445 case CEE_CONV_OVF_I_UN:
1446 case CEE_CONV_OVF_U_UN:
1447 ins->type = STACK_PTR;
1448 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1450 case CEE_CONV_OVF_I1_UN:
1451 case CEE_CONV_OVF_I2_UN:
1452 case CEE_CONV_OVF_I4_UN:
1453 case CEE_CONV_OVF_U1_UN:
1454 case CEE_CONV_OVF_U2_UN:
1455 case CEE_CONV_OVF_U4_UN:
1456 ins->type = STACK_I4;
1457 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1460 ins->type = STACK_PTR;
1461 switch (ins->inst_i0->type) {
1467 ins->opcode = OP_LCONV_TO_U;
1470 ins->opcode = OP_FCONV_TO_U;
1476 ins->type = STACK_I8;
1477 ins->opcode += unops_op_map [ins->inst_i0->type];
1479 case CEE_CONV_OVF_I8:
1480 case CEE_CONV_OVF_U8:
1481 ins->type = STACK_I8;
1482 ins->opcode += ovf3ops_op_map [ins->inst_i0->type];
1484 case CEE_CONV_OVF_U8_UN:
1485 case CEE_CONV_OVF_I8_UN:
1486 ins->type = STACK_I8;
1487 ins->opcode += ovf2ops_op_map [ins->inst_i0->type];
1491 ins->type = STACK_R8;
1492 ins->opcode += unops_op_map [ins->inst_i0->type];
1495 ins->type = STACK_R8;
1499 ins->type = STACK_I4;
1500 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1503 case CEE_CONV_OVF_I:
1504 case CEE_CONV_OVF_U:
1505 ins->type = STACK_PTR;
1506 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1509 case CEE_ADD_OVF_UN:
1511 case CEE_MUL_OVF_UN:
1513 case CEE_SUB_OVF_UN:
1514 ins->type = bin_num_table [ins->inst_i0->type] [ins->inst_i1->type];
1515 ins->opcode += ovfops_op_map [ins->inst_i0->type];
1518 g_error ("opcode 0x%04x not handled in type from op", ins->opcode);
1525 STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I4, STACK_I8, STACK_PTR, STACK_R8, STACK_R8, STACK_OBJ
1528 /* map ldelem.x to the matching ldind.x opcode */
1530 ldelem_to_ldind [] = {
1544 /* map stelem.x to the matching stind.x opcode */
1546 stelem_to_stind [] = {
1560 param_table [STACK_MAX] [STACK_MAX] = {
1565 check_values_to_signature (MonoInst *args, MonoType *this, MonoMethodSignature *sig) {
1569 switch (args->type) {
1579 for (i = 0; i < sig->param_count; ++i) {
1580 switch (args [i].type) {
1584 if (!sig->params [i]->byref)
1588 if (sig->params [i]->byref)
1590 switch (sig->params [i]->type) {
1591 case MONO_TYPE_CLASS:
1592 case MONO_TYPE_STRING:
1593 case MONO_TYPE_OBJECT:
1594 case MONO_TYPE_SZARRAY:
1595 case MONO_TYPE_ARRAY:
1602 if (sig->params [i]->byref)
1604 if (sig->params [i]->type != MONO_TYPE_R4 && sig->params [i]->type != MONO_TYPE_R8)
1613 /*if (!param_table [args [i].type] [sig->params [i]->type])
1621 * When we need a pointer to the current domain many times in a method, we
1622 * call mono_domain_get() once and we store the result in a local variable.
1623 * This function returns the variable that represents the MonoDomain*.
1625 inline static MonoInst *
1626 mono_get_domainvar (MonoCompile *cfg)
1628 if (!cfg->domainvar)
1629 cfg->domainvar = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1630 return cfg->domainvar;
1634 * The got_var contains the address of the Global Offset Table when AOT
1637 inline static MonoInst *
1638 mono_get_got_var (MonoCompile *cfg)
1640 #ifdef MONO_ARCH_NEED_GOT_VAR
1641 if (!cfg->compile_aot)
1643 if (!cfg->got_var) {
1644 cfg->got_var = mono_compile_create_var (cfg, &mono_defaults.int_class->byval_arg, OP_LOCAL);
1646 return cfg->got_var;
1653 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
1656 int num = cfg->num_varinfo;
1658 if ((num + 1) >= cfg->varinfo_count) {
1659 cfg->varinfo_count = (cfg->varinfo_count + 2) * 2;
1660 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
1661 cfg->vars = (MonoMethodVar **)g_realloc (cfg->vars, sizeof (MonoMethodVar*) * cfg->varinfo_count);
1664 /*g_print ("created temp %d of type 0x%x\n", num, type->type);*/
1665 mono_jit_stats.allocate_var++;
1667 MONO_INST_NEW (cfg, inst, opcode);
1668 inst->inst_c0 = num;
1669 inst->inst_vtype = type;
1670 inst->klass = mono_class_from_mono_type (type);
1671 /* if set to 1 the variable is native */
1674 cfg->varinfo [num] = inst;
1676 cfg->vars [num] = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoMethodVar));
1677 MONO_INIT_VARINFO (cfg->vars [num], num);
1680 //g_print ("created temp %d of type %s\n", num, mono_type_get_name (type));
1685 * Transform a MonoInst into a load from the variable of index var_index.
1688 mono_compile_make_var_load (MonoCompile *cfg, MonoInst *dest, gssize var_index) {
1689 memset (dest, 0, sizeof (MonoInst));
1690 dest->ssa_op = MONO_SSA_LOAD;
1691 dest->inst_i0 = cfg->varinfo [var_index];
1692 dest->opcode = mono_type_to_ldind (dest->inst_i0->inst_vtype);
1693 type_to_eval_stack_type (dest->inst_i0->inst_vtype, dest);
1694 dest->klass = dest->inst_i0->klass;
1698 * Create a MonoInst that is a load from the variable of index var_index.
1701 mono_compile_create_var_load (MonoCompile *cfg, gssize var_index) {
1703 NEW_TEMPLOAD (cfg,dest,var_index);
1708 * Create a MonoInst that is a store of the given value into the variable of index var_index.
1711 mono_compile_create_var_store (MonoCompile *cfg, gssize var_index, MonoInst *value) {
1713 NEW_TEMPSTORE (cfg, dest, var_index, value);
1718 type_from_stack_type (MonoInst *ins) {
1719 switch (ins->type) {
1720 case STACK_I4: return &mono_defaults.int32_class->byval_arg;
1721 case STACK_I8: return &mono_defaults.int64_class->byval_arg;
1722 case STACK_PTR: return &mono_defaults.int_class->byval_arg;
1723 case STACK_R8: return &mono_defaults.double_class->byval_arg;
1724 case STACK_MP: return &mono_defaults.int_class->byval_arg;
1725 case STACK_OBJ: return &mono_defaults.object_class->byval_arg;
1726 case STACK_VTYPE: return &ins->klass->byval_arg;
1728 g_error ("stack type %d to montype not handled\n", ins->type);
1734 mono_type_from_stack_type (MonoInst *ins) {
1735 return type_from_stack_type (ins);
1739 array_access_to_klass (int opcode)
1743 return mono_defaults.byte_class;
1745 return mono_defaults.uint16_class;
1748 return mono_defaults.int_class;
1751 return mono_defaults.sbyte_class;
1754 return mono_defaults.int16_class;
1757 return mono_defaults.int32_class;
1759 return mono_defaults.uint32_class;
1762 return mono_defaults.int64_class;
1765 return mono_defaults.single_class;
1768 return mono_defaults.double_class;
1769 case CEE_LDELEM_REF:
1770 case CEE_STELEM_REF:
1771 return mono_defaults.object_class;
1773 g_assert_not_reached ();
1779 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
1783 MONO_ADD_INS (bb, inst);
1786 switch (bb->last_ins->opcode) {
1800 while (prev->next && prev->next != bb->last_ins)
1802 if (prev == bb->code) {
1803 if (bb->last_ins == bb->code) {
1804 inst->next = bb->code;
1807 inst->next = prev->next;
1811 inst->next = bb->last_ins;
1815 // g_warning ("handle conditional jump in add_ins_to_end ()\n");
1817 MONO_ADD_INS (bb, inst);
1823 mono_add_varcopy_to_end (MonoCompile *cfg, MonoBasicBlock *bb, int src, int dest)
1825 MonoInst *inst, *load;
1827 NEW_TEMPLOAD (cfg, load, src);
1829 NEW_TEMPSTORE (cfg, inst, dest, load);
1830 if (inst->opcode == CEE_STOBJ) {
1831 NEW_TEMPLOADA (cfg, inst, dest);
1832 handle_stobj (cfg, bb, inst, load, NULL, inst->klass, TRUE, FALSE);
1834 inst->cil_code = NULL;
1835 mono_add_ins_to_end (bb, inst);
1840 * We try to share variables when possible
1843 mono_compile_get_interface_var (MonoCompile *cfg, int slot, MonoInst *ins)
1848 /* inlining can result in deeper stacks */
1849 if (slot >= mono_method_get_header (cfg->method)->max_stack)
1850 return mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1852 pos = ins->type - 1 + slot * STACK_MAX;
1854 switch (ins->type) {
1861 if ((vnum = cfg->intvars [pos]))
1862 return cfg->varinfo [vnum];
1863 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1864 cfg->intvars [pos] = res->inst_c0;
1867 res = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
1873 * This function is called to handle items that are left on the evaluation stack
1874 * at basic block boundaries. What happens is that we save the values to local variables
1875 * and we reload them later when first entering the target basic block (with the
1876 * handle_loaded_temps () function).
1877 * It is also used to handle items on the stack in store opcodes, since it is
1878 * possible that the variable to be stored into is already on the stack, in
1879 * which case its old value should be used.
1880 * A single joint point will use the same variables (stored in the array bb->out_stack or
1881 * bb->in_stack, if the basic block is before or after the joint point).
1884 handle_stack_args (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst **sp, int count) {
1886 MonoBasicBlock *outb;
1887 MonoInst *inst, **locals;
1892 if (cfg->verbose_level > 3)
1893 g_print ("%d item(s) on exit from B%d\n", count, bb->block_num);
1894 if (!bb->out_scount) {
1895 bb->out_scount = count;
1896 //g_print ("bblock %d has out:", bb->block_num);
1898 for (i = 0; i < bb->out_count; ++i) {
1899 outb = bb->out_bb [i];
1900 /* exception handlers are linked, but they should not be considered for stack args */
1901 if (outb->flags & BB_EXCEPTION_HANDLER)
1903 //g_print (" %d", outb->block_num);
1904 if (outb->in_stack) {
1906 bb->out_stack = outb->in_stack;
1912 bb->out_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*) * count);
1913 for (i = 0; i < count; ++i) {
1915 * try to reuse temps already allocated for this purpouse, if they occupy the same
1916 * stack slot and if they are of the same type.
1917 * This won't cause conflicts since if 'local' is used to
1918 * store one of the values in the in_stack of a bblock, then
1919 * the same variable will be used for the same outgoing stack
1921 * This doesn't work when inlining methods, since the bblocks
1922 * in the inlined methods do not inherit their in_stack from
1923 * the bblock they are inlined to. See bug #58863 for an
1926 if (cfg->inlined_method)
1927 bb->out_stack [i] = mono_compile_create_var (cfg, type_from_stack_type (sp [i]), OP_LOCAL);
1929 bb->out_stack [i] = mono_compile_get_interface_var (cfg, i, sp [i]);
1934 for (i = 0; i < bb->out_count; ++i) {
1935 outb = bb->out_bb [i];
1936 /* exception handlers are linked, but they should not be considered for stack args */
1937 if (outb->flags & BB_EXCEPTION_HANDLER)
1939 if (outb->in_scount) {
1940 if (outb->in_scount != bb->out_scount)
1942 continue; /* check they are the same locals */
1944 outb->in_scount = count;
1945 outb->in_stack = bb->out_stack;
1948 locals = bb->out_stack;
1949 for (i = 0; i < count; ++i) {
1950 /* add store ops at the end of the bb, before the branch */
1951 NEW_TEMPSTORE (cfg, inst, locals [i]->inst_c0, sp [i]);
1952 if (inst->opcode == CEE_STOBJ) {
1953 NEW_TEMPLOADA (cfg, inst, locals [i]->inst_c0);
1954 handle_stobj (cfg, bb, inst, sp [i], sp [i]->cil_code, inst->klass, TRUE, FALSE);
1956 inst->cil_code = sp [i]->cil_code;
1957 mono_add_ins_to_end (bb, inst);
1959 if (cfg->verbose_level > 3)
1960 g_print ("storing %d to temp %d\n", i, (int)locals [i]->inst_c0);
1964 * It is possible that the out bblocks already have in_stack assigned, and
1965 * the in_stacks differ. In this case, we will store to all the different
1972 /* Find a bblock which has a different in_stack */
1974 while (bindex < bb->out_count) {
1975 outb = bb->out_bb [bindex];
1976 /* exception handlers are linked, but they should not be considered for stack args */
1977 if (outb->flags & BB_EXCEPTION_HANDLER) {
1981 if (outb->in_stack != locals) {
1983 * Instead of storing sp [i] to locals [i], we need to store
1984 * locals [i] to <new locals>[i], since the sp [i] tree can't
1985 * be shared between trees.
1987 for (i = 0; i < count; ++i)
1988 mono_add_varcopy_to_end (cfg, bb, locals [i]->inst_c0, outb->in_stack [i]->inst_c0);
1989 locals = outb->in_stack;
2001 ret_type_to_call_opcode (MonoType *type, int calli, int virt)
2004 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
2007 switch (type->type) {
2008 case MONO_TYPE_VOID:
2009 return calli? OP_VOIDCALL_REG: virt? OP_VOIDCALLVIRT: OP_VOIDCALL;
2012 case MONO_TYPE_BOOLEAN:
2015 case MONO_TYPE_CHAR:
2018 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
2022 case MONO_TYPE_FNPTR:
2023 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
2024 case MONO_TYPE_CLASS:
2025 case MONO_TYPE_STRING:
2026 case MONO_TYPE_OBJECT:
2027 case MONO_TYPE_SZARRAY:
2028 case MONO_TYPE_ARRAY:
2029 return calli? OP_CALL_REG: virt? CEE_CALLVIRT: CEE_CALL;
2032 return calli? OP_LCALL_REG: virt? OP_LCALLVIRT: OP_LCALL;
2035 return calli? OP_FCALL_REG: virt? OP_FCALLVIRT: OP_FCALL;
2036 case MONO_TYPE_VALUETYPE:
2037 if (type->data.klass->enumtype) {
2038 type = type->data.klass->enum_basetype;
2041 return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
2042 case MONO_TYPE_TYPEDBYREF:
2043 return calli? OP_VCALL_REG: virt? OP_VCALLVIRT: OP_VCALL;
2044 case MONO_TYPE_GENERICINST:
2045 type = &type->data.generic_class->container_class->byval_arg;
2048 g_error ("unknown type 0x%02x in ret_type_to_call_opcode", type->type);
2054 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
2056 MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
2057 MonoJumpInfoBBTable *table;
2059 table = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
2061 table->table_size = num_blocks;
2063 ji->ip.label = label;
2064 ji->type = MONO_PATCH_INFO_SWITCH;
2065 ji->data.table = table;
2066 ji->next = cfg->patch_info;
2067 cfg->patch_info = ji;
2071 * When we add a tree of instructions, we need to ensure the instructions currently
2072 * on the stack are executed before (like, if we load a value from a local).
2073 * We ensure this by saving the currently loaded values to temps and rewriting the
2074 * instructions to load the values.
2075 * This is not done for opcodes that terminate a basic block (because it's handled already
2076 * by handle_stack_args ()) and for opcodes that can't change values, like POP.
2079 handle_loaded_temps (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst **stack, MonoInst **sp)
2081 MonoInst *load, *store, *temp, *ins;
2083 while (stack < sp) {
2085 /* handle also other constants */
2086 if ((ins->opcode != OP_ICONST) &&
2087 /* temps never get written to again, so we can safely avoid duplicating them */
2088 !(ins->ssa_op == MONO_SSA_LOAD && ins->inst_i0->opcode == OP_LOCAL && ins->inst_i0->flags & MONO_INST_IS_TEMP)) {
2089 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
2090 temp->flags |= MONO_INST_IS_TEMP;
2091 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2092 store->cil_code = ins->cil_code;
2093 if (store->opcode == CEE_STOBJ) {
2094 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
2095 handle_stobj (cfg, bblock, store, ins, ins->cil_code, temp->klass, FALSE, FALSE);
2097 MONO_ADD_INS (bblock, store);
2098 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2099 load->cil_code = ins->cil_code;
2107 * target_type_is_incompatible:
2108 * @cfg: MonoCompile context
2110 * Check that the item @arg on the evaluation stack can be stored
2111 * in the target type (can be a local, or field, etc).
2112 * The cfg arg can be used to check if we need verification or just
2115 * Returns: non-0 value if arg can't be stored on a target.
2118 target_type_is_incompatible (MonoCompile *cfg, MonoType *target, MonoInst *arg)
2120 MonoType *simple_type;
2123 if (target->byref) {
2124 /* FIXME: check that the pointed to types match */
2125 if (arg->type == STACK_MP)
2126 return arg->klass != mono_class_from_mono_type (target);
2127 if (arg->type == STACK_PTR)
2131 simple_type = mono_type_get_underlying_type (target);
2132 switch (simple_type->type) {
2133 case MONO_TYPE_VOID:
2137 case MONO_TYPE_BOOLEAN:
2140 case MONO_TYPE_CHAR:
2143 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2147 /* STACK_MP is needed when setting pinned locals */
2148 if (arg->type != STACK_I4 && arg->type != STACK_PTR && arg->type != STACK_MP)
2153 case MONO_TYPE_FNPTR:
2154 if (arg->type != STACK_I4 && arg->type != STACK_PTR)
2157 case MONO_TYPE_CLASS:
2158 case MONO_TYPE_STRING:
2159 case MONO_TYPE_OBJECT:
2160 case MONO_TYPE_SZARRAY:
2161 case MONO_TYPE_ARRAY:
2162 if (arg->type != STACK_OBJ)
2164 /* FIXME: check type compatibility */
2168 if (arg->type != STACK_I8)
2173 if (arg->type != STACK_R8)
2176 case MONO_TYPE_VALUETYPE:
2177 if (arg->type != STACK_VTYPE)
2179 klass = mono_class_from_mono_type (simple_type);
2180 if (klass != arg->klass)
2183 case MONO_TYPE_TYPEDBYREF:
2184 if (arg->type != STACK_VTYPE)
2186 klass = mono_class_from_mono_type (simple_type);
2187 if (klass != arg->klass)
2190 case MONO_TYPE_GENERICINST:
2191 if (mono_type_generic_inst_is_valuetype (simple_type)) {
2192 if (arg->type != STACK_VTYPE)
2194 klass = mono_class_from_mono_type (simple_type);
2195 if (klass != arg->klass)
2199 if (arg->type != STACK_OBJ)
2201 /* FIXME: check type compatibility */
2205 g_error ("unknown type 0x%02x in target_type_is_incompatible", simple_type->type);
2211 * Prepare arguments for passing to a function call.
2212 * Return a non-zero value if the arguments can't be passed to the given
2214 * The type checks are not yet complete and some conversions may need
2215 * casts on 32 or 64 bit architectures.
2217 * FIXME: implement this using target_type_is_incompatible ()
2220 check_call_signature (MonoCompile *cfg, MonoMethodSignature *sig, MonoInst **args)
2222 MonoType *simple_type;
2226 if (args [0]->type != STACK_OBJ && args [0]->type != STACK_MP && args [0]->type != STACK_PTR)
2230 for (i = 0; i < sig->param_count; ++i) {
2231 if (sig->params [i]->byref) {
2232 if (args [i]->type != STACK_MP && args [i]->type != STACK_PTR)
2236 simple_type = sig->params [i];
2238 switch (simple_type->type) {
2239 case MONO_TYPE_VOID:
2244 case MONO_TYPE_BOOLEAN:
2247 case MONO_TYPE_CHAR:
2250 if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR)
2256 case MONO_TYPE_FNPTR:
2257 if (args [i]->type != STACK_I4 && args [i]->type != STACK_PTR && args [i]->type != STACK_MP && args [i]->type != STACK_OBJ)
2260 case MONO_TYPE_CLASS:
2261 case MONO_TYPE_STRING:
2262 case MONO_TYPE_OBJECT:
2263 case MONO_TYPE_SZARRAY:
2264 case MONO_TYPE_ARRAY:
2265 if (args [i]->type != STACK_OBJ)
2270 if (args [i]->type != STACK_I8)
2275 if (args [i]->type != STACK_R8)
2278 case MONO_TYPE_VALUETYPE:
2279 if (simple_type->data.klass->enumtype) {
2280 simple_type = simple_type->data.klass->enum_basetype;
2283 if (args [i]->type != STACK_VTYPE)
2286 case MONO_TYPE_TYPEDBYREF:
2287 if (args [i]->type != STACK_VTYPE)
2290 case MONO_TYPE_GENERICINST:
2291 simple_type = &simple_type->data.generic_class->container_class->byval_arg;
2295 g_error ("unknown type 0x%02x in check_call_signature",
2303 mono_spill_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoCallInst *call, MonoMethodSignature *sig, gboolean ret_object,
2304 const guint8 *ip, gboolean to_end)
2306 MonoInst *temp, *store, *ins = (MonoInst*)call;
2307 MonoType *ret = sig->ret;
2309 if (!MONO_TYPE_IS_VOID (ret) || ret_object) {
2311 call->inst.type = STACK_OBJ;
2312 call->inst.opcode = CEE_CALL;
2313 temp = mono_compile_create_var (cfg, &mono_defaults.string_class->byval_arg, OP_LOCAL);
2315 type_to_eval_stack_type (ret, ins);
2316 temp = mono_compile_create_var (cfg, ret, OP_LOCAL);
2319 temp->flags |= MONO_INST_IS_TEMP;
2321 if (MONO_TYPE_ISSTRUCT (ret)) {
2322 MonoInst *loada, *dummy_store;
2325 * Emit a dummy store to the local holding the result so the
2326 * liveness info remains correct.
2328 NEW_DUMMY_STORE (cfg, dummy_store, temp->inst_c0);
2330 mono_add_ins_to_end (bblock, dummy_store);
2332 MONO_ADD_INS (bblock, dummy_store);
2334 /* we use this to allocate native sized structs */
2335 temp->unused = sig->pinvoke;
2337 NEW_TEMPLOADA (cfg, loada, temp->inst_c0);
2338 if (call->inst.opcode == OP_VCALL)
2339 ins->inst_left = loada;
2341 ins->inst_right = loada; /* a virtual or indirect call */
2344 mono_add_ins_to_end (bblock, ins);
2346 MONO_ADD_INS (bblock, ins);
2348 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2349 store->cil_code = ip;
2351 mono_add_ins_to_end (bblock, store);
2353 MONO_ADD_INS (bblock, store);
2355 return temp->inst_c0;
2358 mono_add_ins_to_end (bblock, ins);
2360 MONO_ADD_INS (bblock, ins);
2365 inline static MonoCallInst *
2366 mono_emit_call_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2367 MonoInst **args, int calli, int virtual, const guint8 *ip, gboolean to_end)
2372 MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (sig->ret, calli, virtual));
2374 call->inst.cil_code = ip;
2376 call->signature = sig;
2377 call = mono_arch_call_opcode (cfg, bblock, call, virtual);
2378 type_to_eval_stack_type (sig->ret, &call->inst);
2380 for (arg = call->out_args; arg;) {
2381 MonoInst *narg = arg->next;
2386 mono_add_ins_to_end (bblock, arg);
2388 MONO_ADD_INS (bblock, arg);
2395 mono_emit_calli (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig,
2396 MonoInst **args, MonoInst *addr, const guint8 *ip)
2398 MonoCallInst *call = mono_emit_call_args (cfg, bblock, sig, args, TRUE, FALSE, ip, FALSE);
2400 call->inst.inst_i0 = addr;
2402 return mono_spill_call (cfg, bblock, call, sig, FALSE, ip, FALSE);
2405 static MonoCallInst*
2406 mono_emit_method_call_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2407 MonoInst **args, const guint8 *ip, MonoInst *this, gboolean to_end)
2409 gboolean virtual = this != NULL;
2412 call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, virtual, ip, to_end);
2414 if (this && sig->hasthis &&
2415 (method->klass->marshalbyref || method->klass == mono_defaults.object_class) &&
2416 !(method->flags & METHOD_ATTRIBUTE_VIRTUAL) && !MONO_CHECK_THIS (this)) {
2417 call->method = mono_marshal_get_remoting_invoke_with_check (method);
2419 call->method = method;
2421 call->inst.flags |= MONO_INST_HAS_METHOD;
2422 call->inst.inst_left = this;
2425 mono_get_got_var (cfg);
2426 else if (call->method->klass->flags & TYPE_ATTRIBUTE_INTERFACE)
2427 /* Needed by the code generated in inssel.brg */
2428 mono_get_got_var (cfg);
2433 static MonoCallInst*
2434 mono_emit_method_call (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method, MonoMethodSignature *sig,
2435 MonoInst **args, const guint8 *ip, MonoInst *this)
2437 return mono_emit_method_call_full (cfg, bblock, method, sig, args, ip, this, FALSE);
2441 mono_emit_method_call_spilled (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,
2442 MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this)
2444 MonoCallInst *call = mono_emit_method_call (cfg, bblock, method, signature, args, ip, this);
2446 return mono_spill_call (cfg, bblock, call, signature, method->string_ctor, ip, FALSE);
2450 mono_emit_method_call_spilled_full (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *method,
2451 MonoMethodSignature *signature, MonoInst **args, const guint8 *ip, MonoInst *this,
2452 gboolean ret_object, gboolean to_end)
2454 MonoCallInst *call = mono_emit_method_call_full (cfg, bblock, method, signature, args, ip, this, to_end);
2456 return mono_spill_call (cfg, bblock, call, signature, ret_object, ip, to_end);
2460 mono_emit_native_call (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoMethodSignature *sig,
2461 MonoInst **args, const guint8 *ip, gboolean ret_object, gboolean to_end)
2467 call = mono_emit_call_args (cfg, bblock, sig, args, FALSE, FALSE, ip, to_end);
2470 mono_get_got_var (cfg);
2472 return mono_spill_call (cfg, bblock, call, sig, ret_object, ip, to_end);
2476 mono_emit_jit_icall (MonoCompile *cfg, MonoBasicBlock *bblock, gconstpointer func, MonoInst **args, const guint8 *ip)
2478 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (func);
2481 g_warning ("unregistered JIT ICall");
2482 g_assert_not_reached ();
2485 mono_get_got_var (cfg);
2486 return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, args, ip, FALSE, FALSE);
2490 mono_emulate_opcode (MonoCompile *cfg, MonoInst *tree, MonoInst **iargs, MonoJitICallInfo *info)
2492 MonoInst *ins, *temp = NULL, *store, *load, *begin;
2493 MonoInst *last_arg = NULL;
2497 //g_print ("emulating: ");
2498 //mono_print_tree_nl (tree);
2499 MONO_INST_NEW_CALL (cfg, call, ret_type_to_call_opcode (info->sig->ret, FALSE, FALSE));
2500 ins = (MonoInst*)call;
2502 call->inst.cil_code = tree->cil_code;
2504 call->signature = info->sig;
2506 call = mono_arch_call_opcode (cfg, cfg->cbb, call, FALSE);
2508 mono_get_got_var (cfg);
2510 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2511 temp = mono_compile_create_var (cfg, info->sig->ret, OP_LOCAL);
2512 temp->flags |= MONO_INST_IS_TEMP;
2513 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
2514 store->cil_code = tree->cil_code;
2519 nargs = info->sig->param_count + info->sig->hasthis;
2521 for (last_arg = call->out_args; last_arg && last_arg->next; last_arg = last_arg->next) ;
2524 last_arg->next = store;
2527 begin = call->out_args;
2531 if (cfg->prev_ins) {
2533 * This assumes that that in a tree, emulate_opcode is called for a
2534 * node before it is called for its children. dec_foreach needs to
2535 * take this into account.
2537 store->next = cfg->prev_ins->next;
2538 cfg->prev_ins->next = begin;
2540 store->next = cfg->cbb->code;
2541 cfg->cbb->code = begin;
2544 call->fptr = mono_icall_get_wrapper (info);
2546 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
2547 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
2552 static MonoMethodSignature *
2553 mono_get_element_address_signature (int arity)
2555 static GHashTable *sighash = NULL;
2556 MonoMethodSignature *res;
2561 sighash = g_hash_table_new (NULL, NULL);
2563 else if ((res = g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
2564 LeaveCriticalSection (&jit_mutex);
2568 res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
2571 #ifdef MONO_ARCH_VARARG_ICALLS
2572 /* Only set this only some archs since not all backends can handle varargs+pinvoke */
2573 res->call_convention = MONO_CALL_VARARG;
2575 res->params [0] = &mono_defaults.array_class->byval_arg;
2577 for (i = 1; i <= arity; i++)
2578 res->params [i] = &mono_defaults.int_class->byval_arg;
2580 res->ret = &mono_defaults.int_class->byval_arg;
2582 g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
2588 static MonoMethodSignature *
2589 mono_get_array_new_va_signature (int arity)
2591 static GHashTable *sighash = NULL;
2592 MonoMethodSignature *res;
2597 sighash = g_hash_table_new (NULL, NULL);
2599 else if ((res = g_hash_table_lookup (sighash, GINT_TO_POINTER (arity)))) {
2604 res = mono_metadata_signature_alloc (mono_defaults.corlib, arity + 1);
2607 #ifdef MONO_ARCH_VARARG_ICALLS
2608 /* Only set this only some archs since not all backends can handle varargs+pinvoke */
2609 res->call_convention = MONO_CALL_VARARG;
2612 res->params [0] = &mono_defaults.int_class->byval_arg;
2613 for (i = 0; i < arity; i++)
2614 res->params [i + 1] = &mono_defaults.int_class->byval_arg;
2616 res->ret = &mono_defaults.int_class->byval_arg;
2618 g_hash_table_insert (sighash, GINT_TO_POINTER (arity), res);
2625 get_memcpy_method (void)
2627 static MonoMethod *memcpy_method = NULL;
2628 if (!memcpy_method) {
2629 memcpy_method = mono_class_get_method_from_name (mono_defaults.string_class, "memcpy", 3);
2631 g_error ("Old corlib found. Install a new one");
2633 return memcpy_method;
2637 handle_stobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, MonoInst *src, const unsigned char *ip, MonoClass *klass, gboolean to_end, gboolean native) {
2638 MonoInst *iargs [3];
2641 MonoMethod *memcpy_method;
2645 * This check breaks with spilled vars... need to handle it during verification anyway.
2646 * g_assert (klass && klass == src->klass && klass == dest->klass);
2650 n = mono_class_native_size (klass, &align);
2652 n = mono_class_value_size (klass, &align);
2654 if ((cfg->opt & MONO_OPT_INTRINS) && !to_end && n <= sizeof (gpointer) * 5) {
2656 if (dest->opcode == OP_LDADDR) {
2657 /* Keep liveness info correct */
2658 NEW_DUMMY_STORE (cfg, inst, dest->inst_i0->inst_c0);
2659 MONO_ADD_INS (bblock, inst);
2661 MONO_INST_NEW (cfg, inst, OP_MEMCPY);
2662 inst->inst_left = dest;
2663 inst->inst_right = src;
2664 inst->cil_code = ip;
2666 MONO_ADD_INS (bblock, inst);
2671 NEW_ICONST (cfg, iargs [2], n);
2673 memcpy_method = get_memcpy_method ();
2674 mono_emit_method_call_spilled_full (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL, FALSE, to_end);
2678 get_memset_method (void)
2680 static MonoMethod *memset_method = NULL;
2681 if (!memset_method) {
2682 memset_method = mono_class_get_method_from_name (mono_defaults.string_class, "memset", 3);
2684 g_error ("Old corlib found. Install a new one");
2686 return memset_method;
2690 handle_initobj (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *dest, const guchar *ip, MonoClass *klass, MonoInst **stack_start, MonoInst **sp)
2692 MonoInst *iargs [3];
2693 MonoInst *ins, *zero_int32;
2695 MonoMethod *memset_method;
2697 NEW_ICONST (cfg, zero_int32, 0);
2699 mono_class_init (klass);
2700 n = mono_class_value_size (klass, NULL);
2701 MONO_INST_NEW (cfg, ins, 0);
2703 ins->inst_left = dest;
2704 ins->inst_right = zero_int32;
2707 ins->opcode = CEE_STIND_I1;
2708 MONO_ADD_INS (bblock, ins);
2711 ins->opcode = CEE_STIND_I2;
2712 MONO_ADD_INS (bblock, ins);
2715 ins->opcode = CEE_STIND_I4;
2716 MONO_ADD_INS (bblock, ins);
2719 if (n <= sizeof (gpointer) * 5) {
2720 ins->opcode = OP_MEMSET;
2723 MONO_ADD_INS (bblock, ins);
2726 memset_method = get_memset_method ();
2727 handle_loaded_temps (cfg, bblock, stack_start, sp);
2729 NEW_ICONST (cfg, iargs [1], 0);
2730 NEW_ICONST (cfg, iargs [2], n);
2731 mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
2737 handle_alloc (MonoCompile *cfg, MonoBasicBlock *bblock, MonoClass *klass, gboolean for_box, const guchar *ip)
2739 MonoInst *iargs [2];
2742 if (cfg->opt & MONO_OPT_SHARED) {
2743 NEW_DOMAINCONST (cfg, iargs [0]);
2744 NEW_CLASSCONST (cfg, iargs [1], klass);
2746 alloc_ftn = mono_object_new;
2748 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
2751 alloc_ftn = mono_class_get_allocation_ftn (vtable, for_box, &pass_lw);
2753 guint32 lw = vtable->klass->instance_size;
2754 lw = ((lw + (sizeof (gpointer) - 1)) & ~(sizeof (gpointer) - 1)) / sizeof (gpointer);
2755 NEW_ICONST (cfg, iargs [0], lw);
2756 NEW_VTABLECONST (cfg, iargs [1], vtable);
2759 NEW_VTABLECONST (cfg, iargs [0], vtable);
2762 return mono_emit_jit_icall (cfg, bblock, alloc_ftn, iargs, ip);
2766 * Handles unbox of a Nullable<T>, returning a temp variable
2767 * where the result is stored
2770 handle_unbox_nullable (MonoCompile* cfg, MonoBasicBlock* bblock, MonoInst* val, const guchar *ip, MonoClass* klass)
2772 MonoMethod* method = mono_class_get_method_from_name (klass, "Unbox", 1);
2773 return mono_emit_method_call_spilled (cfg, bblock, method, mono_method_signature (method), &val, ip, NULL);
2780 handle_box (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *val, const guchar *ip, MonoClass *klass)
2782 MonoInst *dest, *vtoffset, *add, *vstore;
2785 if (mono_class_is_nullable (klass)) {
2786 MonoMethod* method = mono_class_get_method_from_name (klass, "Box", 1);
2787 temp = mono_emit_method_call_spilled (cfg, bblock, method, mono_method_signature (method), &val, ip, NULL);
2788 NEW_TEMPLOAD (cfg, dest, temp);
2793 temp = handle_alloc (cfg, bblock, klass, TRUE, ip);
2794 NEW_TEMPLOAD (cfg, dest, temp);
2795 NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
2796 MONO_INST_NEW (cfg, add, OP_PADD);
2797 add->inst_left = dest;
2798 add->inst_right = vtoffset;
2801 MONO_INST_NEW (cfg, vstore, CEE_STIND_I);
2802 vstore->opcode = mono_type_to_stind (&klass->byval_arg);
2803 vstore->cil_code = ip;
2804 vstore->inst_left = add;
2805 vstore->inst_right = val;
2807 if (vstore->opcode == CEE_STOBJ) {
2808 handle_stobj (cfg, bblock, add, val, ip, klass, FALSE, FALSE);
2810 MONO_ADD_INS (bblock, vstore);
2812 NEW_TEMPLOAD (cfg, dest, temp);
2817 handle_array_new (MonoCompile *cfg, MonoBasicBlock *bblock, int rank, MonoInst **sp, unsigned char *ip)
2819 MonoMethodSignature *esig;
2820 char icall_name [256];
2822 MonoJitICallInfo *info;
2824 /* Need to register the icall so it gets an icall wrapper */
2825 sprintf (icall_name, "ves_array_new_va_%d", rank);
2827 info = mono_find_jit_icall_by_name (icall_name);
2829 esig = mono_get_array_new_va_signature (rank);
2830 name = g_strdup (icall_name);
2831 info = mono_register_jit_icall (mono_array_new_va, name, esig, FALSE);
2834 g_hash_table_insert (jit_icall_name_hash, name, name);
2838 cfg->flags |= MONO_CFG_HAS_VARARGS;
2840 return mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, sp, ip, TRUE, FALSE);
2844 mono_emit_load_got_addr (MonoCompile *cfg)
2846 MonoInst *load, *store, *dummy_use;
2849 if (!cfg->got_var || cfg->got_var_allocated)
2852 MONO_INST_NEW (cfg, get_got, OP_LOAD_GOTADDR);
2853 NEW_TEMPSTORE (cfg, store, cfg->got_var->inst_c0, get_got);
2855 /* Add it to the start of the first bblock */
2856 if (cfg->bb_entry->code) {
2857 store->next = cfg->bb_entry->code;
2858 cfg->bb_entry->code = store;
2861 MONO_ADD_INS (cfg->bb_entry, store);
2863 cfg->got_var_allocated = TRUE;
2866 * Add a dummy use to keep the got_var alive, since real uses might
2867 * only be generated in the decompose or instruction selection phases.
2868 * Add it to end_bblock, so the variable's lifetime covers the whole
2871 NEW_TEMPLOAD (cfg, load, cfg->got_var->inst_c0);
2872 NEW_DUMMY_USE (cfg, dummy_use, load);
2873 MONO_ADD_INS (cfg->bb_exit, dummy_use);
2876 #define CODE_IS_STLOC(ip) (((ip) [0] >= CEE_STLOC_0 && (ip) [0] <= CEE_STLOC_3) || ((ip) [0] == CEE_STLOC_S))
2879 mini_class_is_system_array (MonoClass *klass)
2881 if (klass->parent == mono_defaults.array_class)
2883 else if (mono_defaults.generic_array_class && klass->parent && klass->parent->generic_class)
2884 return klass->parent->generic_class->container_class == mono_defaults.generic_array_class;
2890 mono_method_check_inlining (MonoCompile *cfg, MonoMethod *method)
2892 MonoMethodHeader *header = mono_method_get_header (method);
2893 MonoMethodSignature *signature = mono_method_signature (method);
2897 #ifdef MONO_ARCH_HAVE_LMF_OPS
2898 if (((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2899 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) &&
2900 !MONO_TYPE_ISSTRUCT (signature->ret) && !mini_class_is_system_array (method->klass))
2904 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2905 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
2906 (method->iflags & METHOD_IMPL_ATTRIBUTE_NOINLINING) ||
2907 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) ||
2908 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2909 (method->klass->marshalbyref) ||
2910 !header || header->num_clauses ||
2911 /* fixme: why cant we inline valuetype returns? */
2912 MONO_TYPE_ISSTRUCT (signature->ret))
2915 /* its not worth to inline methods with valuetype arguments?? */
2916 for (i = 0; i < signature->param_count; i++) {
2917 if (MONO_TYPE_ISSTRUCT (signature->params [i])) {
2923 * if we can initialize the class of the method right away, we do,
2924 * otherwise we don't allow inlining if the class needs initialization,
2925 * since it would mean inserting a call to mono_runtime_class_init()
2926 * inside the inlined code
2928 if (!(cfg->opt & MONO_OPT_SHARED)) {
2929 vtable = mono_class_vtable (cfg->domain, method->klass);
2930 if (method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) {
2931 if (cfg->run_cctors)
2932 mono_runtime_class_init (vtable);
2934 else if (!vtable->initialized && mono_class_needs_cctor_run (method->klass, NULL))
2938 * If we're compiling for shared code
2939 * the cctor will need to be run at aot method load time, for example,
2940 * or at the end of the compilation of the inlining method.
2942 if (mono_class_needs_cctor_run (method->klass, NULL) && !((method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2945 //if (!MONO_TYPE_IS_VOID (signature->ret)) return FALSE;
2948 * CAS - do not inline methods with declarative security
2949 * Note: this has to be before any possible return TRUE;
2951 if (mono_method_has_declsec (method))
2954 /* also consider num_locals? */
2955 if (getenv ("MONO_INLINELIMIT")) {
2956 if (header->code_size < atoi (getenv ("MONO_INLINELIMIT"))) {
2959 } else if (header->code_size < INLINE_LENGTH_LIMIT)
2966 mini_field_access_needs_cctor_run (MonoCompile *cfg, MonoMethod *method, MonoVTable *vtable)
2968 if (vtable->initialized && !cfg->compile_aot)
2971 if (vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)
2974 if (!mono_class_needs_cctor_run (vtable->klass, method))
2977 if (! (method->flags & METHOD_ATTRIBUTE_STATIC) && (vtable->klass == method->klass))
2978 /* The initialization is already done before the method is called */
2985 mini_get_ldelema_ins (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethod *cmethod, MonoInst **sp, unsigned char *ip, gboolean is_set)
2989 MonoMethodSignature *esig;
2990 char icall_name [256];
2992 MonoJitICallInfo *info;
2994 rank = mono_method_signature (cmethod)->param_count - (is_set? 1: 0);
2997 MONO_INST_NEW (cfg, addr, CEE_LDELEMA);
2998 addr->inst_left = sp [0];
2999 addr->inst_right = sp [1];
3000 addr->cil_code = ip;
3001 addr->type = STACK_MP;
3002 addr->klass = cmethod->klass->element_class;
3006 if (rank == 2 && (cfg->opt & MONO_OPT_INTRINS)) {
3007 #ifdef MONO_ARCH_EMULATE_MUL_DIV
3008 /* OP_LDELEMA2D depends on OP_LMUL */
3011 NEW_GROUP (cfg, indexes, sp [1], sp [2]);
3012 MONO_INST_NEW (cfg, addr, OP_LDELEMA2D);
3013 addr->inst_left = sp [0];
3014 addr->inst_right = indexes;
3015 addr->cil_code = ip;
3016 addr->type = STACK_MP;
3017 addr->klass = cmethod->klass;
3022 /* Need to register the icall so it gets an icall wrapper */
3023 sprintf (icall_name, "ves_array_element_address_%d", rank);
3025 info = mono_find_jit_icall_by_name (icall_name);
3027 esig = mono_get_element_address_signature (rank);
3028 name = g_strdup (icall_name);
3029 info = mono_register_jit_icall (ves_array_element_address, name, esig, FALSE);
3032 g_hash_table_insert (jit_icall_name_hash, name, name);
3036 temp = mono_emit_native_call (cfg, bblock, mono_icall_get_wrapper (info), info->sig, sp, ip, FALSE, FALSE);
3037 cfg->flags |= MONO_CFG_HAS_VARARGS;
3039 NEW_TEMPLOAD (cfg, addr, temp);
3043 MonoJitICallInfo **emul_opcode_map = NULL;
3046 mono_find_jit_opcode_emulation (int opcode)
3048 if (emul_opcode_map)
3049 return emul_opcode_map [opcode];
3054 static MonoException*
3055 mini_loader_error_to_exception (MonoLoaderError *error)
3057 MonoException *ex = NULL;
3059 switch (error->kind) {
3060 case MONO_LOADER_ERROR_TYPE: {
3061 MonoString *class_name = mono_string_new (mono_domain_get (), error->class_name);
3063 ex = mono_get_exception_type_load (class_name, error->assembly_name);
3066 case MONO_LOADER_ERROR_METHOD:
3067 case MONO_LOADER_ERROR_FIELD: {
3070 class_name = g_strdup_printf ("%s%s%s", error->klass->name_space, *error->klass->name_space ? "." : "", error->klass->name);
3072 if (error->kind == MONO_LOADER_ERROR_METHOD)
3073 ex = mono_get_exception_missing_method (class_name, error->member_name);
3075 ex = mono_get_exception_missing_field (class_name, error->member_name);
3076 g_free (class_name);
3080 g_assert_not_reached ();
3087 mini_get_inst_for_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoInst **args)
3089 MonoInst *ins = NULL;
3091 static MonoClass *runtime_helpers_class = NULL;
3092 if (! runtime_helpers_class)
3093 runtime_helpers_class = mono_class_from_name (mono_defaults.corlib,
3094 "System.Runtime.CompilerServices", "RuntimeHelpers");
3096 if (cmethod->klass == mono_defaults.string_class) {
3097 if (strcmp (cmethod->name, "get_Chars") == 0) {
3098 MONO_INST_NEW (cfg, ins, OP_GETCHR);
3099 ins->inst_i0 = args [0];
3100 ins->inst_i1 = args [1];
3102 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3103 MONO_INST_NEW (cfg, ins, OP_STRLEN);
3104 ins->inst_i0 = args [0];
3106 } else if (strcmp (cmethod->name, "InternalSetChar") == 0) {
3108 MONO_INST_NEW (cfg, get_addr, OP_STR_CHAR_ADDR);
3109 get_addr->inst_i0 = args [0];
3110 get_addr->inst_i1 = args [1];
3111 MONO_INST_NEW (cfg, ins, CEE_STIND_I2);
3112 ins->inst_i0 = get_addr;
3113 ins->inst_i1 = args [2];
3117 } else if (cmethod->klass == mono_defaults.object_class) {
3118 if (strcmp (cmethod->name, "GetType") == 0) {
3119 MONO_INST_NEW (cfg, ins, OP_GETTYPE);
3120 ins->inst_i0 = args [0];
3122 /* The OP_GETHASHCODE rule depends on OP_MUL */
3123 #if !defined(MONO_ARCH_EMULATE_MUL_DIV) && !defined(HAVE_MOVING_COLLECTOR)
3124 } else if (strcmp (cmethod->name, "InternalGetHashCode") == 0) {
3125 MONO_INST_NEW (cfg, ins, OP_GETHASHCODE);
3126 ins->inst_i0 = args [0];
3129 } else if (strcmp (cmethod->name, ".ctor") == 0) {
3130 MONO_INST_NEW (cfg, ins, CEE_NOP);
3134 } else if (cmethod->klass == mono_defaults.array_class) {
3135 if (cmethod->name [0] != 'g')
3138 if (strcmp (cmethod->name, "get_Rank") == 0) {
3139 MONO_INST_NEW (cfg, ins, OP_ARRAY_RANK);
3140 ins->inst_i0 = args [0];
3142 } else if (strcmp (cmethod->name, "get_Length") == 0) {
3143 MONO_INST_NEW (cfg, ins, CEE_LDLEN);
3144 ins->inst_i0 = args [0];
3148 } else if (cmethod->klass == runtime_helpers_class) {
3149 if (strcmp (cmethod->name, "get_OffsetToStringData") == 0) {
3150 NEW_ICONST (cfg, ins, G_STRUCT_OFFSET (MonoString, chars));
3154 } else if (cmethod->klass == mono_defaults.thread_class) {
3155 if (strcmp (cmethod->name, "get_CurrentThread") == 0 && (ins = mono_arch_get_thread_intrinsic (cfg)))
3157 } else if (mini_class_is_system_array (cmethod->klass) &&
3158 strcmp (cmethod->name, "GetGenericValueImpl") == 0) {
3160 MonoInst *ldelem, *store, *load;
3161 MonoClass *eklass = mono_class_from_mono_type (fsig->params [1]);
3163 n = mono_type_to_stind (&eklass->byval_arg);
3168 NEW_LDELEMA (cfg, ldelem, sp, eklass);
3169 ldelem->flags |= MONO_INST_NORANGECHECK;
3170 MONO_INST_NEW (cfg, store, n);
3171 n = mono_type_to_ldind (&eklass->byval_arg);
3172 MONO_INST_NEW (cfg, load, mono_type_to_ldind (&eklass->byval_arg));
3173 type_to_eval_stack_type (&eklass->byval_arg, load);
3174 load->inst_left = ldelem;
3175 store->inst_left = args [2];
3176 store->inst_right = load;
3180 return mono_arch_get_inst_for_method (cfg, cmethod, fsig, args);
3184 mono_save_args (MonoCompile *cfg, MonoBasicBlock *bblock, MonoMethodSignature *sig, MonoInst **sp, MonoInst **args)
3186 MonoInst *store, *temp;
3189 g_assert (!MONO_TYPE_ISSTRUCT (sig->ret));
3191 if (!sig->hasthis && sig->param_count == 0)
3195 if (sp [0]->opcode == OP_ICONST) {
3198 temp = mono_compile_create_var (cfg, type_from_stack_type (*sp), OP_LOCAL);
3200 NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3201 store->cil_code = sp [0]->cil_code;
3202 MONO_ADD_INS (bblock, store);
3207 for (i = 0; i < sig->param_count; ++i) {
3208 if (sp [0]->opcode == OP_ICONST) {
3211 temp = mono_compile_create_var (cfg, sig->params [i], OP_LOCAL);
3213 NEW_TEMPSTORE (cfg, store, temp->inst_c0, *sp);
3214 store->cil_code = sp [0]->cil_code;
3215 if (store->opcode == CEE_STOBJ) {
3216 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
3217 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, temp->klass, FALSE, FALSE);
3219 MONO_ADD_INS (bblock, store);
3227 inline_method (MonoCompile *cfg, MonoMethod *cmethod, MonoMethodSignature *fsig, MonoBasicBlock *bblock, MonoInst **sp,
3228 guchar *ip, guint real_offset, GList *dont_inline, MonoBasicBlock **last_b, gboolean inline_allways)
3230 MonoInst *ins, *rvar = NULL;
3231 MonoMethodHeader *cheader;
3232 MonoBasicBlock *ebblock, *sbblock;
3233 int i, costs, new_locals_offset;
3234 MonoMethod *prev_inlined_method;
3236 if (cfg->verbose_level > 2)
3237 g_print ("INLINE START %p %s -> %s\n", cmethod, mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
3239 if (!cmethod->inline_info) {
3240 mono_jit_stats.inlineable_methods++;
3241 cmethod->inline_info = 1;
3243 /* allocate space to store the return value */
3244 if (!MONO_TYPE_IS_VOID (fsig->ret)) {
3245 rvar = mono_compile_create_var (cfg, fsig->ret, OP_LOCAL);
3248 /* allocate local variables */
3249 cheader = mono_method_get_header (cmethod);
3250 new_locals_offset = cfg->num_varinfo;
3251 for (i = 0; i < cheader->num_locals; ++i)
3252 mono_compile_create_var (cfg, cheader->locals [i], OP_LOCAL);
3254 /* allocate starte and end blocks */
3255 sbblock = NEW_BBLOCK (cfg);
3256 sbblock->block_num = cfg->num_bblocks++;
3257 sbblock->real_offset = real_offset;
3259 ebblock = NEW_BBLOCK (cfg);
3260 ebblock->block_num = cfg->num_bblocks++;
3261 ebblock->real_offset = real_offset;
3263 prev_inlined_method = cfg->inlined_method;
3264 cfg->inlined_method = cmethod;
3266 costs = mono_method_to_ir (cfg, cmethod, sbblock, ebblock, new_locals_offset, rvar, dont_inline, sp, real_offset, *ip == CEE_CALLVIRT);
3268 cfg->inlined_method = prev_inlined_method;
3270 if ((costs >= 0 && costs < 60) || inline_allways) {
3271 if (cfg->verbose_level > 2)
3272 g_print ("INLINE END %s -> %s\n", mono_method_full_name (cfg->method, TRUE), mono_method_full_name (cmethod, TRUE));
3274 mono_jit_stats.inlined_methods++;
3276 /* always add some code to avoid block split failures */
3277 MONO_INST_NEW (cfg, ins, CEE_NOP);
3278 MONO_ADD_INS (bblock, ins);
3281 bblock->next_bb = sbblock;
3282 link_bblock (cfg, bblock, sbblock);
3285 NEW_TEMPLOAD (cfg, ins, rvar->inst_c0);
3291 if (cfg->verbose_level > 2)
3292 g_print ("INLINE ABORTED %s\n", mono_method_full_name (cmethod, TRUE));
3298 * Some of these comments may well be out-of-date.
3299 * Design decisions: we do a single pass over the IL code (and we do bblock
3300 * splitting/merging in the few cases when it's required: a back jump to an IL
3301 * address that was not already seen as bblock starting point).
3302 * Code is validated as we go (full verification is still better left to metadata/verify.c).
3303 * Complex operations are decomposed in simpler ones right away. We need to let the
3304 * arch-specific code peek and poke inside this process somehow (except when the
3305 * optimizations can take advantage of the full semantic info of coarse opcodes).
3306 * All the opcodes of the form opcode.s are 'normalized' to opcode.
3307 * MonoInst->opcode initially is the IL opcode or some simplification of that
3308 * (OP_LOAD, OP_STORE). The arch-specific code may rearrange it to an arch-specific
3309 * opcode with value bigger than OP_LAST.
3310 * At this point the IR can be handed over to an interpreter, a dumb code generator
3311 * or to the optimizing code generator that will translate it to SSA form.
3313 * Profiling directed optimizations.
3314 * We may compile by default with few or no optimizations and instrument the code
3315 * or the user may indicate what methods to optimize the most either in a config file
3316 * or through repeated runs where the compiler applies offline the optimizations to
3317 * each method and then decides if it was worth it.
3320 * * consider using an array instead of an hash table (bb_hash)
3323 #define CHECK_TYPE(ins) if (!(ins)->type) goto unverified
3324 #define CHECK_STACK(num) if ((sp - stack_start) < (num)) goto unverified
3325 #define CHECK_STACK_OVF(num) if (((sp - stack_start) + (num)) > header->max_stack) goto unverified
3326 #define CHECK_ARG(num) if ((unsigned)(num) >= (unsigned)num_args) goto unverified
3327 #define CHECK_LOCAL(num) if ((unsigned)(num) >= (unsigned)header->num_locals) goto unverified
3328 #define CHECK_OPSIZE(size) if (ip + size > end) goto unverified
3331 /* offset from br.s -> br like opcodes */
3332 #define BIG_BRANCH_OFFSET 13
3335 ip_in_bb (MonoCompile *cfg, MonoBasicBlock *bb, const guint8* ip)
3337 MonoBasicBlock *b = g_hash_table_lookup (cfg->bb_hash, ip);
3339 return b == NULL || b == bb;
3343 get_basic_blocks (MonoCompile *cfg, GHashTable *bbhash, MonoMethodHeader* header, guint real_offset, unsigned char *start, unsigned char *end, unsigned char **pos)
3345 unsigned char *ip = start;
3346 unsigned char *target;
3349 MonoBasicBlock *bblock;
3350 const MonoOpcode *opcode;
3353 cli_addr = ip - start;
3354 i = mono_opcode_value ((const guint8 **)&ip, end);
3357 opcode = &mono_opcodes [i];
3358 switch (opcode->argument) {
3359 case MonoInlineNone:
3362 case MonoInlineString:
3363 case MonoInlineType:
3364 case MonoInlineField:
3365 case MonoInlineMethod:
3368 case MonoShortInlineR:
3375 case MonoShortInlineVar:
3376 case MonoShortInlineI:
3379 case MonoShortInlineBrTarget:
3380 target = start + cli_addr + 2 + (signed char)ip [1];
3381 GET_BBLOCK (cfg, bbhash, bblock, target);
3384 GET_BBLOCK (cfg, bbhash, bblock, ip);
3386 case MonoInlineBrTarget:
3387 target = start + cli_addr + 5 + (gint32)read32 (ip + 1);
3388 GET_BBLOCK (cfg, bbhash, bblock, target);
3391 GET_BBLOCK (cfg, bbhash, bblock, ip);
3393 case MonoInlineSwitch: {
3394 guint32 n = read32 (ip + 1);
3397 cli_addr += 5 + 4 * n;
3398 target = start + cli_addr;
3399 GET_BBLOCK (cfg, bbhash, bblock, target);
3401 for (j = 0; j < n; ++j) {
3402 target = start + cli_addr + (gint32)read32 (ip);
3403 GET_BBLOCK (cfg, bbhash, bblock, target);
3413 g_assert_not_reached ();
3416 if (i == CEE_THROW) {
3417 unsigned char *bb_start = ip - 1;
3419 /* Find the start of the bblock containing the throw */
3421 while ((bb_start > start) && !bblock) {
3422 bblock = g_hash_table_lookup (bbhash, (bb_start));
3426 bblock->out_of_line = 1;
3436 emit_tree (MonoCompile *cfg, MonoBasicBlock *bblock, MonoInst *ins, const guint8* ip_next)
3438 MonoInst *store, *temp, *load;
3440 if (ip_in_bb (cfg, bblock, ip_next) &&
3441 (CODE_IS_STLOC (ip_next) || *ip_next == CEE_RET))
3444 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
3445 temp->flags |= MONO_INST_IS_TEMP;
3446 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
3447 store->cil_code = ins->cil_code;
3448 MONO_ADD_INS (bblock, store);
3449 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
3450 load->cil_code = ins->cil_code;
3454 static inline MonoMethod *
3455 mini_get_method (MonoMethod *m, guint32 token, MonoClass *klass, MonoGenericContext *context)
3459 if (m->wrapper_type != MONO_WRAPPER_NONE)
3460 return mono_method_get_wrapper_data (m, token);
3462 method = mono_get_method_full (m->klass->image, token, klass, context);
3464 if (method && method->is_inflated)
3465 method = mono_get_inflated_method (method);
3470 static inline MonoClass*
3471 mini_get_class (MonoMethod *method, guint32 token, MonoGenericContext *context)
3475 if (method->wrapper_type != MONO_WRAPPER_NONE)
3476 klass = mono_method_get_wrapper_data (method, token);
3478 klass = mono_class_get_full (method->klass->image, token, context);
3480 mono_class_init (klass);
3485 void check_linkdemand (MonoCompile *cfg, MonoMethod *caller, MonoMethod *callee, MonoBasicBlock *bblock, unsigned char *ip)
3487 guint32 result = mono_declsec_linkdemand (cfg->domain, caller, callee);
3488 if (result == MONO_JIT_SECURITY_OK)
3491 if (result == MONO_JIT_LINKDEMAND_ECMA) {
3492 /* Generate code to throw a SecurityException before the actual call/link */
3493 MonoAssembly *assembly = mono_image_get_assembly (caller->klass->image);
3494 MonoReflectionAssembly *refass = (MonoReflectionAssembly*) mono_assembly_get_object (cfg->domain, assembly);
3495 MonoReflectionMethod *refmet = mono_method_get_object (cfg->domain, caller, NULL);
3496 MonoSecurityManager *secman = mono_security_manager_get_methods ();
3499 NEW_ICONST (cfg, args [0], 4);
3500 NEW_PCONST (cfg, args [1], refass);
3501 NEW_PCONST (cfg, args [2], refmet);
3502 mono_emit_method_call_spilled (cfg, bblock, secman->linkdemandsecurityexception, mono_method_signature (secman->linkdemandsecurityexception), args, ip, NULL);
3503 } else if (cfg->exception_type == MONO_EXCEPTION_NONE) {
3504 /* don't hide previous results */
3505 cfg->exception_type = MONO_EXCEPTION_SECURITY_LINKDEMAND;
3506 cfg->exception_data = result;
3511 can_access_internals (MonoAssembly *accessing, MonoAssembly* accessed)
3514 if (accessing == accessed)
3516 if (!accessed || !accessing)
3518 for (tmp = accessed->friend_assembly_names; tmp; tmp = tmp->next) {
3519 MonoAssemblyName *friend = tmp->data;
3520 /* Be conservative with checks */
3523 if (strcmp (accessing->aname.name, friend->name))
3525 if (friend->public_key_token [0]) {
3526 if (!accessing->aname.public_key_token [0])
3528 if (strcmp ((char*)friend->public_key_token, (char*)accessing->aname.public_key_token))
3536 /* FIXME: check visibility of type, too */
3538 can_access_member (MonoClass *access_klass, MonoClass *member_klass, int access_level)
3540 /* Partition I 8.5.3.2 */
3541 /* the access level values are the same for fields and methods */
3542 switch (access_level) {
3543 case FIELD_ATTRIBUTE_COMPILER_CONTROLLED:
3544 /* same compilation unit */
3545 return access_klass->image == member_klass->image;
3546 case FIELD_ATTRIBUTE_PRIVATE:
3547 return access_klass == member_klass;
3548 case FIELD_ATTRIBUTE_FAM_AND_ASSEM:
3549 if (mono_class_has_parent (access_klass, member_klass) &&
3550 can_access_internals (access_klass->image->assembly, member_klass->image->assembly))
3553 case FIELD_ATTRIBUTE_ASSEMBLY:
3554 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
3555 case FIELD_ATTRIBUTE_FAMILY:
3556 if (mono_class_has_parent (access_klass, member_klass))
3559 case FIELD_ATTRIBUTE_FAM_OR_ASSEM:
3560 if (mono_class_has_parent (access_klass, member_klass))
3562 return can_access_internals (access_klass->image->assembly, member_klass->image->assembly);
3563 case FIELD_ATTRIBUTE_PUBLIC:
3570 can_access_field (MonoMethod *method, MonoClassField *field)
3572 /* FIXME: check all overlapping fields */
3573 int can = can_access_member (method->klass, field->parent, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
3575 MonoClass *nested = method->klass->nested_in;
3577 can = can_access_member (nested, field->parent, field->type->attrs & FIELD_ATTRIBUTE_FIELD_ACCESS_MASK);
3580 nested = nested->nested_in;
3587 can_access_method (MonoMethod *method, MonoMethod *called)
3589 int can = can_access_member (method->klass, called->klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
3591 MonoClass *nested = method->klass->nested_in;
3593 can = can_access_member (nested, called->klass, called->flags & METHOD_ATTRIBUTE_MEMBER_ACCESS_MASK);
3596 nested = nested->nested_in;
3601 * with generics calls to explicit interface implementations can be expressed
3602 * directly: the method is private, but we must allow it. This may be opening
3603 * a hole or the generics code should handle this differently.
3604 * Maybe just ensure the interface type is public.
3606 if ((called->flags & METHOD_ATTRIBUTE_VIRTUAL) && (called->flags & METHOD_ATTRIBUTE_FINAL))
3612 * mono_method_to_ir: translates IL into basic blocks containing trees
3615 mono_method_to_ir (MonoCompile *cfg, MonoMethod *method, MonoBasicBlock *start_bblock, MonoBasicBlock *end_bblock,
3616 int locals_offset, MonoInst *return_var, GList *dont_inline, MonoInst **inline_args,
3617 guint inline_offset, gboolean is_virtual_call)
3619 MonoInst *zero_int32, *zero_int64, *zero_ptr, *zero_obj, *zero_r8;
3620 MonoInst *ins, **sp, **stack_start;
3621 MonoBasicBlock *bblock, *tblock = NULL, *init_localsbb = NULL;
3623 MonoMethod *cmethod;
3624 MonoInst **arg_array;
3625 MonoMethodHeader *header;
3627 guint32 token, ins_flag;
3629 MonoClass *constrained_call = NULL;
3630 unsigned char *ip, *end, *target, *err_pos;
3631 static double r8_0 = 0.0;
3632 MonoMethodSignature *sig;
3633 MonoGenericContext *generic_context = NULL;
3634 MonoGenericContainer *generic_container = NULL;
3635 MonoType **param_types;
3636 GList *bb_recheck = NULL, *tmp;
3637 int i, n, start_new_bblock, ialign;
3638 int num_calls = 0, inline_costs = 0;
3639 int breakpoint_id = 0;
3641 guint real_offset, num_args;
3642 MonoBoolean security, pinvoke;
3643 MonoSecurityManager* secman = NULL;
3644 MonoDeclSecurityActions actions;
3645 GSList *class_inits = NULL;
3646 gboolean dont_verify, dont_verify_stloc;
3648 /* serialization and xdomain stuff may need access to private fields and methods */
3649 dont_verify = method->klass->image->assembly->corlib_internal? TRUE: FALSE;
3650 dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE;
3651 dont_verify |= method->wrapper_type == MONO_WRAPPER_XDOMAIN_DISPATCH;
3653 /* still some type unsefety issues in marshal wrappers... (unknown is PtrToStructure) */
3654 dont_verify_stloc = method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE;
3655 dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_UNKNOWN;
3656 dont_verify_stloc |= method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED;
3658 image = method->klass->image;
3659 header = mono_method_get_header (method);
3660 generic_container = method->generic_container;
3661 sig = mono_method_signature (method);
3662 num_args = sig->hasthis + sig->param_count;
3663 ip = (unsigned char*)header->code;
3664 end = ip + header->code_size;
3665 mono_jit_stats.cil_code_size += header->code_size;
3667 if (sig->is_inflated)
3668 generic_context = ((MonoMethodInflated *) method)->context;
3669 else if (generic_container)
3670 generic_context = &generic_container->context;
3672 g_assert (!sig->has_type_parameters);
3674 if (cfg->method == method) {
3676 bbhash = cfg->bb_hash;
3678 real_offset = inline_offset;
3679 bbhash = g_hash_table_new (g_direct_hash, NULL);
3682 if (cfg->verbose_level > 2)
3683 g_print ("method to IR %s\n", mono_method_full_name (method, TRUE));
3685 dont_inline = g_list_prepend (dont_inline, method);
3686 if (cfg->method == method) {
3688 if (cfg->method->save_lmf)
3689 /* Needed by the prolog code */
3690 mono_get_got_var (cfg);
3692 if (cfg->prof_options & MONO_PROFILE_INS_COVERAGE)
3693 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, header->code_size);
3696 cfg->bb_entry = start_bblock = NEW_BBLOCK (cfg);
3697 start_bblock->cil_code = NULL;
3698 start_bblock->cil_length = 0;
3699 start_bblock->block_num = cfg->num_bblocks++;
3702 cfg->bb_exit = end_bblock = NEW_BBLOCK (cfg);
3703 end_bblock->cil_code = NULL;
3704 end_bblock->cil_length = 0;
3705 end_bblock->block_num = cfg->num_bblocks++;
3706 g_assert (cfg->num_bblocks == 2);
3708 arg_array = alloca (sizeof (MonoInst *) * num_args);
3709 for (i = num_args - 1; i >= 0; i--)
3710 arg_array [i] = cfg->varinfo [i];
3712 if (header->num_clauses) {
3713 cfg->spvars = g_hash_table_new (NULL, NULL);
3714 cfg->exvars = g_hash_table_new (NULL, NULL);
3716 /* handle exception clauses */
3717 for (i = 0; i < header->num_clauses; ++i) {
3718 MonoBasicBlock *try_bb;
3719 MonoExceptionClause *clause = &header->clauses [i];
3720 GET_BBLOCK (cfg, bbhash, try_bb, ip + clause->try_offset);
3721 try_bb->real_offset = clause->try_offset;
3722 GET_BBLOCK (cfg, bbhash, tblock, ip + clause->handler_offset);
3723 tblock->real_offset = clause->handler_offset;
3724 tblock->flags |= BB_EXCEPTION_HANDLER;
3726 link_bblock (cfg, try_bb, tblock);
3728 if (*(ip + clause->handler_offset) == CEE_POP)
3729 tblock->flags |= BB_EXCEPTION_DEAD_OBJ;
3731 if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY ||
3732 clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
3733 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
3734 MONO_ADD_INS (tblock, ins);
3736 /* todo: is a fault block unsafe to optimize? */
3737 if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
3738 tblock->flags |= BB_EXCEPTION_UNSAFE;
3742 /*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);
3744 g_print ("%s", mono_disasm_code_one (NULL, method, p, &p));
3746 /* catch and filter blocks get the exception object on the stack */
3747 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE ||
3748 clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
3749 MonoInst *load, *dummy_use;
3751 /* mostly like handle_stack_args (), but just sets the input args */
3752 /* g_print ("handling clause at IL_%04x\n", clause->handler_offset); */
3753 tblock->in_scount = 1;
3754 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
3755 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
3758 * Add a dummy use for the exvar so its liveness info will be
3761 NEW_TEMPLOAD (cfg, load, tblock->in_stack [0]->inst_c0);
3762 NEW_DUMMY_USE (cfg, dummy_use, load);
3763 MONO_ADD_INS (tblock, dummy_use);
3765 if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
3766 GET_BBLOCK (cfg, bbhash, tblock, ip + clause->data.filter_offset);
3767 tblock->real_offset = clause->data.filter_offset;
3768 tblock->in_scount = 1;
3769 tblock->in_stack = mono_mempool_alloc (cfg->mempool, sizeof (MonoInst*));
3770 /* The filter block shares the exvar with the handler block */
3771 tblock->in_stack [0] = mono_create_exvar_for_offset (cfg, clause->handler_offset);
3772 MONO_INST_NEW (cfg, ins, OP_START_HANDLER);
3773 MONO_ADD_INS (tblock, ins);
3778 arg_array = alloca (sizeof (MonoInst *) * num_args);
3779 mono_save_args (cfg, start_bblock, sig, inline_args, arg_array);
3782 /* FIRST CODE BLOCK */
3783 bblock = NEW_BBLOCK (cfg);
3784 bblock->cil_code = ip;
3786 ADD_BBLOCK (cfg, bbhash, bblock);
3788 if (cfg->method == method) {
3789 breakpoint_id = mono_debugger_method_has_breakpoint (method);
3790 if (breakpoint_id && (mono_debug_format != MONO_DEBUG_FORMAT_DEBUGGER)) {
3791 MONO_INST_NEW (cfg, ins, CEE_BREAK);
3792 MONO_ADD_INS (bblock, ins);
3796 if (mono_use_security_manager)
3797 secman = mono_security_manager_get_methods ();
3799 security = (secman && mono_method_has_declsec (method));
3800 /* at this point having security doesn't mean we have any code to generate */
3801 if (security && (cfg->method == method)) {
3802 /* Only Demand, NonCasDemand and DemandChoice requires code generation.
3803 * And we do not want to enter the next section (with allocation) if we
3804 * have nothing to generate */
3805 security = mono_declsec_get_demands (method, &actions);
3808 /* we must Demand SecurityPermission.Unmanaged before P/Invoking */
3809 pinvoke = (secman && (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE));
3811 MonoMethod *wrapped = mono_marshal_method_from_wrapper (method);
3812 if (wrapped && (wrapped->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
3813 MonoCustomAttrInfo* custom = mono_custom_attrs_from_method (wrapped);
3815 /* unless the method or it's class has the [SuppressUnmanagedCodeSecurity] attribute */
3816 if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
3821 custom = mono_custom_attrs_from_class (wrapped->klass);
3822 if (custom && mono_custom_attrs_has_attr (custom, secman->suppressunmanagedcodesecurity)) {
3827 /* not a P/Invoke after all */
3832 if ((header->init_locals || (cfg->method == method && (cfg->opt & MONO_OPT_SHARED))) || mono_compile_aot || security || pinvoke) {
3833 /* we use a separate basic block for the initialization code */
3834 cfg->bb_init = init_localsbb = NEW_BBLOCK (cfg);
3835 init_localsbb->real_offset = real_offset;
3836 start_bblock->next_bb = init_localsbb;
3837 init_localsbb->next_bb = bblock;
3838 link_bblock (cfg, start_bblock, init_localsbb);
3839 link_bblock (cfg, init_localsbb, bblock);
3840 init_localsbb->block_num = cfg->num_bblocks++;
3842 start_bblock->next_bb = bblock;
3843 link_bblock (cfg, start_bblock, bblock);
3846 /* at this point we know, if security is TRUE, that some code needs to be generated */
3847 if (security && (cfg->method == method)) {
3850 mono_jit_stats.cas_demand_generation++;
3852 if (actions.demand.blob) {
3853 /* Add code for SecurityAction.Demand */
3854 NEW_DECLSECCONST (cfg, args[0], image, actions.demand);
3855 NEW_ICONST (cfg, args [1], actions.demand.size);
3856 /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
3857 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
3859 if (actions.noncasdemand.blob) {
3860 /* CLR 1.x uses a .noncasdemand (but 2.x doesn't) */
3861 /* For Mono we re-route non-CAS Demand to Demand (as the managed code must deal with it anyway) */
3862 NEW_DECLSECCONST (cfg, args[0], image, actions.noncasdemand);
3863 NEW_ICONST (cfg, args [1], actions.noncasdemand.size);
3864 /* Calls static void SecurityManager.InternalDemand (byte* permissions, int size); */
3865 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demand, mono_method_signature (secman->demand), args, ip, NULL);
3867 if (actions.demandchoice.blob) {
3868 /* New in 2.0, Demand must succeed for one of the permissions (i.e. not all) */
3869 NEW_DECLSECCONST (cfg, args[0], image, actions.demandchoice);
3870 NEW_ICONST (cfg, args [1], actions.demandchoice.size);
3871 /* Calls static void SecurityManager.InternalDemandChoice (byte* permissions, int size); */
3872 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandchoice, mono_method_signature (secman->demandchoice), args, ip, NULL);
3876 /* we must Demand SecurityPermission.Unmanaged before p/invoking */
3878 mono_emit_method_call_spilled (cfg, init_localsbb, secman->demandunmanaged, mono_method_signature (secman->demandunmanaged), NULL, ip, NULL);
3881 if (get_basic_blocks (cfg, bbhash, header, real_offset, ip, end, &err_pos)) {
3886 if (cfg->method == method)
3887 mono_debug_init_method (cfg, bblock, breakpoint_id);
3889 param_types = mono_mempool_alloc (cfg->mempool, sizeof (MonoType*) * num_args);
3891 param_types [0] = method->klass->valuetype?&method->klass->this_arg:&method->klass->byval_arg;
3892 for (n = 0; n < sig->param_count; ++n)
3893 param_types [n + sig->hasthis] = sig->params [n];
3894 for (n = 0; n < header->num_locals; ++n) {
3895 if (header->locals [n]->type == MONO_TYPE_VOID && !header->locals [n]->byref)
3900 /* do this somewhere outside - not here */
3901 NEW_ICONST (cfg, zero_int32, 0);
3902 NEW_ICONST (cfg, zero_int64, 0);
3903 zero_int64->type = STACK_I8;
3904 NEW_PCONST (cfg, zero_ptr, 0);
3905 NEW_PCONST (cfg, zero_obj, 0);
3906 zero_obj->type = STACK_OBJ;
3908 MONO_INST_NEW (cfg, zero_r8, OP_R8CONST);
3909 zero_r8->type = STACK_R8;
3910 zero_r8->inst_p0 = &r8_0;
3912 /* add a check for this != NULL to inlined methods */
3913 if (is_virtual_call) {
3914 MONO_INST_NEW (cfg, ins, OP_CHECK_THIS);
3915 NEW_ARGLOAD (cfg, ins->inst_left, 0);
3917 MONO_ADD_INS (bblock, ins);
3920 /* we use a spare stack slot in SWITCH and NEWOBJ and others */
3921 stack_start = sp = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * (header->max_stack + 1));
3924 start_new_bblock = 0;
3927 if (cfg->method == method)
3928 real_offset = ip - header->code;
3930 real_offset = inline_offset;
3932 if (start_new_bblock) {
3933 bblock->cil_length = ip - bblock->cil_code;
3934 if (start_new_bblock == 2) {
3935 g_assert (ip == tblock->cil_code);
3937 GET_BBLOCK (cfg, bbhash, tblock, ip);
3939 bblock->next_bb = tblock;
3941 start_new_bblock = 0;
3942 for (i = 0; i < bblock->in_scount; ++i) {
3943 if (cfg->verbose_level > 3)
3944 g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);
3945 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
3948 g_slist_free (class_inits);
3951 if ((tblock = g_hash_table_lookup (bbhash, ip)) && (tblock != bblock)) {
3952 link_bblock (cfg, bblock, tblock);
3953 if (sp != stack_start) {
3954 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
3957 bblock->next_bb = tblock;
3959 for (i = 0; i < bblock->in_scount; ++i) {
3960 if (cfg->verbose_level > 3)
3961 g_print ("loading %d from temp %d\n", i, (int)bblock->in_stack [i]->inst_c0);
3962 NEW_TEMPLOAD (cfg, ins, bblock->in_stack [i]->inst_c0);
3965 g_slist_free (class_inits);
3970 bblock->real_offset = real_offset;
3972 if ((cfg->method == method) && cfg->coverage_info) {
3973 MonoInst *store, *one;
3974 guint32 cil_offset = ip - header->code;
3975 cfg->coverage_info->data [cil_offset].cil_code = ip;
3977 /* TODO: Use an increment here */
3978 NEW_ICONST (cfg, one, 1);
3981 NEW_PCONST (cfg, ins, &(cfg->coverage_info->data [cil_offset].count));
3984 MONO_INST_NEW (cfg, store, CEE_STIND_I);
3985 store->cil_code = ip;
3986 store->inst_left = ins;
3987 store->inst_right = one;
3989 MONO_ADD_INS (bblock, store);
3992 if (cfg->verbose_level > 3)
3993 g_print ("converting (in B%d: stack: %d) %s", bblock->block_num, (int)(sp - stack_start), mono_disasm_code_one (NULL, method, ip, NULL));
3998 MONO_INST_NEW (cfg, ins, *ip);
3999 ins->cil_code = ip++;
4000 MONO_ADD_INS (bblock, ins);
4006 CHECK_STACK_OVF (1);
4007 n = (*ip)-CEE_LDARG_0;
4009 NEW_ARGLOAD (cfg, ins, n);
4010 ins->cil_code = ip++;
4017 CHECK_STACK_OVF (1);
4018 n = (*ip)-CEE_LDLOC_0;
4020 NEW_LOCLOAD (cfg, ins, n);
4021 ins->cil_code = ip++;
4029 n = (*ip)-CEE_STLOC_0;
4032 handle_loaded_temps (cfg, bblock, stack_start, sp);
4033 NEW_LOCSTORE (cfg, ins, n, *sp);
4035 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
4037 if (ins->opcode == CEE_STOBJ) {
4038 NEW_LOCLOADA (cfg, ins, n);
4039 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
4041 MONO_ADD_INS (bblock, ins);
4047 CHECK_STACK_OVF (1);
4049 NEW_ARGLOAD (cfg, ins, ip [1]);
4056 CHECK_STACK_OVF (1);
4058 NEW_ARGLOADA (cfg, ins, ip [1]);
4068 NEW_ARGSTORE (cfg, ins, ip [1], *sp);
4069 handle_loaded_temps (cfg, bblock, stack_start, sp);
4071 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [ip [1]], *sp))
4073 if (ins->opcode == CEE_STOBJ) {
4074 NEW_ARGLOADA (cfg, ins, ip [1]);
4075 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
4077 MONO_ADD_INS (bblock, ins);
4082 CHECK_STACK_OVF (1);
4083 CHECK_LOCAL (ip [1]);
4084 NEW_LOCLOAD (cfg, ins, ip [1]);
4091 CHECK_STACK_OVF (1);
4092 CHECK_LOCAL (ip [1]);
4093 NEW_LOCLOADA (cfg, ins, ip [1]);
4102 handle_loaded_temps (cfg, bblock, stack_start, sp);
4103 CHECK_LOCAL (ip [1]);
4104 NEW_LOCSTORE (cfg, ins, ip [1], *sp);
4106 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [ip [1]], *sp))
4108 if (ins->opcode == CEE_STOBJ) {
4109 NEW_LOCLOADA (cfg, ins, ip [1]);
4110 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
4112 MONO_ADD_INS (bblock, ins);
4117 CHECK_STACK_OVF (1);
4118 NEW_PCONST (cfg, ins, NULL);
4120 ins->type = STACK_OBJ;
4125 CHECK_STACK_OVF (1);
4126 NEW_ICONST (cfg, ins, -1);
4140 CHECK_STACK_OVF (1);
4141 NEW_ICONST (cfg, ins, (*ip) - CEE_LDC_I4_0);
4148 CHECK_STACK_OVF (1);
4150 NEW_ICONST (cfg, ins, *((signed char*)ip));
4157 CHECK_STACK_OVF (1);
4158 NEW_ICONST (cfg, ins, (gint32)read32 (ip + 1));
4165 CHECK_STACK_OVF (1);
4166 MONO_INST_NEW (cfg, ins, OP_I8CONST);
4168 ins->type = STACK_I8;
4170 ins->inst_l = (gint64)read64 (ip);
4176 /* we should really allocate this only late in the compilation process */
4177 mono_domain_lock (cfg->domain);
4178 f = mono_mempool_alloc (cfg->domain->mp, sizeof (float));
4179 mono_domain_unlock (cfg->domain);
4181 CHECK_STACK_OVF (1);
4182 MONO_INST_NEW (cfg, ins, OP_R4CONST);
4183 ins->type = STACK_R8;
4194 mono_domain_lock (cfg->domain);
4195 d = mono_mempool_alloc (cfg->domain->mp, sizeof (double));
4196 mono_domain_unlock (cfg->domain);
4198 CHECK_STACK_OVF (1);
4199 MONO_INST_NEW (cfg, ins, OP_R8CONST);
4200 ins->type = STACK_R8;
4210 MonoInst *temp, *store;
4212 CHECK_STACK_OVF (1);
4217 * small optimization: if the loaded value was from a local already,
4218 * just load it twice.
4220 if (ins->ssa_op == MONO_SSA_LOAD &&
4221 (ins->inst_i0->opcode == OP_LOCAL || ins->inst_i0->opcode == OP_ARG)) {
4223 MONO_INST_NEW (cfg, temp, 0);
4225 temp->cil_code = ip;
4228 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
4229 temp->flags |= MONO_INST_IS_TEMP;
4230 temp->cil_code = ip;
4231 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
4232 store->cil_code = ip;
4233 if (store->opcode == CEE_STOBJ) {
4234 NEW_TEMPLOADA (cfg, store, temp->inst_c0);
4235 handle_stobj (cfg, bblock, store, sp [0], sp [0]->cil_code, store->klass, TRUE, FALSE);
4237 MONO_ADD_INS (bblock, store);
4239 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
4242 NEW_TEMPLOAD (cfg, ins, temp->inst_c0);
4252 MONO_INST_NEW (cfg, ins, CEE_POP);
4253 MONO_ADD_INS (bblock, ins);
4254 ins->cil_code = ip++;
4260 if (stack_start != sp)
4262 MONO_INST_NEW (cfg, ins, CEE_JMP);
4263 token = read32 (ip + 1);
4264 /* FIXME: check the signature matches */
4265 cmethod = mini_get_method (method, token, NULL, generic_context);
4270 if (mono_use_security_manager) {
4271 check_linkdemand (cfg, method, cmethod, bblock, ip);
4274 ins->inst_p0 = cmethod;
4275 MONO_ADD_INS (bblock, ins);
4277 start_new_bblock = 1;
4281 case CEE_CALLVIRT: {
4282 MonoInst *addr = NULL;
4283 MonoMethodSignature *fsig = NULL;
4284 int temp, array_rank = 0;
4285 int virtual = *ip == CEE_CALLVIRT;
4288 token = read32 (ip + 1);
4290 if (*ip == CEE_CALLI) {
4295 if (method->wrapper_type != MONO_WRAPPER_NONE)
4296 fsig = (MonoMethodSignature *)mono_method_get_wrapper_data (method, token);
4298 fsig = mono_metadata_parse_signature (image, token);
4300 n = fsig->param_count + fsig->hasthis;
4302 if (method->wrapper_type != MONO_WRAPPER_NONE) {
4303 cmethod = (MonoMethod *)mono_method_get_wrapper_data (method, token);
4304 } else if (constrained_call) {
4305 cmethod = mono_get_method_constrained (image, token, constrained_call, generic_context);
4306 cmethod = mono_get_inflated_method (cmethod);
4308 cmethod = mini_get_method (method, token, NULL, generic_context);
4313 if (!dont_verify && !can_access_method (method, cmethod))
4316 if (!virtual && (cmethod->flags & METHOD_ATTRIBUTE_ABSTRACT))
4317 /* MS.NET seems to silently convert this to a callvirt */
4320 if (!cmethod->klass->inited)
4321 mono_class_init (cmethod->klass);
4323 if (mono_method_signature (cmethod)->pinvoke) {
4324 MonoMethod *wrapper = mono_marshal_get_native_wrapper (cmethod);
4325 fsig = mono_method_signature (wrapper);
4326 } else if (constrained_call) {
4327 fsig = mono_method_signature (cmethod);
4329 fsig = mono_method_get_signature_full (cmethod, image, token, generic_context);
4332 n = fsig->param_count + fsig->hasthis;
4334 if (mono_use_security_manager) {
4335 check_linkdemand (cfg, method, cmethod, bblock, ip);
4338 if (cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL &&
4339 mini_class_is_system_array (cmethod->klass)) {
4340 array_rank = cmethod->klass->rank;
4343 if (cmethod->string_ctor)
4344 g_assert_not_reached ();
4349 mono_get_got_var (cfg);
4351 /* code in inssel.brg might transform a virtual call to a normal call */
4352 if (!(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) ||
4353 ((cmethod->flags & METHOD_ATTRIBUTE_FINAL) &&
4354 cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK))
4355 mono_get_got_var (cfg);
4358 if (cmethod && cmethod->klass->generic_container) {
4365 //g_assert (!virtual || fsig->hasthis);
4369 if (constrained_call) {
4371 * We have the `constrained.' prefix opcode.
4373 if (constrained_call->valuetype && !cmethod->klass->valuetype) {
4376 * The type parameter is instantiated as a valuetype,
4377 * but that type doesn't override the method we're
4378 * calling, so we need to box `this'.
4379 * sp [0] is a pointer to the data: we need the value
4380 * in handle_box (), so load it here.
4382 MONO_INST_NEW (cfg, load, mono_type_to_ldind (&constrained_call->byval_arg));
4383 type_to_eval_stack_type (&constrained_call->byval_arg, load);
4384 load->cil_code = ip;
4385 load->inst_left = sp [0];
4386 sp [0] = handle_box (cfg, bblock, load, ip, constrained_call);
4387 } else if (!constrained_call->valuetype) {
4391 * The type parameter is instantiated as a reference
4392 * type. We have a managed pointer on the stack, so
4393 * we need to dereference it here.
4396 MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
4398 ins->inst_i0 = sp [0];
4399 ins->type = STACK_OBJ;
4401 } else if (cmethod->klass->valuetype)
4403 constrained_call = NULL;
4406 if (*ip != CEE_CALLI && check_call_signature (cfg, fsig, sp)) {
4411 if (cmethod && virtual &&
4412 (cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) &&
4413 !((cmethod->flags & METHOD_ATTRIBUTE_FINAL) &&
4414 cmethod->wrapper_type != MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK) &&
4415 mono_method_signature (cmethod)->generic_param_count) {
4416 MonoInst *this_temp, *store;
4417 MonoInst *iargs [3];
4419 g_assert (mono_method_signature (cmethod)->is_inflated);
4421 this_temp = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
4422 this_temp->cil_code = ip;
4423 NEW_TEMPSTORE (cfg, store, this_temp->inst_c0, sp [0]);
4425 store->cil_code = ip;
4426 MONO_ADD_INS (bblock, store);
4428 NEW_TEMPLOAD (cfg, iargs [0], this_temp->inst_c0);
4429 NEW_PCONST (cfg, iargs [1], cmethod);
4430 NEW_PCONST (cfg, iargs [2], ((MonoMethodInflated *) cmethod)->context);
4431 temp = mono_emit_jit_icall (cfg, bblock, helper_compile_generic_method, iargs, ip);
4433 NEW_TEMPLOAD (cfg, addr, temp);
4434 NEW_TEMPLOAD (cfg, sp [0], this_temp->inst_c0);
4436 if ((temp = mono_emit_calli (cfg, bblock, fsig, sp, addr, ip)) != -1) {
4437 NEW_TEMPLOAD (cfg, *sp, temp);
4445 if ((ins_flag & MONO_INST_TAILCALL) && cmethod && (*ip == CEE_CALL) &&
4446 (mono_metadata_signature_equal (mono_method_signature (method), mono_method_signature (cmethod)))) {
4448 /* FIXME: This assumes the two methods has the same number and type of arguments */
4449 for (i = 0; i < n; ++i) {
4450 /* Check if argument is the same */
4451 NEW_ARGLOAD (cfg, ins, i);
4452 if ((ins->opcode == sp [i]->opcode) && (ins->inst_i0 == sp [i]->inst_i0))
4455 /* Prevent argument from being register allocated */
4456 arg_array [i]->flags |= MONO_INST_VOLATILE;
4457 NEW_ARGSTORE (cfg, ins, i, sp [i]);
4459 if (ins->opcode == CEE_STOBJ) {
4460 NEW_ARGLOADA (cfg, ins, i);
4461 handle_stobj (cfg, bblock, ins, sp [i], sp [i]->cil_code, ins->klass, FALSE, FALSE);
4464 MONO_ADD_INS (bblock, ins);
4466 MONO_INST_NEW (cfg, ins, CEE_JMP);
4468 ins->inst_p0 = cmethod;
4469 ins->inst_p1 = arg_array [0];
4470 MONO_ADD_INS (bblock, ins);
4471 link_bblock (cfg, bblock, end_bblock);
4472 start_new_bblock = 1;
4473 /* skip CEE_RET as well */
4478 if (cmethod && (cfg->opt & MONO_OPT_INTRINS) && (ins = mini_get_inst_for_method (cfg, cmethod, fsig, sp))) {
4481 if (MONO_TYPE_IS_VOID (fsig->ret)) {
4482 MONO_ADD_INS (bblock, ins);
4484 type_to_eval_stack_type (fsig->ret, ins);
4493 handle_loaded_temps (cfg, bblock, stack_start, sp);
4495 if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
4496 (!virtual || !(cmethod->flags & METHOD_ATTRIBUTE_VIRTUAL) || (cmethod->flags & METHOD_ATTRIBUTE_FINAL)) &&
4497 mono_method_check_inlining (cfg, cmethod) &&
4498 !g_list_find (dont_inline, cmethod)) {
4500 MonoBasicBlock *ebblock;
4501 gboolean allways = FALSE;
4503 if ((cmethod->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
4504 (cmethod->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4505 cmethod = mono_marshal_get_native_wrapper (cmethod);
4509 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, allways))) {
4513 GET_BBLOCK (cfg, bbhash, bblock, ip);
4514 ebblock->next_bb = bblock;
4515 link_bblock (cfg, ebblock, bblock);
4517 if (!MONO_TYPE_IS_VOID (fsig->ret))
4520 /* indicates start of a new block, and triggers a load of all
4521 stack arguments at bb boundarie */
4524 inline_costs += costs;
4529 inline_costs += 10 * num_calls++;
4531 /* tail recursion elimination */
4532 if ((cfg->opt & MONO_OPT_TAILC) && *ip == CEE_CALL && cmethod == method && ip [5] == CEE_RET) {
4533 gboolean has_vtargs = FALSE;
4536 /* keep it simple */
4537 for (i = fsig->param_count - 1; i >= 0; i--) {
4538 if (MONO_TYPE_ISSTRUCT (mono_method_signature (cmethod)->params [i]))
4543 for (i = 0; i < n; ++i) {
4544 NEW_ARGSTORE (cfg, ins, i, sp [i]);
4546 MONO_ADD_INS (bblock, ins);
4548 MONO_INST_NEW (cfg, ins, CEE_BR);
4550 MONO_ADD_INS (bblock, ins);
4551 tblock = start_bblock->out_bb [0];
4552 link_bblock (cfg, bblock, tblock);
4553 ins->inst_target_bb = tblock;
4554 start_new_bblock = 1;
4556 /* skip the CEE_RET, too */
4557 if (ip_in_bb (cfg, bblock, ip + 5))
4566 if (*ip == CEE_CALLI) {
4568 if ((temp = mono_emit_calli (cfg, bblock, fsig, sp, addr, ip)) != -1) {
4569 NEW_TEMPLOAD (cfg, *sp, temp);
4573 } else if (array_rank) {
4576 if (strcmp (cmethod->name, "Set") == 0) { /* array Set */
4577 if (sp [fsig->param_count]->type == STACK_OBJ) {
4578 MonoInst *iargs [2];
4579 MonoInst *array, *to_store, *store;
4581 handle_loaded_temps (cfg, bblock, stack_start, sp);
4583 array = mono_compile_create_var (cfg, type_from_stack_type (sp [0]), OP_LOCAL);
4584 NEW_TEMPSTORE (cfg, store, array->inst_c0, sp [0]);
4585 store->cil_code = ip;
4586 MONO_ADD_INS (bblock, store);
4587 NEW_TEMPLOAD (cfg, iargs [0], array->inst_c0);
4589 to_store = mono_compile_create_var (cfg, type_from_stack_type (sp [fsig->param_count]), OP_LOCAL);
4590 NEW_TEMPSTORE (cfg, store, to_store->inst_c0, sp [fsig->param_count]);
4591 store->cil_code = ip;
4592 MONO_ADD_INS (bblock, store);
4593 NEW_TEMPLOAD (cfg, iargs [1], to_store->inst_c0);
4596 * We first save the args for the call so that the args are copied to the stack
4597 * and a new instruction tree for them is created. If we don't do this,
4598 * the same MonoInst is added to two different trees and this is not
4601 mono_emit_jit_icall (cfg, bblock, helper_stelem_ref_check, iargs, ip);
4603 NEW_TEMPLOAD (cfg, sp [0], array->inst_c0);
4604 NEW_TEMPLOAD (cfg, sp [fsig->param_count], to_store->inst_c0);
4607 addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, TRUE);
4608 NEW_INDSTORE (cfg, ins, addr, sp [fsig->param_count], fsig->params [fsig->param_count - 1]);
4610 if (ins->opcode == CEE_STOBJ) {
4611 handle_stobj (cfg, bblock, addr, sp [fsig->param_count], ip, mono_class_from_mono_type (fsig->params [fsig->param_count-1]), FALSE, FALSE);
4613 MONO_ADD_INS (bblock, ins);
4616 } else if (strcmp (cmethod->name, "Get") == 0) { /* array Get */
4617 addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
4618 NEW_INDLOAD (cfg, ins, addr, fsig->ret);
4622 } else if (strcmp (cmethod->name, "Address") == 0) { /* array Address */
4623 addr = mini_get_ldelema_ins (cfg, bblock, cmethod, sp, ip, FALSE);
4626 g_assert_not_reached ();
4630 if (ip_in_bb (cfg, bblock, ip + 5)
4631 && (!MONO_TYPE_ISSTRUCT (fsig->ret))
4632 && (!MONO_TYPE_IS_VOID (fsig->ret) || cmethod->string_ctor)
4633 && (CODE_IS_STLOC (ip + 5) || ip [5] == CEE_POP || ip [5] == CEE_RET)) {
4634 /* no need to spill */
4635 ins = (MonoInst*)mono_emit_method_call (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL);
4638 if ((temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, virtual ? sp [0] : NULL)) != -1) {
4639 NEW_TEMPLOAD (cfg, *sp, temp);
4649 if (cfg->method != method) {
4650 /* return from inlined methode */
4655 //g_assert (returnvar != -1);
4656 NEW_TEMPSTORE (cfg, store, return_var->inst_c0, *sp);
4657 store->cil_code = sp [0]->cil_code;
4658 if (store->opcode == CEE_STOBJ) {
4659 g_assert_not_reached ();
4660 NEW_TEMPLOADA (cfg, store, return_var->inst_c0);
4661 handle_stobj (cfg, bblock, store, *sp, sp [0]->cil_code, return_var->klass, FALSE, FALSE);
4663 MONO_ADD_INS (bblock, store);
4667 g_assert (!return_var);
4670 MONO_INST_NEW (cfg, ins, CEE_NOP);
4671 ins->opcode = mono_type_to_stind (mono_method_signature (method)->ret);
4672 if (ins->opcode == CEE_STOBJ) {
4673 NEW_RETLOADA (cfg, ins);
4674 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
4676 ins->opcode = OP_SETRET;
4678 ins->inst_i0 = *sp;;
4679 ins->inst_i1 = NULL;
4680 MONO_ADD_INS (bblock, ins);
4684 if (sp != stack_start)
4686 MONO_INST_NEW (cfg, ins, CEE_BR);
4687 ins->cil_code = ip++;
4688 ins->inst_target_bb = end_bblock;
4689 MONO_ADD_INS (bblock, ins);
4690 link_bblock (cfg, bblock, end_bblock);
4691 start_new_bblock = 1;
4695 MONO_INST_NEW (cfg, ins, CEE_BR);
4696 ins->cil_code = ip++;
4697 MONO_ADD_INS (bblock, ins);
4698 target = ip + 1 + (signed char)(*ip);
4700 GET_BBLOCK (cfg, bbhash, tblock, target);
4701 link_bblock (cfg, bblock, tblock);
4702 CHECK_BBLOCK (target, ip, tblock);
4703 ins->inst_target_bb = tblock;
4704 if (sp != stack_start) {
4705 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
4708 start_new_bblock = 1;
4709 inline_costs += BRANCH_COST;
4715 if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
4717 MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
4718 ins->cil_code = ip++;
4719 target = ip + 1 + *(signed char*)ip;
4721 ADD_UNCOND (ins->opcode == CEE_BRTRUE);
4722 if (sp != stack_start) {
4723 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
4726 inline_costs += BRANCH_COST;
4740 MONO_INST_NEW (cfg, ins, *ip + BIG_BRANCH_OFFSET);
4741 ins->cil_code = ip++;
4742 target = ip + 1 + *(signed char*)ip;
4745 if (sp != stack_start) {
4746 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
4749 inline_costs += BRANCH_COST;
4753 MONO_INST_NEW (cfg, ins, CEE_BR);
4754 ins->cil_code = ip++;
4755 MONO_ADD_INS (bblock, ins);
4756 target = ip + 4 + (gint32)read32(ip);
4758 GET_BBLOCK (cfg, bbhash, tblock, target);
4759 link_bblock (cfg, bblock, tblock);
4760 CHECK_BBLOCK (target, ip, tblock);
4761 ins->inst_target_bb = tblock;
4762 if (sp != stack_start) {
4763 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
4766 start_new_bblock = 1;
4767 inline_costs += BRANCH_COST;
4773 if (sp [-1]->type == STACK_VTYPE || sp [-1]->type == STACK_R8)
4775 MONO_INST_NEW (cfg, ins, *ip);
4776 ins->cil_code = ip++;
4777 target = ip + 4 + (gint32)read32(ip);
4779 ADD_UNCOND(ins->opcode == CEE_BRTRUE);
4780 if (sp != stack_start) {
4781 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
4784 inline_costs += BRANCH_COST;
4798 MONO_INST_NEW (cfg, ins, *ip);
4799 ins->cil_code = ip++;
4800 target = ip + 4 + (gint32)read32(ip);
4803 if (sp != stack_start) {
4804 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
4807 inline_costs += BRANCH_COST;
4812 n = read32 (ip + 1);
4813 MONO_INST_NEW (cfg, ins, *ip);
4815 ins->inst_left = *sp;
4816 if ((ins->inst_left->type != STACK_I4) && (ins->inst_left->type != STACK_PTR))
4820 CHECK_OPSIZE (n * sizeof (guint32));
4821 target = ip + n * sizeof (guint32);
4822 MONO_ADD_INS (bblock, ins);
4823 GET_BBLOCK (cfg, bbhash, tblock, target);
4824 link_bblock (cfg, bblock, tblock);
4825 ins->klass = GUINT_TO_POINTER (n);
4826 ins->inst_many_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (n + 1));
4827 ins->inst_many_bb [n] = tblock;
4829 for (i = 0; i < n; ++i) {
4830 GET_BBLOCK (cfg, bbhash, tblock, target + (gint32)read32(ip));
4831 link_bblock (cfg, bblock, tblock);
4832 ins->inst_many_bb [i] = tblock;
4835 if (sp != stack_start) {
4836 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
4839 /* Needed by the code generated in inssel.brg */
4840 mono_get_got_var (cfg);
4841 inline_costs += (BRANCH_COST * 2);
4855 MONO_INST_NEW (cfg, ins, *ip);
4860 ins->type = ldind_type [*ip - CEE_LDIND_I1];
4861 ins->flags |= ins_flag;
4873 MONO_INST_NEW (cfg, ins, *ip);
4874 ins->cil_code = ip++;
4876 handle_loaded_temps (cfg, bblock, stack_start, sp);
4877 MONO_ADD_INS (bblock, ins);
4878 ins->inst_i0 = sp [0];
4879 ins->inst_i1 = sp [1];
4880 ins->flags |= ins_flag;
4888 #ifdef MONO_ARCH_NO_EMULATE_MUL_IMM
4889 /* FIXME: This breaks with ssapre (mono -O=ssapre loader.exe) */
4890 if ((ins->inst_right->opcode == OP_ICONST) && !(cfg->opt & MONO_OPT_SSAPRE)) {
4891 switch (ins->opcode) {
4893 ins->opcode = OP_IMUL_IMM;
4894 ins->inst_imm = ins->inst_right->inst_c0;
4897 ins->opcode = OP_LMUL_IMM;
4898 ins->inst_imm = ins->inst_right->inst_c0;
4901 g_assert_not_reached ();
4906 if (mono_find_jit_opcode_emulation (ins->opcode)) {
4908 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
4909 mono_get_got_var (cfg);
4927 /* special case that gives a nice speedup and happens to workaorund a ppc jit but (for the release)
4928 * later apply the speedup to the left shift as well
4931 if ((ins->opcode == OP_LSHR_UN) && (ins->type == STACK_I8)
4932 && (ins->inst_right->opcode == OP_ICONST) && (ins->inst_right->inst_c0 == 32)) {
4933 ins->opcode = OP_LONG_SHRUN_32;
4934 /*g_print ("applied long shr speedup to %s\n", cfg->method->name);*/
4938 if (mono_find_jit_opcode_emulation (ins->opcode)) {
4940 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
4941 mono_get_got_var (cfg);
4955 case CEE_CONV_OVF_I8:
4956 case CEE_CONV_OVF_U8:
4960 if (mono_find_jit_opcode_emulation (ins->opcode)) {
4962 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
4963 mono_get_got_var (cfg);
4967 case CEE_CONV_OVF_I4:
4968 case CEE_CONV_OVF_I1:
4969 case CEE_CONV_OVF_I2:
4970 case CEE_CONV_OVF_I:
4971 case CEE_CONV_OVF_U:
4974 if (sp [-1]->type == STACK_R8) {
4975 ADD_UNOP (CEE_CONV_OVF_I8);
4983 case CEE_CONV_OVF_U1:
4984 case CEE_CONV_OVF_U2:
4985 case CEE_CONV_OVF_U4:
4988 if (sp [-1]->type == STACK_R8) {
4989 ADD_UNOP (CEE_CONV_OVF_U8);
4997 case CEE_CONV_OVF_I1_UN:
4998 case CEE_CONV_OVF_I2_UN:
4999 case CEE_CONV_OVF_I4_UN:
5000 case CEE_CONV_OVF_I8_UN:
5001 case CEE_CONV_OVF_U1_UN:
5002 case CEE_CONV_OVF_U2_UN:
5003 case CEE_CONV_OVF_U4_UN:
5004 case CEE_CONV_OVF_U8_UN:
5005 case CEE_CONV_OVF_I_UN:
5006 case CEE_CONV_OVF_U_UN:
5014 token = read32 (ip + 1);
5015 klass = mini_get_class (method, token, generic_context);
5019 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
5020 MonoInst *store, *load;
5021 MONO_INST_NEW (cfg, load, CEE_LDIND_REF);
5022 load->cil_code = ip;
5023 load->inst_i0 = sp [1];
5024 load->type = STACK_OBJ;
5025 load->flags |= ins_flag;
5026 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
5027 store->cil_code = ip;
5028 handle_loaded_temps (cfg, bblock, stack_start, sp);
5029 MONO_ADD_INS (bblock, store);
5030 store->inst_i0 = sp [0];
5031 store->inst_i1 = load;
5032 store->flags |= ins_flag;
5034 n = mono_class_value_size (klass, NULL);
5035 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
5037 MONO_INST_NEW (cfg, copy, OP_MEMCPY);
5038 copy->inst_left = sp [0];
5039 copy->inst_right = sp [1];
5040 copy->cil_code = ip;
5042 MONO_ADD_INS (bblock, copy);
5044 MonoMethod *memcpy_method = get_memcpy_method ();
5045 MonoInst *iargs [3];
5048 NEW_ICONST (cfg, iargs [2], n);
5049 iargs [2]->cil_code = ip;
5051 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
5058 MonoInst *iargs [3];
5064 token = read32 (ip + 1);
5065 klass = mini_get_class (method, token, generic_context);
5068 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
5069 MONO_INST_NEW (cfg, ins, CEE_LDIND_REF);
5071 ins->inst_i0 = sp [0];
5072 ins->type = STACK_OBJ;
5073 ins->flags |= ins_flag;
5080 /* Optimize the common ldobj+stloc combination */
5090 loc_index = ip [5] - CEE_STLOC_0;
5097 if ((loc_index != -1) && ip_in_bb (cfg, bblock, ip + 5)) {
5098 CHECK_LOCAL (loc_index);
5099 NEW_LOCSTORE (cfg, ins, loc_index, *sp);
5101 if (ins->opcode == CEE_STOBJ) {
5102 handle_loaded_temps (cfg, bblock, stack_start, sp);
5104 g_assert (ins->opcode == CEE_STOBJ);
5105 NEW_LOCLOADA (cfg, ins, loc_index);
5106 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
5113 n = mono_class_value_size (klass, NULL);
5114 ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
5115 NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
5116 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
5118 MONO_INST_NEW (cfg, copy, OP_MEMCPY);
5119 copy->inst_left = iargs [0];
5120 copy->inst_right = *sp;
5121 copy->cil_code = ip;
5123 MONO_ADD_INS (bblock, copy);
5125 MonoMethod *memcpy_method = get_memcpy_method ();
5127 NEW_ICONST (cfg, iargs [2], n);
5128 iargs [2]->cil_code = ip;
5130 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
5132 NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
5140 CHECK_STACK_OVF (1);
5142 n = read32 (ip + 1);
5144 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
5145 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, n));
5147 ins->type = STACK_OBJ;
5150 else if (method->wrapper_type != MONO_WRAPPER_NONE) {
5152 MonoInst *iargs [1];
5154 NEW_PCONST (cfg, iargs [0], mono_method_get_wrapper_data (method, n));
5155 temp = mono_emit_jit_icall (cfg, bblock, mono_string_new_wrapper, iargs, ip);
5156 NEW_TEMPLOAD (cfg, *sp, temp);
5160 if (cfg->opt & MONO_OPT_SHARED) {
5162 MonoInst *iargs [3];
5163 MonoInst* domain_var;
5165 if (cfg->compile_aot) {
5166 cfg->ldstr_list = g_list_prepend (cfg->ldstr_list, GINT_TO_POINTER (n));
5168 /* avoid depending on undefined C behavior in sequence points */
5169 domain_var = mono_get_domainvar (cfg);
5170 NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
5171 NEW_IMAGECONST (cfg, iargs [1], image);
5172 NEW_ICONST (cfg, iargs [2], mono_metadata_token_index (n));
5173 temp = mono_emit_jit_icall (cfg, bblock, mono_ldstr, iargs, ip);
5174 NEW_TEMPLOAD (cfg, *sp, temp);
5175 mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
5177 if (bblock->out_of_line) {
5178 MonoInst *iargs [2];
5181 /* Avoid creating the string object */
5182 NEW_IMAGECONST (cfg, iargs [0], image);
5183 NEW_ICONST (cfg, iargs [1], mono_metadata_token_index (n));
5184 temp = mono_emit_jit_icall (cfg, bblock, helper_ldstr, iargs, ip);
5185 NEW_TEMPLOAD (cfg, *sp, temp);
5188 if (cfg->compile_aot) {
5189 NEW_LDSTRCONST (cfg, ins, image, n);
5193 NEW_PCONST (cfg, ins, NULL);
5195 ins->type = STACK_OBJ;
5196 ins->inst_p0 = mono_ldstr (cfg->domain, image, mono_metadata_token_index (n));
5206 MonoInst *iargs [2];
5207 MonoMethodSignature *fsig;
5211 token = read32 (ip + 1);
5212 cmethod = mini_get_method (method, token, NULL, generic_context);
5215 fsig = mono_method_get_signature (cmethod, image, token);
5217 mono_class_init (cmethod->klass);
5219 if (mono_use_security_manager) {
5220 check_linkdemand (cfg, method, cmethod, bblock, ip);
5223 n = fsig->param_count;
5226 /* move the args to allow room for 'this' in the first position */
5232 handle_loaded_temps (cfg, bblock, stack_start, sp);
5234 if (mini_class_is_system_array (cmethod->klass)) {
5235 NEW_METHODCONST (cfg, *sp, cmethod);
5236 temp = handle_array_new (cfg, bblock, fsig->param_count, sp, ip);
5237 } else if (cmethod->string_ctor) {
5238 /* we simply pass a null pointer */
5239 NEW_PCONST (cfg, *sp, NULL);
5240 /* now call the string ctor */
5241 temp = mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, NULL);
5243 MonoInst* callvirt_this_arg = NULL;
5245 if (cmethod->klass->valuetype) {
5246 iargs [0] = mono_compile_create_var (cfg, &cmethod->klass->byval_arg, OP_LOCAL);
5247 temp = iargs [0]->inst_c0;
5249 NEW_TEMPLOADA (cfg, *sp, temp);
5251 handle_initobj (cfg, bblock, *sp, NULL, cmethod->klass, stack_start, sp);
5253 NEW_TEMPLOADA (cfg, *sp, temp);
5256 * The code generated by mini_emit_virtual_call () expects
5257 * iargs [0] to be a boxed instance, but luckily the vcall
5258 * will be transformed into a normal call there. The AOT
5259 * case needs an already allocate got_var.
5261 mono_get_got_var (cfg);
5263 temp = handle_alloc (cfg, bblock, cmethod->klass, FALSE, ip);
5264 NEW_TEMPLOAD (cfg, *sp, temp);
5267 /* Avoid virtual calls to ctors if possible */
5268 if (cmethod->klass->marshalbyref)
5269 callvirt_this_arg = sp [0];
5271 if ((cfg->opt & MONO_OPT_INLINE) && cmethod &&
5272 mono_method_check_inlining (cfg, cmethod) &&
5273 !mono_class_is_subclass_of (cmethod->klass, mono_defaults.exception_class, FALSE) &&
5274 !g_list_find (dont_inline, cmethod)) {
5276 MonoBasicBlock *ebblock;
5277 if ((costs = inline_method (cfg, cmethod, fsig, bblock, sp, ip, real_offset, dont_inline, &ebblock, FALSE))) {
5282 GET_BBLOCK (cfg, bbhash, bblock, ip);
5283 ebblock->next_bb = bblock;
5284 link_bblock (cfg, ebblock, bblock);
5286 NEW_TEMPLOAD (cfg, *sp, temp);
5289 /* indicates start of a new block, and triggers a load
5290 of all stack arguments at bb boundarie */
5293 inline_costs += costs;
5297 mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
5300 /* now call the actual ctor */
5301 mono_emit_method_call_spilled (cfg, bblock, cmethod, fsig, sp, ip, callvirt_this_arg);
5305 NEW_TEMPLOAD (cfg, *sp, temp);
5316 token = read32 (ip + 1);
5317 klass = mini_get_class (method, token, generic_context);
5320 if (sp [0]->type != STACK_OBJ)
5323 /* Needed by the code generated in inssel.brg */
5324 mono_get_got_var (cfg);
5326 if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
5328 MonoMethod *mono_isinst;
5329 MonoInst *iargs [1];
5330 MonoBasicBlock *ebblock;
5334 mono_isinst = mono_marshal_get_isinst (klass);
5337 costs = inline_method (cfg, mono_isinst, mono_method_signature (mono_isinst), bblock,
5338 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
5340 g_assert (costs > 0);
5345 GET_BBLOCK (cfg, bbhash, bblock, ip);
5346 ebblock->next_bb = bblock;
5347 link_bblock (cfg, ebblock, bblock);
5349 temp = iargs [0]->inst_i0->inst_c0;
5350 NEW_TEMPLOAD (cfg, *sp, temp);
5354 inline_costs += costs;
5356 MONO_INST_NEW (cfg, ins, *ip);
5357 ins->type = STACK_OBJ;
5358 ins->inst_left = *sp;
5359 ins->inst_newa_class = klass;
5362 *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
5366 case CEE_UNBOX_ANY: {
5367 MonoInst *add, *vtoffset;
5368 MonoInst *iargs [3];
5373 token = read32 (ip + 1);
5374 klass = mini_get_class (method, token, generic_context);
5378 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
5380 if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
5381 MonoMethod *mono_castclass;
5382 MonoInst *iargs [1];
5383 MonoBasicBlock *ebblock;
5387 mono_castclass = mono_marshal_get_castclass (klass);
5390 costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), bblock,
5391 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
5393 g_assert (costs > 0);
5398 GET_BBLOCK (cfg, bbhash, bblock, ip);
5399 ebblock->next_bb = bblock;
5400 link_bblock (cfg, ebblock, bblock);
5402 temp = iargs [0]->inst_i0->inst_c0;
5403 NEW_TEMPLOAD (cfg, *sp, temp);
5407 inline_costs += costs;
5409 MONO_INST_NEW (cfg, ins, CEE_CASTCLASS);
5410 ins->type = STACK_OBJ;
5411 ins->inst_left = *sp;
5413 ins->inst_newa_class = klass;
5421 if (mono_class_is_nullable (klass)) {
5422 int v = handle_unbox_nullable (cfg, bblock, *sp, ip, klass);
5423 NEW_TEMPLOAD (cfg, *sp, v);
5429 MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
5430 ins->type = STACK_OBJ;
5431 ins->inst_left = *sp;
5433 ins->inst_newa_class = klass;
5436 MONO_INST_NEW (cfg, add, OP_PADD);
5437 NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
5438 add->inst_left = ins;
5439 add->inst_right = vtoffset;
5440 add->type = STACK_MP;
5444 n = mono_class_value_size (klass, NULL);
5445 ins = mono_compile_create_var (cfg, &klass->byval_arg, OP_LOCAL);
5446 NEW_TEMPLOADA (cfg, iargs [0], ins->inst_c0);
5447 if ((cfg->opt & MONO_OPT_INTRINS) && n <= sizeof (gpointer) * 5) {
5449 MONO_INST_NEW (cfg, copy, OP_MEMCPY);
5450 copy->inst_left = iargs [0];
5451 copy->inst_right = *sp;
5452 copy->cil_code = ip;
5454 MONO_ADD_INS (bblock, copy);
5456 MonoMethod *memcpy_method = get_memcpy_method ();
5458 NEW_ICONST (cfg, iargs [2], n);
5459 iargs [2]->cil_code = ip;
5461 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
5463 NEW_TEMPLOAD (cfg, *sp, ins->inst_c0);
5469 MonoInst *add, *vtoffset;
5474 token = read32 (ip + 1);
5475 klass = mini_get_class (method, token, generic_context);
5479 if (mono_class_is_nullable (klass)) {
5480 int v = handle_unbox_nullable (cfg, bblock, *sp, ip, klass);
5481 NEW_TEMPLOAD (cfg, *sp, v);
5487 /* Needed by the code generated in inssel.brg */
5488 mono_get_got_var (cfg);
5490 MONO_INST_NEW (cfg, ins, OP_UNBOXCAST);
5491 ins->type = STACK_OBJ;
5492 ins->inst_left = *sp;
5494 ins->inst_newa_class = klass;
5497 MONO_INST_NEW (cfg, add, OP_PADD);
5498 NEW_ICONST (cfg, vtoffset, sizeof (MonoObject));
5499 add->inst_left = ins;
5500 add->inst_right = vtoffset;
5501 add->type = STACK_MP;
5512 token = read32 (ip + 1);
5513 klass = mini_get_class (method, token, generic_context);
5516 if (sp [0]->type != STACK_OBJ)
5519 /* Needed by the code generated in inssel.brg */
5520 mono_get_got_var (cfg);
5522 if (klass->marshalbyref || klass->flags & TYPE_ATTRIBUTE_INTERFACE) {
5524 MonoMethod *mono_castclass;
5525 MonoInst *iargs [1];
5526 MonoBasicBlock *ebblock;
5530 mono_castclass = mono_marshal_get_castclass (klass);
5533 costs = inline_method (cfg, mono_castclass, mono_method_signature (mono_castclass), bblock,
5534 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
5536 g_assert (costs > 0);
5541 GET_BBLOCK (cfg, bbhash, bblock, ip);
5542 ebblock->next_bb = bblock;
5543 link_bblock (cfg, ebblock, bblock);
5545 temp = iargs [0]->inst_i0->inst_c0;
5546 NEW_TEMPLOAD (cfg, *sp, temp);
5550 inline_costs += costs;
5552 MONO_INST_NEW (cfg, ins, *ip);
5553 ins->type = STACK_OBJ;
5554 ins->inst_left = *sp;
5556 ins->inst_newa_class = klass;
5558 *sp++ = emit_tree (cfg, bblock, ins, ip + 5);
5564 MONO_INST_NEW (cfg, ins, *ip);
5566 ins->inst_left = *sp;
5567 ins->cil_code = ip++;
5568 bblock->out_of_line = TRUE;
5569 MONO_ADD_INS (bblock, ins);
5570 MONO_INST_NEW (cfg, ins, OP_NOT_REACHED);
5571 ins->cil_code = ip - 1;
5572 MONO_ADD_INS (bblock, ins);
5575 link_bblock (cfg, bblock, end_bblock);
5576 start_new_bblock = 1;
5577 mono_get_got_var (cfg);
5582 MonoInst *offset_ins;
5583 MonoClassField *field;
5584 MonoBasicBlock *ebblock;
5588 if (*ip == CEE_STFLD) {
5595 if (sp [0]->type == STACK_I4 || sp [0]->type == STACK_I8 || sp [0]->type == STACK_R8)
5597 if (*ip != CEE_LDFLD && sp [0]->type == STACK_VTYPE)
5600 token = read32 (ip + 1);
5601 if (method->wrapper_type != MONO_WRAPPER_NONE) {
5602 field = mono_method_get_wrapper_data (method, token);
5603 klass = field->parent;
5605 field = mono_field_from_token (image, token, &klass, generic_context);
5609 mono_class_init (klass);
5610 if (!dont_verify && !can_access_field (method, field))
5613 foffset = klass->valuetype? field->offset - sizeof (MonoObject): field->offset;
5614 /* FIXME: mark instructions for use in SSA */
5615 if (*ip == CEE_STFLD) {
5616 if (target_type_is_incompatible (cfg, field->type, sp [1]))
5618 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
5619 MonoMethod *stfld_wrapper = mono_marshal_get_stfld_wrapper (field->type);
5620 MonoInst *iargs [5];
5623 NEW_CLASSCONST (cfg, iargs [1], klass);
5624 NEW_FIELDCONST (cfg, iargs [2], field);
5625 NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) :
5629 if (cfg->opt & MONO_OPT_INLINE) {
5630 costs = inline_method (cfg, stfld_wrapper, mono_method_signature (stfld_wrapper), bblock,
5631 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
5632 g_assert (costs > 0);
5637 GET_BBLOCK (cfg, bbhash, bblock, ip);
5638 ebblock->next_bb = bblock;
5639 link_bblock (cfg, ebblock, bblock);
5641 /* indicates start of a new block, and triggers a load
5642 of all stack arguments at bb boundarie */
5645 inline_costs += costs;
5648 mono_emit_method_call_spilled (cfg, bblock, stfld_wrapper, mono_method_signature (stfld_wrapper), iargs, ip, NULL);
5652 NEW_ICONST (cfg, offset_ins, foffset);
5653 MONO_INST_NEW (cfg, ins, OP_PADD);
5655 ins->inst_left = *sp;
5656 ins->inst_right = offset_ins;
5657 ins->type = STACK_MP;
5659 MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
5660 store->cil_code = ip;
5661 store->inst_left = ins;
5662 store->inst_right = sp [1];
5663 handle_loaded_temps (cfg, bblock, stack_start, sp);
5664 store->flags |= ins_flag;
5666 if (store->opcode == CEE_STOBJ) {
5667 handle_stobj (cfg, bblock, ins, sp [1], ip,
5668 mono_class_from_mono_type (field->type), FALSE, FALSE);
5670 MONO_ADD_INS (bblock, store);
5673 if ((klass->marshalbyref && !MONO_CHECK_THIS (sp [0])) || klass->contextbound || klass == mono_defaults.marshalbyrefobject_class) {
5674 MonoMethod *wrapper = (*ip == CEE_LDFLDA) ? mono_marshal_get_ldflda_wrapper (field->type) : mono_marshal_get_ldfld_wrapper (field->type);
5675 MonoInst *iargs [4];
5679 NEW_CLASSCONST (cfg, iargs [1], klass);
5680 NEW_FIELDCONST (cfg, iargs [2], field);
5681 NEW_ICONST (cfg, iargs [3], klass->valuetype ? field->offset - sizeof (MonoObject) : field->offset);
5682 if ((cfg->opt & MONO_OPT_INLINE) && !MONO_TYPE_ISSTRUCT (mono_method_signature (wrapper)->ret)) {
5683 costs = inline_method (cfg, wrapper, mono_method_signature (wrapper), bblock,
5684 iargs, ip, real_offset, dont_inline, &ebblock, TRUE);
5685 g_assert (costs > 0);
5690 GET_BBLOCK (cfg, bbhash, bblock, ip);
5691 ebblock->next_bb = bblock;
5692 link_bblock (cfg, ebblock, bblock);
5694 temp = iargs [0]->inst_i0->inst_c0;
5696 NEW_TEMPLOAD (cfg, *sp, temp);
5699 /* indicates start of a new block, and triggers a load of
5700 all stack arguments at bb boundarie */
5703 inline_costs += costs;
5706 temp = mono_emit_method_call_spilled (cfg, bblock, wrapper, mono_method_signature (wrapper), iargs, ip, NULL);
5707 NEW_TEMPLOAD (cfg, *sp, temp);
5711 NEW_ICONST (cfg, offset_ins, foffset);
5712 MONO_INST_NEW (cfg, ins, OP_PADD);
5714 ins->inst_left = *sp;
5715 ins->inst_right = offset_ins;
5716 ins->type = STACK_MP;
5718 if (*ip == CEE_LDFLDA) {
5722 MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
5723 type_to_eval_stack_type (field->type, load);
5724 load->cil_code = ip;
5725 load->inst_left = ins;
5726 load->flags |= ins_flag;
5738 MonoClassField *field;
5739 gpointer addr = NULL;
5742 token = read32 (ip + 1);
5743 if (method->wrapper_type != MONO_WRAPPER_NONE) {
5744 field = mono_method_get_wrapper_data (method, token);
5745 klass = field->parent;
5748 field = mono_field_from_token (image, token, &klass, generic_context);
5751 mono_class_init (klass);
5753 g_assert (!(field->type->attrs & FIELD_ATTRIBUTE_LITERAL));
5755 if ((*ip) == CEE_STSFLD)
5756 handle_loaded_temps (cfg, bblock, stack_start, sp);
5758 /* The special_static_fields field is init'd in mono_class_vtable, so it needs
5759 * to be called here.
5761 if (!(cfg->opt & MONO_OPT_SHARED))
5762 mono_class_vtable (cfg->domain, klass);
5763 mono_domain_lock (cfg->domain);
5764 if (cfg->domain->special_static_fields)
5765 addr = g_hash_table_lookup (cfg->domain->special_static_fields, field);
5766 mono_domain_unlock (cfg->domain);
5768 if ((cfg->opt & MONO_OPT_SHARED) || (cfg->compile_aot && addr)) {
5770 MonoInst *iargs [2];
5771 MonoInst *domain_var;
5773 g_assert (field->parent);
5774 /* avoid depending on undefined C behavior in sequence points */
5775 domain_var = mono_get_domainvar (cfg);
5776 NEW_TEMPLOAD (cfg, iargs [0], domain_var->inst_c0);
5777 NEW_FIELDCONST (cfg, iargs [1], field);
5778 temp = mono_emit_jit_icall (cfg, bblock, mono_class_static_field_address, iargs, ip);
5779 NEW_TEMPLOAD (cfg, ins, temp);
5782 vtable = mono_class_vtable (cfg->domain, klass);
5784 if (mini_field_access_needs_cctor_run (cfg, method, vtable) && !(g_slist_find (class_inits, vtable))) {
5785 guint8 *tramp = mono_create_class_init_trampoline (vtable);
5786 mono_emit_native_call (cfg, bblock, tramp,
5787 helper_sig_class_init_trampoline,
5788 NULL, ip, FALSE, FALSE);
5789 if (cfg->verbose_level > 2)
5790 g_print ("class %s.%s needs init call for %s\n", klass->name_space, klass->name, field->name);
5791 class_inits = g_slist_prepend (class_inits, vtable);
5793 if (cfg->run_cctors)
5794 mono_runtime_class_init (vtable);
5796 addr = (char*)vtable->data + field->offset;
5798 if (cfg->compile_aot)
5799 NEW_SFLDACONST (cfg, ins, field);
5801 NEW_PCONST (cfg, ins, addr);
5805 * insert call to mono_threads_get_static_data (GPOINTER_TO_UINT (addr))
5806 * This could be later optimized to do just a couple of
5807 * memory dereferences with constant offsets.
5810 MonoInst *iargs [1];
5811 NEW_ICONST (cfg, iargs [0], GPOINTER_TO_UINT (addr));
5812 temp = mono_emit_jit_icall (cfg, bblock, mono_get_special_static_data, iargs, ip);
5813 NEW_TEMPLOAD (cfg, ins, temp);
5817 /* FIXME: mark instructions for use in SSA */
5818 if (*ip == CEE_LDSFLDA) {
5820 } else if (*ip == CEE_STSFLD) {
5824 MONO_INST_NEW (cfg, store, mono_type_to_stind (field->type));
5825 store->cil_code = ip;
5826 store->inst_left = ins;
5827 store->inst_right = sp [0];
5828 store->flags |= ins_flag;
5831 if (store->opcode == CEE_STOBJ) {
5832 handle_stobj (cfg, bblock, ins, sp [0], ip, mono_class_from_mono_type (field->type), FALSE, FALSE);
5834 MONO_ADD_INS (bblock, store);
5836 gboolean is_const = FALSE;
5837 MonoVTable *vtable = mono_class_vtable (cfg->domain, klass);
5838 if (!((cfg->opt & MONO_OPT_SHARED) || cfg->compile_aot) &&
5839 vtable->initialized && (field->type->attrs & FIELD_ATTRIBUTE_INIT_ONLY)) {
5840 gpointer addr = (char*)vtable->data + field->offset;
5841 int ro_type = field->type->type;
5842 if (ro_type == MONO_TYPE_VALUETYPE && field->type->data.klass->enumtype) {
5843 ro_type = field->type->data.klass->enum_basetype->type;
5845 /* g_print ("RO-FIELD %s.%s:%s\n", klass->name_space, klass->name, field->name);*/
5848 case MONO_TYPE_BOOLEAN:
5850 NEW_ICONST (cfg, *sp, *((guint8 *)addr));
5854 NEW_ICONST (cfg, *sp, *((gint8 *)addr));
5857 case MONO_TYPE_CHAR:
5859 NEW_ICONST (cfg, *sp, *((guint16 *)addr));
5863 NEW_ICONST (cfg, *sp, *((gint16 *)addr));
5868 NEW_ICONST (cfg, *sp, *((gint32 *)addr));
5872 NEW_ICONST (cfg, *sp, *((guint32 *)addr));
5877 case MONO_TYPE_STRING:
5878 case MONO_TYPE_OBJECT:
5879 case MONO_TYPE_CLASS:
5880 case MONO_TYPE_SZARRAY:
5882 case MONO_TYPE_FNPTR:
5883 case MONO_TYPE_ARRAY:
5884 NEW_PCONST (cfg, *sp, *((gpointer *)addr));
5885 type_to_eval_stack_type (field->type, *sp);
5890 MONO_INST_NEW (cfg, *sp, OP_I8CONST);
5891 sp [0]->type = STACK_I8;
5892 sp [0]->inst_l = *((gint64 *)addr);
5897 case MONO_TYPE_VALUETYPE:
5906 CHECK_STACK_OVF (1);
5907 MONO_INST_NEW (cfg, load, mono_type_to_ldind (field->type));
5908 type_to_eval_stack_type (field->type, load);
5909 load->cil_code = ip;
5910 load->inst_left = ins;
5912 load->flags |= ins_flag;
5914 /* fixme: dont see the problem why this does not work */
5915 //cfg->disable_aot = TRUE;
5925 token = read32 (ip + 1);
5926 klass = mini_get_class (method, token, generic_context);
5929 n = mono_type_to_stind (&klass->byval_arg);
5930 if (n == CEE_STOBJ) {
5931 handle_stobj (cfg, bblock, sp [0], sp [1], ip, klass, FALSE, FALSE);
5933 /* FIXME: should check item at sp [1] is compatible with the type of the store. */
5935 MONO_INST_NEW (cfg, store, n);
5936 store->cil_code = ip;
5937 store->inst_left = sp [0];
5938 store->inst_right = sp [1];
5939 store->flags |= ins_flag;
5940 MONO_ADD_INS (bblock, store);
5952 token = read32 (ip + 1);
5953 klass = mini_get_class (method, token, generic_context);
5957 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
5962 if (klass == mono_defaults.void_class)
5964 if (target_type_is_incompatible (cfg, &klass->byval_arg, *sp))
5966 /* frequent check in generic code: box (struct), brtrue */
5967 if (ip + 5 < end && ip_in_bb (cfg, bblock, ip + 5) && (ip [5] == CEE_BRTRUE || ip [5] == CEE_BRTRUE_S)) {
5968 /*g_print ("box-brtrue opt at 0x%04x in %s\n", real_offset, method->name);*/
5969 MONO_INST_NEW (cfg, ins, CEE_POP);
5970 MONO_ADD_INS (bblock, ins);
5974 MONO_INST_NEW (cfg, ins, CEE_BR);
5976 MONO_ADD_INS (bblock, ins);
5977 if (*ip == CEE_BRTRUE_S) {
5980 target = ip + 1 + (signed char)(*ip);
5985 target = ip + 4 + (gint)(read32 (ip));
5988 GET_BBLOCK (cfg, bbhash, tblock, target);
5989 link_bblock (cfg, bblock, tblock);
5990 CHECK_BBLOCK (target, ip, tblock);
5991 ins->inst_target_bb = tblock;
5992 if (sp != stack_start) {
5993 handle_stack_args (cfg, bblock, stack_start, sp - stack_start);
5996 start_new_bblock = 1;
5999 *sp++ = handle_box (cfg, bblock, val, ip, klass);
6006 MONO_INST_NEW (cfg, ins, *ip);
6011 token = read32 (ip + 1);
6013 /* allocate the domainvar - becaus this is used in decompose_foreach */
6014 if (cfg->opt & MONO_OPT_SHARED) {
6015 mono_get_domainvar (cfg);
6016 /* LAME-IR: Mark it as used since otherwise it will be optimized away */
6017 cfg->domainvar->flags |= MONO_INST_VOLATILE;
6021 mono_get_got_var (cfg);
6023 klass = mini_get_class (method, token, generic_context);
6026 ins->inst_newa_class = klass;
6027 ins->inst_newa_len = *sp;
6028 ins->type = STACK_OBJ;
6032 * we store the object so calls to create the array are not interleaved
6033 * with the arguments of other calls.
6036 MonoInst *store, *temp, *load;
6038 temp = mono_compile_create_var (cfg, type_from_stack_type (ins), OP_LOCAL);
6039 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
6040 store->cil_code = ins->cil_code;
6041 MONO_ADD_INS (bblock, store);
6042 NEW_TEMPLOAD (cfg, load, temp->inst_c0);
6043 load->cil_code = ins->cil_code;
6051 if (sp [0]->type != STACK_OBJ)
6053 MONO_INST_NEW (cfg, ins, *ip);
6054 ins->cil_code = ip++;
6055 ins->inst_left = *sp;
6056 ins->type = STACK_PTR;
6063 if (sp [0]->type != STACK_OBJ)
6066 klass = mini_get_class (method, read32 (ip + 1), generic_context);
6069 /* we need to make sure that this array is exactly the type it needs
6070 * to be for correctness. the wrappers are lax with their usage
6071 * so we need to ignore them here
6073 if (!klass->valuetype && method->wrapper_type == MONO_WRAPPER_NONE) {
6075 MONO_INST_NEW (cfg, check, OP_CHECK_ARRAY_TYPE);
6076 check->cil_code = ip;
6077 check->klass = klass;
6078 check->inst_left = sp [0];
6079 check->type = STACK_OBJ;
6083 mono_class_init (klass);
6084 NEW_LDELEMA (cfg, ins, sp, klass);
6089 case CEE_LDELEM_ANY: {
6093 if (sp [0]->type != STACK_OBJ)
6096 token = read32 (ip + 1);
6097 klass = mono_class_get_full (image, token, generic_context);
6100 mono_class_init (klass);
6101 NEW_LDELEMA (cfg, load, sp, klass);
6102 load->cil_code = ip;
6103 MONO_INST_NEW (cfg, ins, mono_type_to_ldind (&klass->byval_arg));
6105 ins->inst_left = load;
6107 type_to_eval_stack_type (&klass->byval_arg, ins);
6121 case CEE_LDELEM_REF: {
6125 * ldind.x (ldelema (array, index))
6126 * ldelema does the bounds check
6130 if (sp [0]->type != STACK_OBJ)
6132 klass = array_access_to_klass (*ip);
6133 NEW_LDELEMA (cfg, load, sp, klass);
6134 load->cil_code = ip;
6135 MONO_INST_NEW (cfg, ins, ldelem_to_ldind [*ip - CEE_LDELEM_I1]);
6137 ins->inst_left = load;
6139 ins->type = ldind_type [ins->opcode - CEE_LDIND_I1];
6149 case CEE_STELEM_R8: {
6153 * stind.x (ldelema (array, index), val)
6154 * ldelema does the bounds check
6158 if (sp [0]->type != STACK_OBJ)
6160 klass = array_access_to_klass (*ip);
6161 NEW_LDELEMA (cfg, load, sp, klass);
6162 load->cil_code = ip;
6163 MONO_INST_NEW (cfg, ins, stelem_to_stind [*ip - CEE_STELEM_I]);
6165 ins->inst_left = load;
6166 ins->inst_right = sp [2];
6168 handle_loaded_temps (cfg, bblock, stack_start, sp);
6169 MONO_ADD_INS (bblock, ins);
6173 case CEE_STELEM_ANY: {
6177 * stind.x (ldelema (array, index), val)
6178 * ldelema does the bounds check
6182 if (sp [0]->type != STACK_OBJ)
6185 token = read32 (ip + 1);
6186 klass = mono_class_get_full (image, token, generic_context);
6189 mono_class_init (klass);
6190 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
6191 MonoMethod* helper = mono_marshal_get_stelemref ();
6192 MonoInst *iargs [3];
6193 handle_loaded_temps (cfg, bblock, stack_start, sp);
6199 mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
6201 NEW_LDELEMA (cfg, load, sp, klass);
6202 load->cil_code = ip;
6204 n = mono_type_to_stind (&klass->byval_arg);
6206 handle_stobj (cfg, bblock, load, sp [2], ip, klass, FALSE, FALSE);
6208 MONO_INST_NEW (cfg, ins, n);
6210 ins->inst_left = load;
6211 ins->inst_right = sp [2];
6212 handle_loaded_temps (cfg, bblock, stack_start, sp);
6213 MONO_ADD_INS (bblock, ins);
6220 case CEE_STELEM_REF: {
6221 MonoInst *iargs [3];
6222 MonoMethod* helper = mono_marshal_get_stelemref ();
6226 if (sp [0]->type != STACK_OBJ)
6228 if (sp [2]->type != STACK_OBJ)
6231 handle_loaded_temps (cfg, bblock, stack_start, sp);
6237 mono_emit_method_call_spilled (cfg, bblock, helper, mono_method_signature (helper), iargs, ip, NULL);
6241 NEW_GROUP (cfg, group, sp [0], sp [1]);
6242 MONO_INST_NEW (cfg, ins, CEE_STELEM_REF);
6244 ins->inst_left = group;
6245 ins->inst_right = sp [2];
6246 MONO_ADD_INS (bblock, ins);
6253 case CEE_CKFINITE: {
6254 MonoInst *store, *temp;
6257 /* this instr. can throw exceptions as side effect,
6258 * so we cant eliminate dead code which contains CKFINITE opdodes.
6259 * Spilling to memory makes sure that we always perform
6263 MONO_INST_NEW (cfg, ins, CEE_CKFINITE);
6265 ins->inst_left = sp [-1];
6266 temp = mono_compile_create_var (cfg, &mono_defaults.double_class->byval_arg, OP_LOCAL);
6268 NEW_TEMPSTORE (cfg, store, temp->inst_c0, ins);
6269 store->cil_code = ip;
6270 MONO_ADD_INS (bblock, store);
6272 NEW_TEMPLOAD (cfg, sp [-1], temp->inst_c0);
6279 MONO_INST_NEW (cfg, ins, *ip);
6282 klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
6285 mono_class_init (klass);
6286 ins->type = STACK_MP;
6287 ins->inst_left = *sp;
6289 ins->inst_newa_class = klass;
6294 case CEE_MKREFANY: {
6295 MonoInst *loc, *klassconst;
6298 MONO_INST_NEW (cfg, ins, *ip);
6301 klass = mono_class_get_full (image, read32 (ip + 1), generic_context);
6304 mono_class_init (klass);
6307 loc = mono_compile_create_var (cfg, &mono_defaults.typed_reference_class->byval_arg, OP_LOCAL);
6308 NEW_TEMPLOADA (cfg, ins->inst_right, loc->inst_c0);
6310 NEW_PCONST (cfg, klassconst, klass);
6311 NEW_GROUP (cfg, ins->inst_left, *sp, klassconst);
6313 MONO_ADD_INS (bblock, ins);
6315 NEW_TEMPLOAD (cfg, *sp, loc->inst_c0);
6322 MonoClass *handle_class;
6324 CHECK_STACK_OVF (1);
6327 n = read32 (ip + 1);
6329 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
6330 handle = mono_method_get_wrapper_data (method, n);
6331 handle_class = mono_method_get_wrapper_data (method, n + 1);
6332 if (handle_class == mono_defaults.typehandle_class)
6333 handle = &((MonoClass*)handle)->byval_arg;
6336 handle = mono_ldtoken (image, n, &handle_class, generic_context);
6340 mono_class_init (handle_class);
6342 if (cfg->opt & MONO_OPT_SHARED) {
6344 MonoInst *res, *store, *addr, *vtvar, *iargs [3];
6346 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
6348 NEW_IMAGECONST (cfg, iargs [0], image);
6349 NEW_ICONST (cfg, iargs [1], n);
6350 NEW_PCONST (cfg, iargs [2], generic_context);
6351 temp = mono_emit_jit_icall (cfg, bblock, mono_ldtoken_wrapper, iargs, ip);
6352 NEW_TEMPLOAD (cfg, res, temp);
6353 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
6354 NEW_INDSTORE (cfg, store, addr, res, &mono_defaults.int_class->byval_arg);
6355 MONO_ADD_INS (bblock, store);
6356 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
6358 if ((ip [5] == CEE_CALL) && (cmethod = mini_get_method (method, read32 (ip + 6), NULL, generic_context)) &&
6359 (cmethod->klass == mono_defaults.monotype_class->parent) &&
6360 (strcmp (cmethod->name, "GetTypeFromHandle") == 0) && ip_in_bb (cfg, bblock, ip + 5)) {
6361 MonoClass *tclass = mono_class_from_mono_type (handle);
6362 mono_class_init (tclass);
6363 if (cfg->compile_aot)
6364 NEW_TYPE_FROM_HANDLE_CONST (cfg, ins, image, n);
6366 NEW_PCONST (cfg, ins, mono_type_get_object (cfg->domain, handle));
6367 ins->type = STACK_OBJ;
6368 ins->klass = cmethod->klass;
6371 MonoInst *store, *addr, *vtvar;
6373 if (cfg->compile_aot)
6374 NEW_LDTOKENCONST (cfg, ins, image, n);
6376 NEW_PCONST (cfg, ins, handle);
6377 vtvar = mono_compile_create_var (cfg, &handle_class->byval_arg, OP_LOCAL);
6378 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
6379 NEW_INDSTORE (cfg, store, addr, ins, &mono_defaults.int_class->byval_arg);
6380 MONO_ADD_INS (bblock, store);
6381 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
6397 case CEE_ADD_OVF_UN:
6399 case CEE_MUL_OVF_UN:
6401 case CEE_SUB_OVF_UN:
6404 if (mono_find_jit_opcode_emulation (ins->opcode)) {
6406 *sp++ = emit_tree (cfg, bblock, ins, ip + 1);
6407 mono_get_got_var (cfg);
6411 case CEE_ENDFINALLY:
6412 MONO_INST_NEW (cfg, ins, *ip);
6413 MONO_ADD_INS (bblock, ins);
6414 ins->cil_code = ip++;
6415 start_new_bblock = 1;
6418 * Control will leave the method so empty the stack, otherwise
6419 * the next basic block will start with a nonempty stack.
6421 while (sp != stack_start) {
6422 MONO_INST_NEW (cfg, ins, CEE_POP);
6426 MONO_ADD_INS (bblock, ins);
6433 if (*ip == CEE_LEAVE) {
6435 target = ip + 5 + (gint32)read32(ip + 1);
6438 target = ip + 2 + (signed char)(ip [1]);
6441 /* empty the stack */
6442 while (sp != stack_start) {
6443 MONO_INST_NEW (cfg, ins, CEE_POP);
6447 MONO_ADD_INS (bblock, ins);
6451 * If this leave statement is in a catch block, check for a
6452 * pending exception, and rethrow it if necessary.
6454 for (i = 0; i < header->num_clauses; ++i) {
6455 MonoExceptionClause *clause = &header->clauses [i];
6457 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)) {
6461 NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, clause->handler_offset)->inst_c0);
6462 load->cil_code = ip;
6464 temp = mono_emit_jit_icall (cfg, bblock, mono_thread_get_pending_exception, NULL, ip);
6465 NEW_TEMPLOAD (cfg, *sp, temp);
6467 MONO_INST_NEW (cfg, ins, OP_THROW_OR_NULL);
6468 ins->inst_left = *sp;
6469 ins->inst_right = load;
6471 MONO_ADD_INS (bblock, ins);
6475 /* fixme: call fault handler ? */
6477 if ((handlers = mono_find_final_block (cfg, ip, target, MONO_EXCEPTION_CLAUSE_FINALLY))) {
6479 for (tmp = handlers; tmp; tmp = tmp->next) {
6481 link_bblock (cfg, bblock, tblock);
6482 MONO_INST_NEW (cfg, ins, OP_CALL_HANDLER);
6484 ins->inst_target_bb = tblock;
6485 MONO_ADD_INS (bblock, ins);
6487 g_list_free (handlers);
6490 MONO_INST_NEW (cfg, ins, CEE_BR);
6492 MONO_ADD_INS (bblock, ins);
6493 GET_BBLOCK (cfg, bbhash, tblock, target);
6494 link_bblock (cfg, bblock, tblock);
6495 CHECK_BBLOCK (target, ip, tblock);
6496 ins->inst_target_bb = tblock;
6497 start_new_bblock = 1;
6499 if (*ip == CEE_LEAVE)
6508 MONO_INST_NEW (cfg, ins, *ip);
6510 handle_loaded_temps (cfg, bblock, stack_start, sp);
6511 MONO_ADD_INS (bblock, ins);
6512 ins->cil_code = ip++;
6513 ins->inst_i0 = sp [0];
6514 ins->inst_i1 = sp [1];
6522 /* trampoline mono specific opcodes */
6523 case MONO_CUSTOM_PREFIX: {
6525 g_assert (method->wrapper_type != MONO_WRAPPER_NONE);
6530 case CEE_MONO_ICALL: {
6533 MonoJitICallInfo *info;
6535 token = read32 (ip + 2);
6536 func = mono_method_get_wrapper_data (method, token);
6537 info = mono_find_jit_icall_by_addr (func);
6540 CHECK_STACK (info->sig->param_count);
6541 sp -= info->sig->param_count;
6543 temp = mono_emit_jit_icall (cfg, bblock, info->func, sp, ip);
6544 if (!MONO_TYPE_IS_VOID (info->sig->ret)) {
6545 NEW_TEMPLOAD (cfg, *sp, temp);
6550 inline_costs += 10 * num_calls++;
6554 case CEE_MONO_LDPTR:
6555 CHECK_STACK_OVF (1);
6557 token = read32 (ip + 2);
6558 NEW_PCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
6562 inline_costs += 10 * num_calls++;
6563 /* Can't embed random pointers into AOT code */
6564 cfg->disable_aot = 1;
6566 case CEE_MONO_VTADDR:
6569 MONO_INST_NEW (cfg, ins, OP_VTADDR);
6571 ins->type = STACK_MP;
6572 ins->inst_left = *sp;
6576 case CEE_MONO_NEWOBJ: {
6577 MonoInst *iargs [2];
6579 CHECK_STACK_OVF (1);
6581 token = read32 (ip + 2);
6582 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
6583 mono_class_init (klass);
6584 NEW_DOMAINCONST (cfg, iargs [0]);
6585 NEW_CLASSCONST (cfg, iargs [1], klass);
6586 temp = mono_emit_jit_icall (cfg, bblock, mono_object_new, iargs, ip);
6587 NEW_TEMPLOAD (cfg, *sp, temp);
6590 inline_costs += 10 * num_calls++;
6593 case CEE_MONO_OBJADDR:
6596 MONO_INST_NEW (cfg, ins, OP_OBJADDR);
6598 ins->type = STACK_MP;
6599 ins->inst_left = *sp;
6603 case CEE_MONO_LDNATIVEOBJ:
6606 token = read32 (ip + 2);
6607 klass = mono_method_get_wrapper_data (method, token);
6608 g_assert (klass->valuetype);
6609 mono_class_init (klass);
6610 NEW_INDLOAD (cfg, ins, sp [-1], &klass->byval_arg);
6614 case CEE_MONO_RETOBJ:
6615 g_assert (cfg->ret);
6616 g_assert (mono_method_signature (method)->pinvoke);
6621 token = read32 (ip + 2);
6622 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
6624 NEW_RETLOADA (cfg, ins);
6625 handle_stobj (cfg, bblock, ins, *sp, ip, klass, FALSE, TRUE);
6627 if (sp != stack_start)
6630 MONO_INST_NEW (cfg, ins, CEE_BR);
6632 ins->inst_target_bb = end_bblock;
6633 MONO_ADD_INS (bblock, ins);
6634 link_bblock (cfg, bblock, end_bblock);
6635 start_new_bblock = 1;
6638 case CEE_MONO_CISINST:
6639 case CEE_MONO_CCASTCLASS: {
6644 token = read32 (ip + 2);
6645 klass = (MonoClass *)mono_method_get_wrapper_data (method, token);
6646 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_CISINST) ? OP_CISINST : OP_CCASTCLASS);
6647 ins->type = STACK_I4;
6648 ins->inst_left = *sp;
6649 ins->inst_newa_class = klass;
6651 *sp++ = emit_tree (cfg, bblock, ins, ip + 6);
6655 case CEE_MONO_SAVE_LMF:
6656 case CEE_MONO_RESTORE_LMF:
6657 #ifdef MONO_ARCH_HAVE_LMF_OPS
6658 MONO_INST_NEW (cfg, ins, (ip [1] == CEE_MONO_SAVE_LMF) ? OP_SAVE_LMF : OP_RESTORE_LMF);
6659 MONO_ADD_INS (bblock, ins);
6660 cfg->need_lmf_area = TRUE;
6664 case CEE_MONO_CLASSCONST:
6665 CHECK_STACK_OVF (1);
6667 token = read32 (ip + 2);
6668 NEW_CLASSCONST (cfg, ins, mono_method_get_wrapper_data (method, token));
6672 inline_costs += 10 * num_calls++;
6674 case CEE_MONO_NOT_TAKEN:
6675 bblock->out_of_line = TRUE;
6679 g_error ("opcode 0x%02x 0x%02x not handled", MONO_CUSTOM_PREFIX, ip [1]);
6688 /* somewhat similar to LDTOKEN */
6689 MonoInst *addr, *vtvar;
6690 CHECK_STACK_OVF (1);
6691 vtvar = mono_compile_create_var (cfg, &mono_defaults.argumenthandle_class->byval_arg, OP_LOCAL);
6693 NEW_TEMPLOADA (cfg, addr, vtvar->inst_c0);
6694 addr->cil_code = ip;
6695 MONO_INST_NEW (cfg, ins, OP_ARGLIST);
6697 ins->inst_left = addr;
6698 MONO_ADD_INS (bblock, ins);
6699 NEW_TEMPLOAD (cfg, ins, vtvar->inst_c0);
6713 * The following transforms:
6714 * CEE_CEQ into OP_CEQ
6715 * CEE_CGT into OP_CGT
6716 * CEE_CGT_UN into OP_CGT_UN
6717 * CEE_CLT into OP_CLT
6718 * CEE_CLT_UN into OP_CLT_UN
6720 MONO_INST_NEW (cfg, cmp, 256 + ip [1]);
6722 MONO_INST_NEW (cfg, ins, cmp->opcode);
6724 cmp->inst_i0 = sp [0];
6725 cmp->inst_i1 = sp [1];
6729 if ((sp [0]->type == STACK_I8) || ((sizeof (gpointer) == 8) && ((sp [0]->type == STACK_PTR) || (sp [0]->type == STACK_OBJ) || (sp [0]->type == STACK_MP))))
6730 cmp->opcode = OP_LCOMPARE;
6732 cmp->opcode = OP_COMPARE;
6734 ins->type = STACK_I4;
6737 /* spill it to reduce the expression complexity
6738 * and workaround bug 54209
6740 if (cmp->inst_left->type == STACK_I8) {
6742 *sp++ = emit_tree (cfg, bblock, ins, ip + 2);
6751 CHECK_STACK_OVF (1);
6753 n = read32 (ip + 2);
6754 cmethod = mini_get_method (method, n, NULL, generic_context);
6757 mono_class_init (cmethod->klass);
6759 if (mono_use_security_manager) {
6760 check_linkdemand (cfg, method, cmethod, bblock, ip);
6763 handle_loaded_temps (cfg, bblock, stack_start, sp);
6765 NEW_METHODCONST (cfg, argconst, cmethod);
6766 if (method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
6767 temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn, &argconst, ip);
6769 temp = mono_emit_jit_icall (cfg, bblock, mono_ldftn_nosync, &argconst, ip);
6770 NEW_TEMPLOAD (cfg, *sp, temp);
6774 inline_costs += 10 * num_calls++;
6777 case CEE_LDVIRTFTN: {
6783 n = read32 (ip + 2);
6784 cmethod = mini_get_method (method, n, NULL, generic_context);
6787 mono_class_init (cmethod->klass);
6789 if (mono_use_security_manager) {
6790 check_linkdemand (cfg, method, cmethod, bblock, ip);
6793 handle_loaded_temps (cfg, bblock, stack_start, sp);
6797 NEW_METHODCONST (cfg, args [1], cmethod);
6798 temp = mono_emit_jit_icall (cfg, bblock, mono_ldvirtfn, args, ip);
6799 NEW_TEMPLOAD (cfg, *sp, temp);
6803 inline_costs += 10 * num_calls++;
6807 CHECK_STACK_OVF (1);
6809 n = read16 (ip + 2);
6811 NEW_ARGLOAD (cfg, ins, n);
6817 CHECK_STACK_OVF (1);
6819 n = read16 (ip + 2);
6821 NEW_ARGLOADA (cfg, ins, n);
6829 handle_loaded_temps (cfg, bblock, stack_start, sp);
6831 n = read16 (ip + 2);
6833 NEW_ARGSTORE (cfg, ins, n, *sp);
6835 if (!dont_verify_stloc && target_type_is_incompatible (cfg, param_types [n], *sp))
6837 if (ins->opcode == CEE_STOBJ) {
6838 NEW_ARGLOADA (cfg, ins, n);
6839 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
6841 MONO_ADD_INS (bblock, ins);
6845 CHECK_STACK_OVF (1);
6847 n = read16 (ip + 2);
6849 NEW_LOCLOAD (cfg, ins, n);
6855 CHECK_STACK_OVF (1);
6857 n = read16 (ip + 2);
6859 NEW_LOCLOADA (cfg, ins, n);
6868 n = read16 (ip + 2);
6870 handle_loaded_temps (cfg, bblock, stack_start, sp);
6871 NEW_LOCSTORE (cfg, ins, n, *sp);
6872 if (!dont_verify_stloc && target_type_is_incompatible (cfg, header->locals [n], *sp))
6875 if (ins->opcode == CEE_STOBJ) {
6876 NEW_LOCLOADA (cfg, ins, n);
6877 handle_stobj (cfg, bblock, ins, *sp, ip, ins->klass, FALSE, FALSE);
6879 MONO_ADD_INS (bblock, ins);
6886 if (sp != stack_start)
6888 if (cfg->method != method)
6890 * Inlining this into a loop in a parent could lead to
6891 * stack overflows which is different behavior than the
6892 * non-inlined case, thus disable inlining in this case.
6894 goto inline_failure;
6895 MONO_INST_NEW (cfg, ins, OP_LOCALLOC);
6896 ins->inst_left = *sp;
6898 ins->type = STACK_PTR;
6900 cfg->flags |= MONO_CFG_HAS_ALLOCA;
6901 if (header->init_locals)
6902 ins->flags |= MONO_INST_INIT;
6906 /* FIXME: set init flag if locals init is set in this method */
6908 case CEE_ENDFILTER: {
6909 MonoExceptionClause *clause, *nearest;
6910 int cc, nearest_num;
6914 if ((sp != stack_start) || (sp [0]->type != STACK_I4))
6916 MONO_INST_NEW (cfg, ins, OP_ENDFILTER);
6917 ins->inst_left = *sp;
6919 MONO_ADD_INS (bblock, ins);
6920 start_new_bblock = 1;
6925 for (cc = 0; cc < header->num_clauses; ++cc) {
6926 clause = &header->clauses [cc];
6927 if ((clause->flags & MONO_EXCEPTION_CLAUSE_FILTER) &&
6928 ((ip - header->code) > clause->data.filter_offset && (ip - header->code) <= clause->handler_offset) &&
6929 (!nearest || (clause->data.filter_offset < nearest->data.filter_offset))) {
6935 if ((ip - header->code) != nearest->handler_offset)
6940 case CEE_UNALIGNED_:
6941 ins_flag |= MONO_INST_UNALIGNED;
6942 /* FIXME: record alignment? we can assume 1 for now */
6947 ins_flag |= MONO_INST_VOLATILE;
6951 ins_flag |= MONO_INST_TAILCALL;
6952 cfg->flags |= MONO_CFG_HAS_TAIL;
6953 /* Can't inline tail calls at this time */
6954 inline_costs += 100000;
6961 token = read32 (ip + 2);
6962 klass = mini_get_class (method, token, generic_context);
6965 if (MONO_TYPE_IS_REFERENCE (&klass->byval_arg)) {
6966 MonoInst *store, *load;
6967 NEW_PCONST (cfg, load, NULL);
6968 load->cil_code = ip;
6969 load->type = STACK_OBJ;
6970 MONO_INST_NEW (cfg, store, CEE_STIND_REF);
6971 store->cil_code = ip;
6972 handle_loaded_temps (cfg, bblock, stack_start, sp);
6973 MONO_ADD_INS (bblock, store);
6974 store->inst_i0 = sp [0];
6975 store->inst_i1 = load;
6977 handle_initobj (cfg, bblock, *sp, NULL, klass, stack_start, sp);
6982 case CEE_CONSTRAINED_:
6983 /* FIXME: implement */
6985 token = read32 (ip + 2);
6986 constrained_call = mono_class_get_full (image, token, generic_context);
6987 if (!constrained_call)
6993 MonoInst *iargs [3];
6996 if ((cfg->opt & MONO_OPT_INTRINS) && (ip [1] == CEE_CPBLK) && (sp [2]->opcode == OP_ICONST) && ((n = sp [2]->inst_c0) <= sizeof (gpointer) * 5)) {
6998 MONO_INST_NEW (cfg, copy, OP_MEMCPY);
6999 copy->inst_left = sp [0];
7000 copy->inst_right = sp [1];
7001 copy->cil_code = ip;
7003 MONO_ADD_INS (bblock, copy);
7010 handle_loaded_temps (cfg, bblock, stack_start, sp);
7011 if (ip [1] == CEE_CPBLK) {
7012 MonoMethod *memcpy_method = get_memcpy_method ();
7013 mono_emit_method_call_spilled (cfg, bblock, memcpy_method, memcpy_method->signature, iargs, ip, NULL);
7015 MonoMethod *memset_method = get_memset_method ();
7016 mono_emit_method_call_spilled (cfg, bblock, memset_method, memset_method->signature, iargs, ip, NULL);
7025 ins_flag |= MONO_INST_NOTYPECHECK;
7027 ins_flag |= MONO_INST_NORANGECHECK;
7028 /* we ignore the no-nullcheck for now since we
7029 * really do it explicitly only when doing callvirt->call
7035 int handler_offset = -1;
7037 for (i = 0; i < header->num_clauses; ++i) {
7038 MonoExceptionClause *clause = &header->clauses [i];
7039 if (MONO_OFFSET_IN_HANDLER (clause, ip - header->code) && !(clause->flags & MONO_EXCEPTION_CLAUSE_FINALLY))
7040 handler_offset = clause->handler_offset;
7043 bblock->flags |= BB_EXCEPTION_UNSAFE;
7045 g_assert (handler_offset != -1);
7047 NEW_TEMPLOAD (cfg, load, mono_find_exvar_for_offset (cfg, handler_offset)->inst_c0);
7048 load->cil_code = ip;
7049 MONO_INST_NEW (cfg, ins, OP_RETHROW);
7050 ins->inst_left = load;
7052 MONO_ADD_INS (bblock, ins);
7054 link_bblock (cfg, bblock, end_bblock);
7055 start_new_bblock = 1;
7057 mono_get_got_var (cfg);
7061 CHECK_STACK_OVF (1);
7063 token = read32 (ip + 2);
7064 /* FIXXME: handle generics. */
7065 if (mono_metadata_token_table (token) == MONO_TABLE_TYPESPEC) {
7066 MonoType *type = mono_type_create_from_typespec (image, token);
7067 token = mono_type_size (type, &ialign);
7069 MonoClass *klass = mono_class_get_full (image, token, generic_context);
7072 mono_class_init (klass);
7073 token = mono_class_value_size (klass, &align);
7075 NEW_ICONST (cfg, ins, token);
7080 case CEE_REFANYTYPE:
7082 MONO_INST_NEW (cfg, ins, OP_REFANYTYPE);
7084 ins->type = STACK_MP;
7085 ins->inst_left = *sp;
7086 ins->type = STACK_VTYPE;
7087 ins->klass = mono_defaults.typehandle_class;
7096 g_error ("opcode 0xfe 0x%02x not handled", ip [1]);
7101 g_error ("opcode 0x%02x not handled", *ip);
7104 if (start_new_bblock != 1)
7107 bblock->cil_length = ip - bblock->cil_code;
7108 bblock->next_bb = end_bblock;
7110 if (cfg->method == method && cfg->domainvar) {
7112 MonoInst *get_domain;
7114 if (! (get_domain = mono_arch_get_domain_intrinsic (cfg))) {
7117 MONO_INST_NEW_CALL (cfg, call, CEE_CALL);
7118 call->signature = helper_sig_domain_get;
7119 call->inst.type = STACK_PTR;
7120 call->fptr = mono_domain_get;
7121 get_domain = (MonoInst*)call;
7124 NEW_TEMPSTORE (cfg, store, cfg->domainvar->inst_c0, get_domain);
7125 MONO_ADD_INS (init_localsbb, store);
7128 if (cfg->method == method && cfg->got_var)
7129 mono_emit_load_got_addr (cfg);
7131 if (header->init_locals) {
7133 for (i = 0; i < header->num_locals; ++i) {
7134 MonoType *ptype = header->locals [i];
7135 int t = ptype->type;
7136 if (t == MONO_TYPE_VALUETYPE && ptype->data.klass->enumtype)
7137 t = ptype->data.klass->enum_basetype->type;
7139 NEW_PCONST (cfg, ins, NULL);
7140 NEW_LOCSTORE (cfg, store, i, ins);
7141 MONO_ADD_INS (init_localsbb, store);
7142 } else if (t >= MONO_TYPE_BOOLEAN && t <= MONO_TYPE_U4) {
7143 NEW_ICONST (cfg, ins, 0);
7144 NEW_LOCSTORE (cfg, store, i, ins);
7145 MONO_ADD_INS (init_localsbb, store);
7146 } else if (t == MONO_TYPE_I8 || t == MONO_TYPE_U8) {
7147 MONO_INST_NEW (cfg, ins, OP_I8CONST);
7148 ins->type = STACK_I8;
7150 NEW_LOCSTORE (cfg, store, i, ins);
7151 MONO_ADD_INS (init_localsbb, store);
7152 } else if (t == MONO_TYPE_R4 || t == MONO_TYPE_R8) {
7153 MONO_INST_NEW (cfg, ins, OP_R8CONST);
7154 ins->type = STACK_R8;
7155 ins->inst_p0 = (void*)&r8_0;
7156 NEW_LOCSTORE (cfg, store, i, ins);
7157 MONO_ADD_INS (init_localsbb, store);
7158 } else if ((t == MONO_TYPE_VALUETYPE) || (t == MONO_TYPE_TYPEDBYREF) ||
7159 ((t == MONO_TYPE_GENERICINST) && mono_type_generic_inst_is_valuetype (ptype))) {
7160 NEW_LOCLOADA (cfg, ins, i);
7161 handle_initobj (cfg, init_localsbb, ins, NULL, mono_class_from_mono_type (ptype), NULL, NULL);
7163 NEW_PCONST (cfg, ins, NULL);
7164 NEW_LOCSTORE (cfg, store, i, ins);
7165 MONO_ADD_INS (init_localsbb, store);
7170 /* resolve backward branches in the middle of an existing basic block */
7171 for (tmp = bb_recheck; tmp; tmp = tmp->next) {
7173 /*g_print ("need recheck in %s at IL_%04x\n", method->name, bblock->cil_code - header->code);*/
7174 tblock = find_previous (bbhash, start_bblock, bblock->cil_code);
7175 if (tblock != start_bblock) {
7177 split_bblock (cfg, tblock, bblock);
7178 l = bblock->cil_code - header->code;
7179 bblock->cil_length = tblock->cil_length - l;
7180 tblock->cil_length = l;
7182 g_print ("recheck failed.\n");
7186 if (cfg->method == method) {
7188 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
7189 bb->region = mono_find_block_region (cfg, bb->real_offset);
7191 mono_create_spvar_for_region (cfg, bb->region);
7192 if (cfg->verbose_level > 2)
7193 g_print ("REGION BB%d IL_%04x ID_%08X\n", bb->block_num, bb->real_offset, bb->region);
7196 g_hash_table_destroy (bbhash);
7199 g_slist_free (class_inits);
7200 dont_inline = g_list_remove (dont_inline, method);
7202 if (inline_costs < 0) {
7205 /* Method is too large */
7206 mname = mono_method_full_name (method, TRUE);
7207 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
7208 cfg->exception_message = g_strdup_printf ("Method %s is too complex.", mname);
7213 return inline_costs;
7216 if (cfg->method != method)
7217 g_hash_table_destroy (bbhash);
7218 g_slist_free (class_inits);
7219 dont_inline = g_list_remove (dont_inline, method);
7223 if (cfg->method != method)
7224 g_hash_table_destroy (bbhash);
7225 g_slist_free (class_inits);
7226 dont_inline = g_list_remove (dont_inline, method);
7227 cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
7231 if (cfg->method != method)
7232 g_hash_table_destroy (bbhash);
7233 g_slist_free (class_inits);
7234 dont_inline = g_list_remove (dont_inline, method);
7235 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
7236 cfg->exception_message = g_strdup_printf ("Invalid IL code in %s: %s\n",
7237 mono_method_full_name (method, TRUE), mono_disasm_code_one (NULL, method, ip, NULL));
7242 mono_print_tree (MonoInst *tree) {
7248 arity = mono_burg_arity [tree->opcode];
7250 printf (" %s%s", arity?"(":"", mono_inst_name (tree->opcode));
7252 switch (tree->opcode) {
7254 printf ("[%d]", (int)tree->inst_c0);
7257 printf ("[%lld]", (long long)tree->inst_l);
7260 printf ("[%f]", *(double*)tree->inst_p0);
7263 printf ("[%f]", *(float*)tree->inst_p0);
7267 printf ("[%d]", (int)tree->inst_c0);
7270 if (tree->inst_offset < 0)
7271 printf ("[-0x%x(%s)]", (int)(-tree->inst_offset), mono_arch_regname (tree->inst_basereg));
7273 printf ("[0x%x(%s)]", (int)(tree->inst_offset), mono_arch_regname (tree->inst_basereg));
7276 printf ("[%s]", mono_arch_regname (tree->dreg));
7279 printf ("[%s]", tree->inst_newa_class->name);
7280 mono_print_tree (tree->inst_newa_len);
7291 case OP_VOIDCALLVIRT: {
7292 MonoCallInst *call = (MonoCallInst*)tree;
7294 printf ("[%s]", call->method->name);
7295 else if (call->fptr) {
7296 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (call->fptr);
7298 printf ("[%s]", info->name);
7304 printf ("[%d (", (int)tree->inst_c0);
7305 for (i = 0; i < tree->inst_phi_args [0]; i++) {
7308 printf ("%d", tree->inst_phi_args [i + 1]);
7319 case OP_LOAD_MEMBASE:
7320 case OP_LOADI4_MEMBASE:
7321 case OP_LOADU4_MEMBASE:
7322 case OP_LOADU1_MEMBASE:
7323 case OP_LOADI1_MEMBASE:
7324 case OP_LOADU2_MEMBASE:
7325 case OP_LOADI2_MEMBASE:
7326 printf ("[%s] <- [%s + 0x%x]", mono_arch_regname (tree->dreg), mono_arch_regname (tree->inst_basereg), (int)tree->inst_offset);
7329 case OP_CALL_HANDLER:
7330 printf ("[B%d]", tree->inst_target_bb->block_num);
7340 case OP_VOIDCALL_REG:
7341 mono_print_tree (tree->inst_left);
7353 printf ("[B%dB%d]", tree->inst_true_bb->block_num, tree->inst_false_bb->block_num);
7354 mono_print_tree (tree->inst_left);
7357 if (!mono_arch_print_tree(tree, arity)) {
7359 mono_print_tree (tree->inst_left);
7361 mono_print_tree (tree->inst_right);
7372 mono_print_tree_nl (MonoInst *tree)
7374 mono_print_tree (tree);
7379 create_helper_signature (void)
7381 helper_sig_domain_get = mono_create_icall_signature ("ptr");
7382 helper_sig_class_init_trampoline = mono_create_icall_signature ("void");
7386 mono_icall_get_wrapper (MonoJitICallInfo* callinfo)
7389 MonoMethod *wrapper;
7391 if (callinfo->wrapper) {
7392 return callinfo->wrapper;
7395 if (callinfo->trampoline)
7396 return callinfo->trampoline;
7398 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
7399 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func);
7402 callinfo->trampoline = mono_create_ftnptr (mono_get_root_domain (), mono_create_jit_trampoline_in_domain (mono_get_root_domain (), wrapper));
7403 mono_register_jit_icall_wrapper (callinfo, callinfo->trampoline);
7405 return callinfo->trampoline;
7409 mono_init_trampolines (void)
7411 mono_trampoline_code [MONO_TRAMPOLINE_GENERIC] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_GENERIC);
7412 mono_trampoline_code [MONO_TRAMPOLINE_JUMP] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_JUMP);
7413 mono_trampoline_code [MONO_TRAMPOLINE_CLASS_INIT] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_CLASS_INIT);
7414 #ifdef MONO_ARCH_HAVE_PIC_AOT
7415 mono_trampoline_code [MONO_TRAMPOLINE_AOT] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_AOT);
7417 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
7418 mono_trampoline_code [MONO_TRAMPOLINE_DELEGATE] = mono_arch_create_trampoline_code (MONO_TRAMPOLINE_DELEGATE);
7423 mono_init_exceptions (void)
7425 #ifndef CUSTOM_EXCEPTION_HANDLING
7426 mono_arch_get_restore_context ();
7427 mono_arch_get_call_filter ();
7428 mono_arch_get_throw_exception ();
7429 mono_arch_get_rethrow_exception ();
7434 mono_get_trampoline_code (MonoTrampolineType tramp_type)
7436 return mono_trampoline_code [tramp_type];
7440 mono_create_class_init_trampoline (MonoVTable *vtable)
7444 /* previously created trampoline code */
7445 mono_domain_lock (vtable->domain);
7447 g_hash_table_lookup (vtable->domain->class_init_trampoline_hash,
7449 mono_domain_unlock (vtable->domain);
7453 #ifdef MONO_ARCH_HAVE_CREATE_SPECIFIC_TRAMPOLINE
7454 code = mono_arch_create_specific_trampoline (vtable, MONO_TRAMPOLINE_CLASS_INIT, vtable->domain, NULL);
7456 code = mono_arch_create_class_init_trampoline (vtable);
7459 ptr = mono_create_ftnptr (vtable->domain, code);
7461 /* store trampoline address */
7462 mono_domain_lock (vtable->domain);
7463 g_hash_table_insert (vtable->domain->class_init_trampoline_hash,
7465 mono_domain_unlock (vtable->domain);
7468 if (!class_init_hash_addr)
7469 class_init_hash_addr = g_hash_table_new (NULL, NULL);
7470 g_hash_table_insert (class_init_hash_addr, ptr, vtable);
7477 mono_create_jump_trampoline (MonoDomain *domain, MonoMethod *method,
7478 gboolean add_sync_wrapper)
7482 #ifdef MONO_ARCH_HAVE_CREATE_SPECIFIC_TRAMPOLINE
7486 if (add_sync_wrapper && method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
7487 return mono_create_jump_trampoline (domain, mono_marshal_get_synchronized_wrapper (method), FALSE);
7489 code = mono_jit_find_compiled_method (domain, method);
7493 mono_domain_lock (domain);
7494 code = g_hash_table_lookup (domain->jump_trampoline_hash, method);
7495 mono_domain_unlock (domain);
7499 #ifdef MONO_ARCH_HAVE_CREATE_SPECIFIC_TRAMPOLINE
7500 code = mono_arch_create_specific_trampoline (method, MONO_TRAMPOLINE_JUMP, mono_domain_get (), &code_size);
7502 ji = g_new0 (MonoJitInfo, 1);
7503 ji->code_start = code;
7504 ji->code_size = code_size;
7505 ji->method = method;
7507 ji = mono_arch_create_jump_trampoline (method);
7511 * mono_delegate_ctor needs to find the method metadata from the
7512 * trampoline address, so we save it here.
7515 mono_jit_info_table_add (domain, ji);
7517 mono_domain_lock (domain);
7518 g_hash_table_insert (domain->jump_trampoline_hash, method, ji->code_start);
7519 mono_domain_unlock (domain);
7521 return ji->code_start;
7525 mono_create_jit_trampoline_in_domain (MonoDomain *domain, MonoMethod *method)
7529 mono_domain_lock (domain);
7530 tramp = g_hash_table_lookup (domain->jit_trampoline_hash, method);
7531 mono_domain_unlock (domain);
7535 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
7536 return mono_create_jit_trampoline (mono_marshal_get_synchronized_wrapper (method));
7538 #ifdef MONO_ARCH_HAVE_CREATE_SPECIFIC_TRAMPOLINE
7539 tramp = mono_arch_create_specific_trampoline (method, MONO_TRAMPOLINE_GENERIC, domain, NULL);
7541 tramp = mono_arch_create_jit_trampoline (method);
7544 mono_domain_lock (domain);
7545 g_hash_table_insert (domain->jit_trampoline_hash, method, tramp);
7546 mono_domain_unlock (domain);
7548 mono_jit_stats.method_trampolines++;
7554 mono_create_jit_trampoline (MonoMethod *method)
7556 return mono_create_jit_trampoline_in_domain (mono_domain_get (), method);
7559 #ifdef MONO_ARCH_HAVE_CREATE_TRAMPOLINE_FROM_TOKEN
7561 mono_create_jit_trampoline_from_token (MonoImage *image, guint32 token)
7565 MonoDomain *domain = mono_domain_get ();
7566 guint8 *buf, *start;
7568 mono_domain_lock (domain);
7569 buf = start = mono_code_manager_reserve (domain->code_mp, 2 * sizeof (gpointer));
7570 mono_domain_unlock (domain);
7572 *(gpointer*)(gpointer)buf = image;
7573 buf += sizeof (gpointer);
7574 *(guint32*)(gpointer)buf = token;
7576 tramp = mono_arch_create_specific_trampoline (start, MONO_TRAMPOLINE_AOT, domain, NULL);
7578 mono_jit_stats.method_trampolines++;
7585 mono_create_delegate_trampoline (MonoMethod *method, gpointer addr)
7587 #ifdef MONO_ARCH_HAVE_CREATE_DELEGATE_TRAMPOLINE
7590 MonoDomain *domain = mono_domain_get ();
7593 code = mono_jit_find_compiled_method (domain, method);
7598 * FIXME: We should return a function descriptor here but it is not stored
7599 * anywhere so it would be leaked.
7603 mono_domain_lock (domain);
7604 ptr = g_hash_table_lookup (domain->delegate_trampoline_hash, method);
7605 mono_domain_unlock (domain);
7609 code = mono_arch_create_specific_trampoline (method, MONO_TRAMPOLINE_DELEGATE, domain, &code_size);
7611 ptr = mono_create_ftnptr (domain, code);
7613 /* store trampoline address */
7614 mono_domain_lock (domain);
7615 g_hash_table_insert (domain->delegate_trampoline_hash,
7617 mono_domain_unlock (domain);
7626 mono_find_class_init_trampoline_by_addr (gconstpointer addr)
7631 if (class_init_hash_addr)
7632 res = g_hash_table_lookup (class_init_hash_addr, addr);
7640 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
7642 if (!domain->dynamic_code_hash)
7643 domain->dynamic_code_hash = g_hash_table_new (NULL, NULL);
7644 g_hash_table_insert (domain->dynamic_code_hash, method, ji);
7647 static MonoJitDynamicMethodInfo*
7648 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
7650 MonoJitDynamicMethodInfo *res;
7652 if (domain->dynamic_code_hash)
7653 res = g_hash_table_lookup (domain->dynamic_code_hash, method);
7666 * mono_allocate_stack_slots_full:
7668 * Allocate stack slots for all non register allocated variables using a
7669 * linear scan algorithm.
7670 * Returns: an array of stack offsets which the caller should free.
7671 * STACK_SIZE is set to the amount of stack space needed.
7672 * STACK_ALIGN is set to the alignment needed by the locals area.
7675 mono_allocate_stack_slots_full (MonoCompile *m, gboolean backward, guint32 *stack_size, guint32 *stack_align)
7677 int i, slot, offset, size;
7682 GList *vars = NULL, *l;
7683 StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
7687 scalar_stack_slots = g_new0 (StackSlotInfo, MONO_TYPE_PINNED);
7688 vtype_stack_slots = g_new0 (StackSlotInfo, 256);
7691 offsets = g_new (gint32, m->num_varinfo);
7692 for (i = 0; i < m->num_varinfo; ++i)
7695 for (i = m->locals_start; i < m->num_varinfo; i++) {
7696 inst = m->varinfo [i];
7697 vmv = MONO_VARINFO (m, i);
7699 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
7702 vars = g_list_prepend (vars, vmv);
7705 vars = mono_varlist_sort (m, vars, 0);
7708 for (l = vars; l; l = l->next) {
7710 inst = m->varinfo [vmv->idx];
7712 /* inst->unused indicates native sized value types, this is used by the
7713 * pinvoke wrappers when they call functions returning structures */
7714 if (inst->unused && MONO_TYPE_ISSTRUCT (inst->inst_vtype) && inst->inst_vtype->type != MONO_TYPE_TYPEDBYREF)
7715 size = mono_class_native_size (inst->inst_vtype->data.klass, &align);
7719 size = mono_type_size (inst->inst_vtype, &ialign);
7723 t = mono_type_get_underlying_type (inst->inst_vtype);
7725 case MONO_TYPE_GENERICINST:
7726 if (!mono_type_generic_inst_is_valuetype (t)) {
7727 slot_info = &scalar_stack_slots [t->type];
7731 case MONO_TYPE_VALUETYPE:
7732 for (i = 0; i < nvtypes; ++i)
7733 if (t->data.klass == vtype_stack_slots [i].vtype)
7736 slot_info = &vtype_stack_slots [i];
7738 g_assert (nvtypes < 256);
7739 vtype_stack_slots [nvtypes].vtype = t->data.klass;
7740 slot_info = &vtype_stack_slots [nvtypes];
7745 slot_info = &scalar_stack_slots [t->type];
7749 if (m->comp_done & MONO_COMP_LIVENESS) {
7750 //printf ("START %2d %08x %08x\n", vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
7752 /* expire old intervals in active */
7753 while (slot_info->active) {
7754 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
7756 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
7759 //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);
7761 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
7762 slot_info->slots = g_list_prepend (slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
7766 * This also handles the case when the variable is used in an
7767 * exception region, as liveness info is not computed there.
7770 * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
7773 if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
7774 if (slot_info->slots) {
7775 slot = GPOINTER_TO_INT (slot_info->slots->data);
7777 slot_info->slots = g_list_delete_link (slot_info->slots, slot_info->slots);
7780 slot_info->active = mono_varlist_insert_sorted (m, slot_info->active, vmv, TRUE);
7785 static int count = 0;
7789 if (count == atoi (getenv ("COUNT")))
7790 printf ("LAST: %s\n", mono_method_full_name (m->method, TRUE));
7791 if (count > atoi (getenv ("COUNT")))
7794 mono_print_tree_nl (inst);
7798 if (slot == 0xffffff) {
7800 * Allways allocate valuetypes to sizeof (gpointer) to allow more
7801 * efficient copying (and to work around the fact that OP_MEMCPY
7802 * and OP_MEMSET ignores alignment).
7804 if (MONO_TYPE_ISSTRUCT (t))
7805 align = sizeof (gpointer);
7809 offset += align - 1;
7810 offset &= ~(align - 1);
7814 offset += align - 1;
7815 offset &= ~(align - 1);
7820 if (*stack_align == 0)
7821 *stack_align = align;
7824 offsets [vmv->idx] = slot;
7827 for (i = 0; i < MONO_TYPE_PINNED; ++i) {
7828 g_list_free (scalar_stack_slots [i].active);
7829 g_list_free (scalar_stack_slots [i].slots);
7831 for (i = 0; i < nvtypes; ++i) {
7832 g_list_free (vtype_stack_slots [i].active);
7833 g_list_free (vtype_stack_slots [i].slots);
7835 g_free (scalar_stack_slots);
7836 g_free (vtype_stack_slots);
7838 *stack_size = offset;
7843 mono_allocate_stack_slots (MonoCompile *m, guint32 *stack_size, guint32 *stack_align)
7845 return mono_allocate_stack_slots_full (m, TRUE, stack_size, stack_align);
7849 mono_register_opcode_emulation (int opcode, const char *name, const char *sigstr, gpointer func, gboolean no_throw)
7851 MonoJitICallInfo *info;
7852 MonoMethodSignature *sig = mono_create_icall_signature (sigstr);
7854 if (!emul_opcode_map)
7855 emul_opcode_map = g_new0 (MonoJitICallInfo*, OP_LAST + 1);
7857 g_assert (!sig->hasthis);
7858 g_assert (sig->param_count < 3);
7860 info = mono_register_jit_icall (func, name, sig, no_throw);
7862 emul_opcode_map [opcode] = info;
7866 register_icall (gpointer func, const char *name, const char *sigstr, gboolean save)
7868 MonoMethodSignature *sig;
7871 sig = mono_create_icall_signature (sigstr);
7875 mono_register_jit_icall (func, name, sig, save);
7879 decompose_foreach (MonoInst *tree, gpointer data)
7881 static MonoJitICallInfo *newarr_info = NULL;
7882 static MonoJitICallInfo *newarr_specific_info = NULL;
7883 MonoJitICallInfo *info;
7886 switch (tree->opcode) {
7888 MonoCompile *cfg = data;
7889 MonoInst *iargs [3];
7892 newarr_info = mono_find_jit_icall_by_addr (mono_array_new);
7893 g_assert (newarr_info);
7894 newarr_specific_info = mono_find_jit_icall_by_addr (mono_array_new_specific);
7895 g_assert (newarr_specific_info);
7898 if (cfg->opt & MONO_OPT_SHARED) {
7899 NEW_DOMAINCONST (cfg, iargs [0]);
7900 NEW_CLASSCONST (cfg, iargs [1], tree->inst_newa_class);
7901 iargs [2] = tree->inst_newa_len;
7906 MonoVTable *vtable = mono_class_vtable (cfg->domain, mono_array_class_get (tree->inst_newa_class, 1));
7908 NEW_VTABLECONST (cfg, iargs [0], vtable);
7909 iargs [1] = tree->inst_newa_len;
7911 info = newarr_specific_info;
7914 mono_emulate_opcode (cfg, tree, iargs, info);
7916 /* Need to decompose arguments after the the opcode is decomposed */
7917 for (i = 0; i < info->sig->param_count; ++i)
7918 dec_foreach (iargs [i], cfg);
7928 mono_inst_foreach (MonoInst *tree, MonoInstFunc func, gpointer data) {
7930 switch (mono_burg_arity [tree->opcode]) {
7933 mono_inst_foreach (tree->inst_left, func, data);
7936 mono_inst_foreach (tree->inst_left, func, data);
7937 mono_inst_foreach (tree->inst_right, func, data);
7940 g_assert_not_reached ();
7947 mono_print_bb_code (MonoBasicBlock *bb) {
7949 MonoInst *c = bb->code;
7951 mono_print_tree (c);
7959 print_dfn (MonoCompile *cfg) {
7964 g_print ("IR code for method %s\n", mono_method_full_name (cfg->method, TRUE));
7966 for (i = 0; i < cfg->num_bblocks; ++i) {
7967 bb = cfg->bblocks [i];
7968 /*if (bb->cil_code) {
7969 char* code1, *code2;
7970 code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
7971 if (bb->last_ins->cil_code)
7972 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
7974 code2 = g_strdup ("");
7976 code1 [strlen (code1) - 1] = 0;
7977 code = g_strdup_printf ("%s -> %s", code1, code2);
7981 code = g_strdup ("\n");
7982 g_print ("\nBB%d DFN%d (len: %d): %s", bb->block_num, i, bb->cil_length, code);
7984 MonoInst *c = bb->code;
7986 mono_print_tree (c);
7994 g_print ("\tprev:");
7995 for (j = 0; j < bb->in_count; ++j) {
7996 g_print (" BB%d", bb->in_bb [j]->block_num);
7998 g_print ("\t\tsucc:");
7999 for (j = 0; j < bb->out_count; ++j) {
8000 g_print (" BB%d", bb->out_bb [j]->block_num);
8002 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
8005 g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
8008 mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
8010 mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
8018 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
8022 g_assert (bb->code);
8023 bb->last_ins->next = inst;
8024 bb->last_ins = inst;
8026 bb->last_ins = bb->code = inst;
8031 mono_destroy_compile (MonoCompile *cfg)
8033 //mono_mempool_stats (cfg->mempool);
8034 g_hash_table_destroy (cfg->bb_hash);
8035 mono_free_loop_info (cfg);
8037 mono_regstate_free (cfg->rs);
8039 g_hash_table_destroy (cfg->spvars);
8041 g_hash_table_destroy (cfg->exvars);
8042 mono_mempool_destroy (cfg->mempool);
8043 g_list_free (cfg->ldstr_list);
8045 g_free (cfg->varinfo);
8047 g_free (cfg->exception_message);
8051 #ifdef HAVE_KW_THREAD
8052 static __thread gpointer mono_lmf_addr MONO_TLS_FAST;
8056 mono_get_jit_tls_key (void)
8058 return mono_jit_tls_id;
8062 mono_get_lmf_tls_offset (void)
8065 MONO_THREAD_VAR_OFFSET(mono_lmf_addr,offset);
8070 mono_get_lmf_addr (void)
8072 #ifdef HAVE_KW_THREAD
8073 return mono_lmf_addr;
8075 MonoJitTlsData *jit_tls;
8077 if ((jit_tls = TlsGetValue (mono_jit_tls_id)))
8078 return &jit_tls->lmf;
8080 g_assert_not_reached ();
8085 /* Called by native->managed wrappers */
8087 mono_jit_thread_attach (MonoDomain *domain)
8089 #ifdef HAVE_KW_THREAD
8090 if (!mono_lmf_addr) {
8091 mono_thread_attach (domain);
8094 if (!TlsGetValue (mono_jit_tls_id))
8095 mono_thread_attach (domain);
8100 * mono_thread_abort:
8101 * @obj: exception object
8103 * abort the thread, print exception information and stack trace
8106 mono_thread_abort (MonoObject *obj)
8108 /* MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id); */
8110 /* handle_remove should be eventually called for this thread, too
8113 mono_thread_exit ();
8117 setup_jit_tls_data (gpointer stack_start, gpointer abort_func)
8119 MonoJitTlsData *jit_tls;
8122 jit_tls = TlsGetValue (mono_jit_tls_id);
8126 jit_tls = g_new0 (MonoJitTlsData, 1);
8128 TlsSetValue (mono_jit_tls_id, jit_tls);
8130 jit_tls->abort_func = abort_func;
8131 jit_tls->end_of_stack = stack_start;
8133 lmf = g_new0 (MonoLMF, 1);
8136 jit_tls->lmf = jit_tls->first_lmf = lmf;
8138 #ifdef HAVE_KW_THREAD
8139 mono_lmf_addr = &jit_tls->lmf;
8142 mono_arch_setup_jit_tls_data (jit_tls);
8144 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
8145 mono_setup_altstack (jit_tls);
8152 mono_thread_start_cb (gsize tid, gpointer stack_start, gpointer func)
8155 void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort);
8156 thread = mono_thread_current ();
8158 thread->jit_data = jit_tls;
8161 void (*mono_thread_attach_aborted_cb ) (MonoObject *obj) = NULL;
8164 mono_thread_abort_dummy (MonoObject *obj)
8166 if (mono_thread_attach_aborted_cb)
8167 mono_thread_attach_aborted_cb (obj);
8169 mono_thread_abort (obj);
8173 mono_thread_attach_cb (gsize tid, gpointer stack_start)
8176 void *jit_tls = setup_jit_tls_data (stack_start, mono_thread_abort_dummy);
8177 thread = mono_thread_current ();
8179 thread->jit_data = jit_tls;
8180 if (mono_profiler_get_events () & MONO_PROFILE_STATISTICAL)
8181 setup_stat_profiler ();
8185 mini_thread_cleanup (MonoThread *thread)
8187 MonoJitTlsData *jit_tls = thread->jit_data;
8190 mono_arch_free_jit_tls_data (jit_tls);
8192 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
8193 mono_free_altstack (jit_tls);
8195 g_free (jit_tls->first_lmf);
8197 thread->jit_data = NULL;
8202 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
8204 MonoJumpInfo *ji = mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
8208 ji->data.target = target;
8209 ji->next = cfg->patch_info;
8211 cfg->patch_info = ji;
8215 mono_remove_patch_info (MonoCompile *cfg, int ip)
8217 MonoJumpInfo **ji = &cfg->patch_info;
8220 if ((*ji)->ip.i == ip)
8223 ji = &((*ji)->next);
8228 mono_resolve_patch_target (MonoMethod *method, MonoDomain *domain, guint8 *code, MonoJumpInfo *patch_info, gboolean run_cctors)
8230 unsigned char *ip = patch_info->ip.i + code;
8231 gconstpointer target = NULL;
8233 switch (patch_info->type) {
8234 case MONO_PATCH_INFO_BB:
8235 target = patch_info->data.bb->native_offset + code;
8237 case MONO_PATCH_INFO_ABS:
8238 target = patch_info->data.target;
8240 case MONO_PATCH_INFO_LABEL:
8241 target = patch_info->data.inst->inst_c0 + code;
8243 case MONO_PATCH_INFO_IP:
8246 case MONO_PATCH_INFO_METHOD_REL:
8247 target = code + patch_info->data.offset;
8249 case MONO_PATCH_INFO_INTERNAL_METHOD: {
8250 MonoJitICallInfo *mi = mono_find_jit_icall_by_name (patch_info->data.name);
8252 g_warning ("unknown MONO_PATCH_INFO_INTERNAL_METHOD %s", patch_info->data.name);
8253 g_assert_not_reached ();
8255 target = mono_icall_get_wrapper (mi);
8258 case MONO_PATCH_INFO_METHOD_JUMP: {
8261 /* get the trampoline to the method from the domain */
8262 target = mono_create_jump_trampoline (domain, patch_info->data.method, TRUE);
8263 if (!domain->jump_target_hash)
8264 domain->jump_target_hash = g_hash_table_new (NULL, NULL);
8265 list = g_hash_table_lookup (domain->jump_target_hash, patch_info->data.method);
8266 list = g_slist_prepend (list, ip);
8267 g_hash_table_insert (domain->jump_target_hash, patch_info->data.method, list);
8270 case MONO_PATCH_INFO_METHOD:
8271 if (patch_info->data.method == method) {
8274 /* get the trampoline to the method from the domain */
8275 target = mono_create_jit_trampoline (patch_info->data.method);
8277 case MONO_PATCH_INFO_SWITCH: {
8278 gpointer *jump_table;
8281 if (method && method->dynamic) {
8282 jump_table = mono_code_manager_reserve (mono_dynamic_code_hash_lookup (domain, method)->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
8284 mono_domain_lock (domain);
8285 jump_table = mono_code_manager_reserve (domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
8286 mono_domain_unlock (domain);
8289 for (i = 0; i < patch_info->data.table->table_size; i++) {
8290 jump_table [i] = code + GPOINTER_TO_INT (patch_info->data.table->table [i]);
8292 target = jump_table;
8295 case MONO_PATCH_INFO_METHODCONST:
8296 case MONO_PATCH_INFO_CLASS:
8297 case MONO_PATCH_INFO_IMAGE:
8298 case MONO_PATCH_INFO_FIELD:
8299 target = patch_info->data.target;
8301 case MONO_PATCH_INFO_IID:
8302 mono_class_init (patch_info->data.klass);
8303 target = GINT_TO_POINTER ((int)patch_info->data.klass->interface_id);
8305 case MONO_PATCH_INFO_VTABLE:
8306 target = mono_class_vtable (domain, patch_info->data.klass);
8308 case MONO_PATCH_INFO_CLASS_INIT:
8309 target = mono_create_class_init_trampoline (mono_class_vtable (domain, patch_info->data.klass));
8311 case MONO_PATCH_INFO_SFLDA: {
8312 MonoVTable *vtable = mono_class_vtable (domain, patch_info->data.field->parent);
8313 if (!vtable->initialized && !(vtable->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT) && (method && mono_class_needs_cctor_run (vtable->klass, method)))
8314 /* Done by the generated code */
8318 mono_runtime_class_init (vtable);
8320 target = (char*)vtable->data + patch_info->data.field->offset;
8323 case MONO_PATCH_INFO_R4:
8324 case MONO_PATCH_INFO_R8:
8325 target = patch_info->data.target;
8327 case MONO_PATCH_INFO_EXC_NAME:
8328 target = patch_info->data.name;
8330 case MONO_PATCH_INFO_LDSTR:
8332 mono_ldstr (domain, patch_info->data.token->image,
8333 mono_metadata_token_index (patch_info->data.token->token));
8335 case MONO_PATCH_INFO_TYPE_FROM_HANDLE: {
8337 MonoClass *handle_class;
8339 handle = mono_ldtoken (patch_info->data.token->image,
8340 patch_info->data.token->token, &handle_class, NULL);
8341 mono_class_init (handle_class);
8342 mono_class_init (mono_class_from_mono_type (handle));
8345 mono_type_get_object (domain, handle);
8348 case MONO_PATCH_INFO_LDTOKEN: {
8350 MonoClass *handle_class;
8352 handle = mono_ldtoken (patch_info->data.token->image,
8353 patch_info->data.token->token, &handle_class, NULL);
8354 mono_class_init (handle_class);
8359 case MONO_PATCH_INFO_DECLSEC:
8360 target = (mono_metadata_blob_heap (patch_info->data.token->image, patch_info->data.token->token) + 2);
8362 case MONO_PATCH_INFO_BB_OVF:
8363 case MONO_PATCH_INFO_EXC_OVF:
8364 case MONO_PATCH_INFO_GOT_OFFSET:
8365 case MONO_PATCH_INFO_NONE:
8368 g_assert_not_reached ();
8371 return (gpointer)target;
8375 dec_foreach (MonoInst *tree, MonoCompile *cfg) {
8376 MonoJitICallInfo *info;
8378 decompose_foreach (tree, cfg);
8380 switch (mono_burg_arity [tree->opcode]) {
8383 dec_foreach (tree->inst_left, cfg);
8385 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
8386 MonoInst *iargs [2];
8388 iargs [0] = tree->inst_left;
8390 mono_emulate_opcode (cfg, tree, iargs, info);
8396 #ifdef MONO_ARCH_BIGMUL_INTRINS
8397 if (tree->opcode == OP_LMUL
8398 && (cfg->opt & MONO_OPT_INTRINS)
8399 && (tree->inst_left->opcode == CEE_CONV_I8
8400 || tree->inst_left->opcode == CEE_CONV_U8)
8401 && tree->inst_left->inst_left->type == STACK_I4
8402 && (tree->inst_right->opcode == CEE_CONV_I8
8403 || tree->inst_right->opcode == CEE_CONV_U8)
8404 && tree->inst_right->inst_left->type == STACK_I4
8405 && tree->inst_left->opcode == tree->inst_right->opcode) {
8406 tree->opcode = (tree->inst_left->opcode == CEE_CONV_I8 ? OP_BIGMUL: OP_BIGMUL_UN);
8407 tree->inst_left = tree->inst_left->inst_left;
8408 tree->inst_right = tree->inst_right->inst_left;
8409 dec_foreach (tree, cfg);
8412 if ((info = mono_find_jit_opcode_emulation (tree->opcode))) {
8413 MonoInst *iargs [2];
8415 iargs [0] = tree->inst_i0;
8416 iargs [1] = tree->inst_i1;
8418 mono_emulate_opcode (cfg, tree, iargs, info);
8420 dec_foreach (iargs [0], cfg);
8421 dec_foreach (iargs [1], cfg);
8424 dec_foreach (tree->inst_left, cfg);
8425 dec_foreach (tree->inst_right, cfg);
8429 g_assert_not_reached ();
8434 decompose_pass (MonoCompile *cfg) {
8437 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
8440 cfg->prev_ins = NULL;
8441 for (tree = cfg->cbb->code; tree; tree = tree->next) {
8442 dec_foreach (tree, cfg);
8443 cfg->prev_ins = tree;
8449 nullify_basic_block (MonoBasicBlock *bb)
8456 bb->code = bb->last_ins = NULL;
8457 bb->cil_code = NULL;
8461 replace_out_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
8465 for (i = 0; i < bb->out_count; i++) {
8466 MonoBasicBlock *ob = bb->out_bb [i];
8469 if (bb->out_count > 1) {
8470 bb->out_bb [i] = bb->out_bb [bb->out_count - 1];
8474 bb->out_bb [i] = repl;
8481 replace_in_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
8485 for (i = 0; i < bb->in_count; i++) {
8486 MonoBasicBlock *ib = bb->in_bb [i];
8489 if (bb->in_count > 1) {
8490 bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
8494 bb->in_bb [i] = repl;
8501 replace_or_add_in_block (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
8503 gboolean found = FALSE;
8506 for (i = 0; i < bb->in_count; i++) {
8507 MonoBasicBlock *ib = bb->in_bb [i];
8510 if (bb->in_count > 1) {
8511 bb->in_bb [i] = bb->in_bb [bb->in_count - 1];
8515 bb->in_bb [i] = repl;
8522 MonoBasicBlock **new_in_bb = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (bb->in_count + 1));
8523 for (i = 0; i < bb->in_count; i++) {
8524 new_in_bb [i] = bb->in_bb [i];
8526 new_in_bb [i] = repl;
8528 bb->in_bb = new_in_bb;
8534 replace_out_block_in_code (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl) {
8537 for (inst = bb->code; inst != NULL; inst = inst->next) {
8538 if (inst->opcode == OP_CALL_HANDLER) {
8539 if (inst->inst_target_bb == orig) {
8540 inst->inst_target_bb = repl;
8544 if (bb->last_ins != NULL) {
8545 switch (bb->last_ins->opcode) {
8547 if (bb->last_ins->inst_target_bb == orig) {
8548 bb->last_ins->inst_target_bb = repl;
8553 int n = GPOINTER_TO_INT (bb->last_ins->klass);
8554 for (i = 0; i < n; i++ ) {
8555 if (bb->last_ins->inst_many_bb [i] == orig) {
8556 bb->last_ins->inst_many_bb [i] = repl;
8571 if (bb->last_ins->inst_true_bb == orig) {
8572 bb->last_ins->inst_true_bb = repl;
8574 if (bb->last_ins->inst_false_bb == orig) {
8575 bb->last_ins->inst_false_bb = repl;
8585 replace_basic_block (MonoBasicBlock *bb, MonoBasicBlock *orig, MonoBasicBlock *repl)
8589 for (i = 0; i < bb->out_count; i++) {
8590 MonoBasicBlock *ob = bb->out_bb [i];
8591 for (j = 0; j < ob->in_count; j++) {
8592 if (ob->in_bb [j] == orig) {
8593 ob->in_bb [j] = repl;
8601 * Check if a bb is useless (is just made of NOPs and ends with an
8602 * unconditional branch, or nothing).
8603 * If it is so, unlink it from the CFG and nullify it, and return TRUE.
8604 * Otherwise, return FALSE;
8607 remove_block_if_useless (MonoCompile *cfg, MonoBasicBlock *bb, MonoBasicBlock *previous_bb) {
8608 MonoBasicBlock *target_bb = NULL;
8611 /* Do not touch handlers */
8612 if (bb->region != -1) {
8613 bb->not_useless = TRUE;
8617 for (inst = bb->code; inst != NULL; inst = inst->next) {
8618 switch (inst->opcode) {
8622 target_bb = inst->inst_target_bb;
8625 bb->not_useless = TRUE;
8630 if (target_bb == NULL) {
8631 if ((bb->out_count == 1) && (bb->out_bb [0] == bb->next_bb)) {
8632 target_bb = bb->next_bb;
8634 /* Do not touch empty BBs that do not "fall through" to their next BB (like the exit BB) */
8639 /* Do not touch BBs following a switch (they are the "default" branch) */
8640 if ((previous_bb->last_ins != NULL) && (previous_bb->last_ins->opcode == CEE_SWITCH)) {
8644 /* Do not touch BBs following the entry BB and jumping to something that is not */
8645 /* thiry "next" bb (the entry BB cannot contain the branch) */
8646 if ((previous_bb == cfg->bb_entry) && (bb->next_bb != target_bb)) {
8650 /* Check that there is a target BB, and that bb is not an empty loop (Bug 75061) */
8651 if ((target_bb != NULL) && (target_bb != bb)) {
8654 if (cfg->verbose_level > 1) {
8655 printf ("remove_block_if_useless %s, removed BB%d\n", mono_method_full_name (cfg->method, TRUE), bb->block_num);
8658 for (i = 0; i < bb->in_count; i++) {
8659 MonoBasicBlock *in_bb = bb->in_bb [i];
8660 replace_out_block (in_bb, bb, target_bb);
8661 replace_out_block_in_code (in_bb, bb, target_bb);
8662 if (bb->in_count == 1) {
8663 replace_in_block (target_bb, bb, in_bb);
8665 replace_or_add_in_block (cfg, target_bb, bb, in_bb);
8669 mono_unlink_bblock (cfg, bb, target_bb);
8671 if ((previous_bb != cfg->bb_entry) &&
8672 (previous_bb->region == bb->region) &&
8673 ((previous_bb->last_ins == NULL) ||
8674 ((previous_bb->last_ins->opcode != CEE_BR) &&
8675 (! (MONO_IS_COND_BRANCH_OP (previous_bb->last_ins))) &&
8676 (previous_bb->last_ins->opcode != CEE_SWITCH)))) {
8677 for (i = 0; i < previous_bb->out_count; i++) {
8678 if (previous_bb->out_bb [i] == target_bb) {
8680 MONO_INST_NEW (cfg, jump, CEE_BR);
8681 MONO_ADD_INS (previous_bb, jump);
8682 jump->cil_code = previous_bb->cil_code;
8683 jump->inst_target_bb = target_bb;
8689 previous_bb->next_bb = bb->next_bb;
8690 nullify_basic_block (bb);
8699 merge_basic_blocks (MonoBasicBlock *bb, MonoBasicBlock *bbn)
8701 bb->out_count = bbn->out_count;
8702 bb->out_bb = bbn->out_bb;
8704 replace_basic_block (bb, bbn, bb);
8708 bb->last_ins->next = bbn->code;
8709 bb->last_ins = bbn->last_ins;
8712 bb->code = bbn->code;
8713 bb->last_ins = bbn->last_ins;
8715 bb->next_bb = bbn->next_bb;
8716 nullify_basic_block (bbn);
8720 move_basic_block_to_end (MonoCompile *cfg, MonoBasicBlock *bb)
8722 MonoBasicBlock *bbn, *next;
8726 /* Find the previous */
8727 for (bbn = cfg->bb_entry; bbn->next_bb && bbn->next_bb != bb; bbn = bbn->next_bb)
8730 bbn->next_bb = bb->next_bb;
8734 for (bbn = cfg->bb_entry; bbn->next_bb; bbn = bbn->next_bb)
8740 if (next && (!bb->last_ins || (bb->last_ins->opcode != OP_NOT_REACHED))) {
8743 MONO_INST_NEW (cfg, ins, CEE_BR);
8744 MONO_ADD_INS (bb, ins);
8745 link_bblock (cfg, bb, next);
8746 ins->inst_target_bb = next;
8750 /* checks that a and b represent the same instructions, conservatively,
8751 * it can return FALSE also for two trees that are equal.
8752 * FIXME: also make sure there are no side effects.
8755 same_trees (MonoInst *a, MonoInst *b)
8758 if (a->opcode != b->opcode)
8760 arity = mono_burg_arity [a->opcode];
8762 if (a->ssa_op == b->ssa_op && a->ssa_op == MONO_SSA_LOAD && a->inst_i0 == b->inst_i0)
8764 return same_trees (a->inst_left, b->inst_left);
8765 } else if (arity == 2) {
8766 return same_trees (a->inst_left, b->inst_left) && same_trees (a->inst_right, b->inst_right);
8767 } else if (arity == 0) {
8768 switch (a->opcode) {
8770 return a->inst_c0 == b->inst_c0;
8779 get_unsigned_condbranch (int opcode)
8782 case CEE_BLE: return CEE_BLE_UN;
8783 case CEE_BLT: return CEE_BLT_UN;
8784 case CEE_BGE: return CEE_BGE_UN;
8785 case CEE_BGT: return CEE_BGT_UN;
8787 g_assert_not_reached ();
8792 tree_is_unsigned (MonoInst* ins) {
8793 switch (ins->opcode) {
8795 return (int)ins->inst_c0 >= 0;
8796 /* array lengths are positive as are string sizes */
8803 case CEE_CONV_OVF_U1:
8804 case CEE_CONV_OVF_U2:
8805 case CEE_CONV_OVF_U4:
8816 /* check if an unsigned compare can be used instead of two signed compares
8817 * for (val < 0 || val > limit) conditionals.
8818 * Returns TRUE if the optimization has been applied.
8819 * Note that this can't be applied if the second arg is not positive...
8822 try_unsigned_compare (MonoCompile *cfg, MonoBasicBlock *bb)
8824 MonoBasicBlock *truet, *falset;
8825 MonoInst *cmp_inst = bb->last_ins->inst_left;
8827 if (!cmp_inst->inst_right->inst_c0 == 0)
8829 truet = bb->last_ins->inst_true_bb;
8830 falset = bb->last_ins->inst_false_bb;
8831 if (falset->in_count != 1)
8833 condb = falset->last_ins;
8834 /* target bb must have one instruction */
8835 if (!condb || (condb != falset->code))
8837 if ((((condb->opcode == CEE_BLE || condb->opcode == CEE_BLT) && (condb->inst_false_bb == truet))
8838 || ((condb->opcode == CEE_BGE || condb->opcode == CEE_BGT) && (condb->inst_true_bb == truet)))
8839 && same_trees (cmp_inst->inst_left, condb->inst_left->inst_left)) {
8840 if (!tree_is_unsigned (condb->inst_left->inst_right))
8842 condb->opcode = get_unsigned_condbranch (condb->opcode);
8843 /* change the original condbranch to just point to the new unsigned check */
8844 bb->last_ins->opcode = CEE_BR;
8845 bb->last_ins->inst_target_bb = falset;
8846 replace_out_block (bb, truet, NULL);
8847 replace_in_block (truet, bb, NULL);
8854 * Optimizes the branches on the Control Flow Graph
8858 optimize_branches (MonoCompile *cfg)
8860 int i, changed = FALSE;
8861 MonoBasicBlock *bb, *bbn;
8862 guint32 niterations;
8865 * Some crazy loops could cause the code below to go into an infinite
8866 * loop, see bug #53003 for an example. To prevent this, we put an upper
8867 * bound on the number of iterations.
8869 if (cfg->num_bblocks > 1000)
8870 niterations = cfg->num_bblocks * 2;
8875 MonoBasicBlock *previous_bb;
8879 /* we skip the entry block (exit is handled specially instead ) */
8880 for (previous_bb = cfg->bb_entry, bb = cfg->bb_entry->next_bb; bb; previous_bb = bb, bb = bb->next_bb) {
8882 /* dont touch code inside exception clauses */
8883 if (bb->region != -1)
8886 if (!bb->not_useless && remove_block_if_useless (cfg, bb, previous_bb)) {
8891 if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
8892 if (cfg->verbose_level > 2)
8893 g_print ("nullify block triggered %d\n", bbn->block_num);
8895 bb->next_bb = bbn->next_bb;
8897 for (i = 0; i < bbn->out_count; i++)
8898 replace_in_block (bbn->out_bb [i], bbn, NULL);
8900 nullify_basic_block (bbn);
8904 if (bb->out_count == 1) {
8905 bbn = bb->out_bb [0];
8907 /* conditional branches where true and false targets are the same can be also replaced with CEE_BR */
8908 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins)) {
8910 MONO_INST_NEW (cfg, pop, CEE_POP);
8911 pop->inst_left = bb->last_ins->inst_left->inst_left;
8912 mono_add_ins_to_end (bb, pop);
8913 MONO_INST_NEW (cfg, pop, CEE_POP);
8914 pop->inst_left = bb->last_ins->inst_left->inst_right;
8915 mono_add_ins_to_end (bb, pop);
8916 bb->last_ins->opcode = CEE_BR;
8917 bb->last_ins->inst_target_bb = bb->last_ins->inst_true_bb;
8919 if (cfg->verbose_level > 2)
8920 g_print ("cond branch removal triggered in %d %d\n", bb->block_num, bb->out_count);
8923 if (bb->region == bbn->region && bb->next_bb == bbn) {
8924 /* the block are in sequence anyway ... */
8926 /* branches to the following block can be removed */
8927 if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
8928 bb->last_ins->opcode = CEE_NOP;
8930 if (cfg->verbose_level > 2)
8931 g_print ("br removal triggered %d -> %d\n", bb->block_num, bbn->block_num);
8934 if (bbn->in_count == 1) {
8936 if (bbn != cfg->bb_exit) {
8937 if (cfg->verbose_level > 2)
8938 g_print ("block merge triggered %d -> %d\n", bb->block_num, bbn->block_num);
8939 merge_basic_blocks (bb, bbn);
8944 //mono_print_bb_code (bb);
8948 if ((bbn = bb->next_bb) && bbn->in_count == 0 && bb->region == bbn->region) {
8949 if (cfg->verbose_level > 2) {
8950 g_print ("nullify block triggered %d\n", bbn->block_num);
8952 bb->next_bb = bbn->next_bb;
8954 for (i = 0; i < bbn->out_count; i++)
8955 replace_in_block (bbn->out_bb [i], bbn, NULL);
8957 nullify_basic_block (bbn);
8962 if (bb->out_count == 1) {
8963 bbn = bb->out_bb [0];
8965 if (bb->last_ins && bb->last_ins->opcode == CEE_BR) {
8966 bbn = bb->last_ins->inst_target_bb;
8967 if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
8968 bbn->code->inst_target_bb->region == bb->region) {
8970 if (cfg->verbose_level > 2)
8971 g_print ("in %s branch to branch triggered %d -> %d -> %d\n", cfg->method->name,
8972 bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num);
8974 replace_in_block (bbn, bb, NULL);
8975 replace_out_block (bb, bbn, bbn->code->inst_target_bb);
8976 link_bblock (cfg, bb, bbn->code->inst_target_bb);
8977 bb->last_ins->inst_target_bb = bbn->code->inst_target_bb;
8982 } else if (bb->out_count == 2) {
8983 if (bb->last_ins && MONO_IS_COND_BRANCH_NOFP (bb->last_ins)) {
8984 int branch_result = mono_eval_cond_branch (bb->last_ins);
8985 MonoBasicBlock *taken_branch_target = NULL, *untaken_branch_target = NULL;
8986 if (branch_result == BRANCH_TAKEN) {
8987 taken_branch_target = bb->last_ins->inst_true_bb;
8988 untaken_branch_target = bb->last_ins->inst_false_bb;
8989 } else if (branch_result == BRANCH_NOT_TAKEN) {
8990 taken_branch_target = bb->last_ins->inst_false_bb;
8991 untaken_branch_target = bb->last_ins->inst_true_bb;
8993 if (taken_branch_target) {
8994 /* if mono_eval_cond_branch () is ever taken to handle
8995 * non-constant values to compare, issue a pop here.
8997 bb->last_ins->opcode = CEE_BR;
8998 bb->last_ins->inst_target_bb = taken_branch_target;
8999 replace_out_block (bb, untaken_branch_target, NULL);
9000 replace_in_block (untaken_branch_target, bb, NULL);
9004 bbn = bb->last_ins->inst_true_bb;
9005 if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
9006 bbn->code->inst_target_bb->region == bb->region) {
9007 if (cfg->verbose_level > 2)
9008 g_print ("cbranch1 to branch triggered %d -> (%d) %d (0x%02x)\n",
9009 bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num,
9013 * Unlink, then relink bblocks to avoid various
9014 * tricky situations when the two targets of the branch
9015 * are equal, or will become equal after the change.
9017 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_true_bb);
9018 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_false_bb);
9020 bb->last_ins->inst_true_bb = bbn->code->inst_target_bb;
9022 link_bblock (cfg, bb, bb->last_ins->inst_true_bb);
9023 link_bblock (cfg, bb, bb->last_ins->inst_false_bb);
9029 bbn = bb->last_ins->inst_false_bb;
9030 if (bb->region == bbn->region && bbn->code && bbn->code->opcode == CEE_BR &&
9031 bbn->code->inst_target_bb->region == bb->region) {
9032 if (cfg->verbose_level > 2)
9033 g_print ("cbranch2 to branch triggered %d -> (%d) %d (0x%02x)\n",
9034 bb->block_num, bbn->block_num, bbn->code->inst_target_bb->block_num,
9037 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_true_bb);
9038 mono_unlink_bblock (cfg, bb, bb->last_ins->inst_false_bb);
9040 bb->last_ins->inst_false_bb = bbn->code->inst_target_bb;
9042 link_bblock (cfg, bb, bb->last_ins->inst_true_bb);
9043 link_bblock (cfg, bb, bb->last_ins->inst_false_bb);
9050 /* detect and optimize to unsigned compares checks like: if (v < 0 || v > limit */
9051 if (bb->last_ins && bb->last_ins->opcode == CEE_BLT && bb->last_ins->inst_left->inst_right->opcode == OP_ICONST) {
9052 if (try_unsigned_compare (cfg, bb)) {
9053 /*g_print ("applied in bb %d (->%d) %s\n", bb->block_num, bb->last_ins->inst_target_bb->block_num, mono_method_full_name (cfg->method, TRUE));*/
9059 if (bb->last_ins && MONO_IS_COND_BRANCH_NOFP (bb->last_ins)) {
9060 if (bb->last_ins->inst_false_bb->out_of_line && (bb->region == bb->last_ins->inst_false_bb->region)) {
9061 /* Reverse the branch */
9062 bb->last_ins->opcode = reverse_branch_op (bb->last_ins->opcode);
9063 bbn = bb->last_ins->inst_false_bb;
9064 bb->last_ins->inst_false_bb = bb->last_ins->inst_true_bb;
9065 bb->last_ins->inst_true_bb = bbn;
9067 move_basic_block_to_end (cfg, bb->last_ins->inst_true_bb);
9068 if (cfg->verbose_level > 2)
9069 g_print ("cbranch to throw block triggered %d.\n",
9075 } while (changed && (niterations > 0));
9080 mono_compile_create_vars (MonoCompile *cfg)
9082 MonoMethodSignature *sig;
9083 MonoMethodHeader *header;
9086 header = mono_method_get_header (cfg->method);
9088 sig = mono_method_signature (cfg->method);
9090 if (!MONO_TYPE_IS_VOID (sig->ret)) {
9091 cfg->ret = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
9092 cfg->ret->opcode = OP_RETARG;
9093 cfg->ret->inst_vtype = sig->ret;
9094 cfg->ret->klass = mono_class_from_mono_type (sig->ret);
9096 if (cfg->verbose_level > 2)
9097 g_print ("creating vars\n");
9100 mono_compile_create_var (cfg, &cfg->method->klass->this_arg, OP_ARG);
9102 for (i = 0; i < sig->param_count; ++i) {
9103 mono_compile_create_var (cfg, sig->params [i], OP_ARG);
9104 if (sig->params [i]->byref) {
9105 cfg->disable_ssa = TRUE;
9109 cfg->locals_start = cfg->num_varinfo;
9111 if (cfg->verbose_level > 2)
9112 g_print ("creating locals\n");
9113 for (i = 0; i < header->num_locals; ++i)
9114 mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
9115 if (cfg->verbose_level > 2)
9116 g_print ("locals done\n");
9118 #ifdef MONO_ARCH_HAVE_CREATE_VARS
9119 mono_arch_create_vars (cfg);
9124 mono_print_code (MonoCompile *cfg)
9128 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9129 MonoInst *tree = bb->code;
9134 g_print ("CODE BLOCK %d (nesting %d):\n", bb->block_num, bb->nesting);
9136 for (; tree; tree = tree->next) {
9137 mono_print_tree (tree);
9142 bb->last_ins->next = NULL;
9146 extern const char * const mono_burg_rule_string [];
9149 emit_state (MonoCompile *cfg, MBState *state, int goal)
9152 int ern = mono_burg_rule (state, goal);
9153 const guint16 *nts = mono_burg_nts_data + mono_burg_nts [ern];
9156 //g_print ("rule: %s\n", mono_burg_rule_string [ern]);
9160 // state->reg1 = state->reg2; /* chain rule */
9162 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
9165 state->reg1 = mono_regstate_next_int (cfg->rs);
9166 //g_print ("alloc symbolic R%d (reg2: R%d) in block %d\n", state->reg1, state->reg2, cfg->cbb->block_num);
9169 state->reg1 = mono_regstate_next_int (cfg->rs);
9170 state->reg2 = mono_regstate_next_int (cfg->rs);
9173 state->reg1 = mono_regstate_next_float (cfg->rs);
9176 #ifdef MONO_ARCH_ENABLE_EMIT_STATE_OPT
9178 * Enabling this might cause bugs to surface in the local register
9179 * allocators on some architectures like x86.
9181 if ((state->tree->ssa_op == MONO_SSA_STORE) && (state->left->tree->opcode == OP_REGVAR)) {
9182 /* Do not optimize away reg-reg moves */
9183 if (! ((state->right->tree->ssa_op == MONO_SSA_LOAD) && (state->right->left->tree->opcode == OP_REGVAR))) {
9184 state->right->reg1 = state->left->tree->dreg;
9193 mono_burg_kids (state, ern, kids);
9195 emit_state (cfg, kids [0], nts [0]);
9197 emit_state (cfg, kids [1], nts [1]);
9199 g_assert (!nts [3]);
9200 emit_state (cfg, kids [2], nts [2]);
9205 // g_print ("emit: %s (%p)\n", mono_burg_rule_string [ern], state);
9206 if ((emit = mono_burg_func [ern]))
9207 emit (state, state->tree, cfg);
9210 #define DEBUG_SELECTION
9213 mini_select_instructions (MonoCompile *cfg)
9217 cfg->state_pool = mono_mempool_new ();
9218 cfg->rs = mono_regstate_new ();
9220 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9221 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
9222 bb->next_bb != bb->last_ins->inst_false_bb) {
9224 /* we are careful when inverting, since bugs like #59580
9225 * could show up when dealing with NaNs.
9227 if (MONO_IS_COND_BRANCH_NOFP(bb->last_ins) && bb->next_bb == bb->last_ins->inst_true_bb) {
9228 MonoBasicBlock *tmp = bb->last_ins->inst_true_bb;
9229 bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb;
9230 bb->last_ins->inst_false_bb = tmp;
9232 bb->last_ins->opcode = reverse_branch_op (bb->last_ins->opcode);
9234 MonoInst *inst = mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
9235 inst->opcode = CEE_BR;
9236 inst->inst_target_bb = bb->last_ins->inst_false_bb;
9237 mono_bblock_add_inst (bb, inst);
9242 #ifdef DEBUG_SELECTION
9243 if (cfg->verbose_level >= 4) {
9244 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9245 MonoInst *tree = bb->code;
9246 g_print ("DUMP BLOCK %d:\n", bb->block_num);
9249 for (; tree; tree = tree->next) {
9250 mono_print_tree (tree);
9257 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9258 MonoInst *tree = bb->code, *next;
9264 bb->last_ins = NULL;
9267 mono_regstate_reset (cfg->rs);
9269 #ifdef DEBUG_SELECTION
9270 if (cfg->verbose_level >= 3)
9271 g_print ("LABEL BLOCK %d:\n", bb->block_num);
9273 for (; tree; tree = next) {
9275 #ifdef DEBUG_SELECTION
9276 if (cfg->verbose_level >= 3) {
9277 mono_print_tree (tree);
9282 if (!(mbstate = mono_burg_label (tree, cfg))) {
9283 g_warning ("unable to label tree %p", tree);
9284 mono_print_tree (tree);
9286 g_assert_not_reached ();
9288 emit_state (cfg, mbstate, MB_NTERM_stmt);
9290 bb->max_ireg = cfg->rs->next_vireg;
9291 bb->max_freg = cfg->rs->next_vfreg;
9294 bb->last_ins->next = NULL;
9296 mono_mempool_empty (cfg->state_pool);
9298 mono_mempool_destroy (cfg->state_pool);
9302 mono_codegen (MonoCompile *cfg)
9304 MonoJumpInfo *patch_info;
9306 int i, max_epilog_size;
9309 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9310 cfg->spill_count = 0;
9311 /* we reuse dfn here */
9312 /* bb->dfn = bb_count++; */
9313 mono_arch_local_regalloc (cfg, bb);
9316 if (cfg->prof_options & MONO_PROFILE_COVERAGE)
9317 cfg->coverage_info = mono_profiler_coverage_alloc (cfg->method, cfg->num_bblocks);
9319 code = mono_arch_emit_prolog (cfg);
9321 if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE)
9322 code = mono_arch_instrument_prolog (cfg, mono_profiler_method_enter, code, FALSE);
9324 cfg->code_len = code - cfg->native_code;
9325 cfg->prolog_end = cfg->code_len;
9327 mono_debug_open_method (cfg);
9329 /* emit code all basic blocks */
9330 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9331 bb->native_offset = cfg->code_len;
9332 mono_arch_output_basic_block (cfg, bb);
9334 if (bb == cfg->bb_exit) {
9335 cfg->epilog_begin = cfg->code_len;
9337 if (cfg->prof_options & MONO_PROFILE_ENTER_LEAVE) {
9338 code = cfg->native_code + cfg->code_len;
9339 code = mono_arch_instrument_epilog (cfg, mono_profiler_method_leave, code, FALSE);
9340 cfg->code_len = code - cfg->native_code;
9343 mono_arch_emit_epilog (cfg);
9347 mono_arch_emit_exceptions (cfg);
9349 max_epilog_size = 0;
9351 code = cfg->native_code + cfg->code_len;
9353 /* we always allocate code in cfg->domain->code_mp to increase locality */
9354 cfg->code_size = cfg->code_len + max_epilog_size;
9355 /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
9357 if (cfg->method->dynamic) {
9358 /* Allocate the code into a separate memory pool so it can be freed */
9359 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
9360 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
9361 mono_domain_lock (cfg->domain);
9362 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
9363 mono_domain_unlock (cfg->domain);
9365 code = mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size);
9367 mono_domain_lock (cfg->domain);
9368 code = mono_code_manager_reserve (cfg->domain->code_mp, cfg->code_size);
9369 mono_domain_unlock (cfg->domain);
9372 memcpy (code, cfg->native_code, cfg->code_len);
9373 g_free (cfg->native_code);
9374 cfg->native_code = code;
9375 code = cfg->native_code + cfg->code_len;
9377 /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
9378 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
9379 switch (patch_info->type) {
9380 case MONO_PATCH_INFO_ABS: {
9381 MonoJitICallInfo *info = mono_find_jit_icall_by_addr (patch_info->data.target);
9383 //printf ("TEST %s %p\n", info->name, patch_info->data.target);
9384 if ((cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) &&
9385 strstr (cfg->method->name, info->name))
9387 * This is an icall wrapper, and this is a call to the
9392 /* for these array methods we currently register the same function pointer
9393 * since it's a vararg function. But this means that mono_find_jit_icall_by_addr ()
9394 * will return the incorrect one depending on the order they are registered.
9395 * See tests/test-arr.cs
9397 if (strstr (info->name, "ves_array_new_va_") == NULL && strstr (info->name, "ves_array_element_address_") == NULL) {
9398 patch_info->type = MONO_PATCH_INFO_INTERNAL_METHOD;
9399 patch_info->data.name = info->name;
9404 MonoVTable *vtable = mono_find_class_init_trampoline_by_addr (patch_info->data.target);
9406 patch_info->type = MONO_PATCH_INFO_CLASS_INIT;
9407 patch_info->data.klass = vtable->klass;
9412 case MONO_PATCH_INFO_SWITCH: {
9414 if (cfg->method->dynamic) {
9415 table = mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
9417 mono_domain_lock (cfg->domain);
9418 table = mono_code_manager_reserve (cfg->domain->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
9419 mono_domain_unlock (cfg->domain);
9422 if (!cfg->compile_aot)
9423 /* In the aot case, the patch already points to the correct location */
9424 patch_info->ip.i = patch_info->ip.label->inst_c0;
9425 for (i = 0; i < patch_info->data.table->table_size; i++) {
9426 table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
9428 patch_info->data.table->table = (MonoBasicBlock**)table;
9437 if (cfg->verbose_level > 0) {
9438 char* nm = mono_method_full_name (cfg->method, TRUE);
9439 g_print ("Method %s emitted at %p to %p (code length %d) [%s]\n",
9441 cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
9445 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
9446 mono_arch_save_unwind_info (cfg);
9449 mono_arch_patch_code (cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors);
9451 if (cfg->method->dynamic) {
9452 mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
9454 mono_domain_lock (cfg->domain);
9455 mono_code_manager_commit (cfg->domain->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
9456 mono_domain_unlock (cfg->domain);
9459 mono_arch_flush_icache (cfg->native_code, cfg->code_len);
9461 mono_debug_close_method (cfg);
9467 remove_critical_edges (MonoCompile *cfg) {
9469 MonoBasicBlock *previous_bb;
9471 if (cfg->verbose_level > 3) {
9472 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9474 printf ("remove_critical_edges %s, BEFORE BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
9475 for (i = 0; i < bb->in_count; i++) {
9476 printf (" %d", bb->in_bb [i]->block_num);
9479 for (i = 0; i < bb->out_count; i++) {
9480 printf (" %d", bb->out_bb [i]->block_num);
9483 if (bb->last_ins != NULL) {
9485 mono_print_tree (bb->last_ins);
9491 for (previous_bb = cfg->bb_entry, bb = previous_bb->next_bb; bb != NULL; previous_bb = previous_bb->next_bb, bb = bb->next_bb) {
9492 if (bb->in_count > 1) {
9494 for (in_bb_index = 0; in_bb_index < bb->in_count; in_bb_index++) {
9495 MonoBasicBlock *in_bb = bb->in_bb [in_bb_index];
9496 if (in_bb->out_count > 1) {
9497 MonoBasicBlock *new_bb = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
9498 new_bb->block_num = cfg->num_bblocks++;
9499 // new_bb->real_offset = bb->real_offset;
9500 new_bb->region = bb->region;
9502 /* Do not alter the CFG while altering the BB list */
9503 if (previous_bb->region == bb->region) {
9504 if (previous_bb != cfg->bb_entry) {
9505 /* If previous_bb "followed through" to bb, */
9506 /* keep it linked with a CEE_BR */
9507 if ((previous_bb->last_ins == NULL) ||
9508 ((previous_bb->last_ins->opcode != CEE_BR) &&
9509 (! (MONO_IS_COND_BRANCH_OP (previous_bb->last_ins))) &&
9510 (previous_bb->last_ins->opcode != CEE_SWITCH))) {
9512 /* Make sure previous_bb really falls through bb */
9513 for (i = 0; i < previous_bb->out_count; i++) {
9514 if (previous_bb->out_bb [i] == bb) {
9516 MONO_INST_NEW (cfg, jump, CEE_BR);
9517 MONO_ADD_INS (previous_bb, jump);
9518 jump->cil_code = previous_bb->cil_code;
9519 jump->inst_target_bb = bb;
9525 /* We cannot add any inst to the entry BB, so we must */
9526 /* put a new BB in the middle to hold the CEE_BR */
9528 MonoBasicBlock *new_bb_after_entry = mono_mempool_alloc0 ((cfg)->mempool, sizeof (MonoBasicBlock));
9529 new_bb_after_entry->block_num = cfg->num_bblocks++;
9530 // new_bb_after_entry->real_offset = bb->real_offset;
9531 new_bb_after_entry->region = bb->region;
9533 MONO_INST_NEW (cfg, jump, CEE_BR);
9534 MONO_ADD_INS (new_bb_after_entry, jump);
9535 jump->cil_code = bb->cil_code;
9536 jump->inst_target_bb = bb;
9538 previous_bb->next_bb = new_bb_after_entry;
9539 previous_bb = new_bb_after_entry;
9541 if (cfg->verbose_level > 2) {
9542 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);
9547 /* Insert new_bb in the BB list */
9548 previous_bb->next_bb = new_bb;
9549 new_bb->next_bb = bb;
9550 previous_bb = new_bb;
9552 /* Setup in_bb and out_bb */
9553 new_bb->in_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
9554 new_bb->in_bb [0] = in_bb;
9555 new_bb->in_count = 1;
9556 new_bb->out_bb = mono_mempool_alloc ((cfg)->mempool, sizeof (MonoBasicBlock*));
9557 new_bb->out_bb [0] = bb;
9558 new_bb->out_count = 1;
9560 /* Relink in_bb and bb to (from) new_bb */
9561 replace_out_block (in_bb, bb, new_bb);
9562 replace_out_block_in_code (in_bb, bb, new_bb);
9563 replace_in_block (bb, in_bb, new_bb);
9565 if (cfg->verbose_level > 2) {
9566 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);
9573 if (cfg->verbose_level > 3) {
9574 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
9576 printf ("remove_critical_edges %s, AFTER BB%d (in:", mono_method_full_name (cfg->method, TRUE), bb->block_num);
9577 for (i = 0; i < bb->in_count; i++) {
9578 printf (" %d", bb->in_bb [i]->block_num);
9581 for (i = 0; i < bb->out_count; i++) {
9582 printf (" %d", bb->out_bb [i]->block_num);
9585 if (bb->last_ins != NULL) {
9587 mono_print_tree (bb->last_ins);
9595 * mini_method_compile:
9596 * @method: the method to compile
9597 * @opts: the optimization flags to use
9598 * @domain: the domain where the method will be compiled in
9599 * @run_cctors: whether we should run type ctors if possible
9600 * @compile_aot: whether this is an AOT compilation
9601 * @parts: debug flag
9603 * Returns: a MonoCompile* pointer. Caller must check the exception_type
9604 * field in the returned struct to see if compilation succeded.
9607 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, gboolean run_cctors, gboolean compile_aot, int parts)
9609 MonoMethodHeader *header = mono_method_get_header (method);
9613 int dfn = 0, i, code_size_ratio;
9614 gboolean deadce_has_run = FALSE;
9616 mono_jit_stats.methods_compiled++;
9617 if (mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)
9618 mono_profiler_method_jit (method);
9620 cfg = g_new0 (MonoCompile, 1);
9621 cfg->method = method;
9622 cfg->mempool = mono_mempool_new ();
9624 cfg->prof_options = mono_profiler_get_events ();
9625 cfg->run_cctors = run_cctors;
9626 cfg->bb_hash = g_hash_table_new (NULL, NULL);
9627 cfg->domain = domain;
9628 cfg->verbose_level = mini_verbose;
9629 cfg->compile_aot = compile_aot;
9631 cfg->exception_type = MONO_EXCEPTION_INVALID_PROGRAM;
9632 cfg->exception_message = g_strdup_printf ("Missing or incorrect header for method %s", cfg->method->name);
9633 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
9634 mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
9638 ip = (guint8 *)header->code;
9640 cfg->intvars = mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * header->max_stack);
9641 cfg->aliasing_info = NULL;
9643 if (cfg->verbose_level > 2)
9644 g_print ("converting method %s\n", mono_method_full_name (method, TRUE));
9647 * create MonoInst* which represents arguments and local variables
9649 mono_compile_create_vars (cfg);
9651 if ((i = mono_method_to_ir (cfg, method, NULL, NULL, cfg->locals_start, NULL, NULL, NULL, 0, FALSE)) < 0) {
9652 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
9653 mono_profiler_method_end_jit (method, NULL, MONO_PROFILE_FAILED);
9654 /* cfg contains the details of the failure, so let the caller cleanup */
9658 mono_jit_stats.basic_blocks += cfg->num_bblocks;
9659 mono_jit_stats.max_basic_blocks = MAX (cfg->num_bblocks, mono_jit_stats.max_basic_blocks);
9661 if ((cfg->num_varinfo > 2000) && !mono_compile_aot) {
9663 * we disable some optimizations if there are too many variables
9664 * because JIT time may become too expensive. The actual number needs
9665 * to be tweaked and eventually the non-linear algorithms should be fixed.
9667 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
9668 cfg->disable_ssa = TRUE;
9671 /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
9673 if (cfg->opt & MONO_OPT_BRANCH)
9674 optimize_branches (cfg);
9676 if (cfg->opt & MONO_OPT_SSAPRE) {
9677 remove_critical_edges (cfg);
9680 /* Depth-first ordering on basic blocks */
9681 cfg->bblocks = mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
9683 df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
9684 if (cfg->num_bblocks != dfn + 1) {
9687 cfg->num_bblocks = dfn + 1;
9689 if (!header->clauses) {
9690 /* remove unreachable code, because the code in them may be
9691 * inconsistent (access to dead variables for example) */
9692 for (bb = cfg->bb_entry; bb;) {
9693 MonoBasicBlock *bbn = bb->next_bb;
9695 if (bbn && bbn->region == -1 && !bbn->dfn) {
9696 if (cfg->verbose_level > 1)
9697 g_print ("found unreachable code in BB%d\n", bbn->block_num);
9698 bb->next_bb = bbn->next_bb;
9699 nullify_basic_block (bbn);
9707 if (cfg->opt & MONO_OPT_LOOP) {
9708 mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM);
9709 mono_compute_natural_loops (cfg);
9712 /* after method_to_ir */
9716 //#define DEBUGSSA "logic_run"
9717 #define DEBUGSSA_CLASS "Tests"
9720 if (!header->num_clauses && !cfg->disable_ssa) {
9721 mono_local_cprop (cfg);
9722 mono_ssa_compute (cfg);
9726 /* fixme: add all optimizations which requires SSA */
9727 if (cfg->opt & (MONO_OPT_SSA | MONO_OPT_ABCREM | MONO_OPT_SSAPRE)) {
9728 if (!(cfg->comp_done & MONO_COMP_SSA) && !header->num_clauses && !cfg->disable_ssa) {
9729 mono_local_cprop (cfg);
9730 mono_ssa_compute (cfg);
9732 if (cfg->verbose_level >= 2) {
9739 /* after SSA translation */
9743 if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
9744 if (cfg->comp_done & MONO_COMP_SSA) {
9745 mono_ssa_cprop (cfg);
9747 mono_local_cprop (cfg);
9751 if (cfg->comp_done & MONO_COMP_SSA) {
9752 //mono_ssa_deadce (cfg);
9754 //mono_ssa_strength_reduction (cfg);
9756 if (cfg->opt & MONO_OPT_SSAPRE) {
9757 mono_perform_ssapre (cfg);
9758 //mono_local_cprop (cfg);
9761 if (cfg->opt & MONO_OPT_DEADCE) {
9762 mono_ssa_deadce (cfg);
9763 deadce_has_run = TRUE;
9766 if ((cfg->flags & MONO_CFG_HAS_LDELEMA) && (cfg->opt & MONO_OPT_ABCREM))
9767 mono_perform_abc_removal (cfg);
9769 mono_ssa_remove (cfg);
9771 if (cfg->opt & MONO_OPT_BRANCH)
9772 optimize_branches (cfg);
9775 /* after SSA removal */
9779 decompose_pass (cfg);
9784 g_assert (cfg->got_var_allocated);
9787 * Allways allocate the GOT var to a register, because keeping it
9788 * in memory will increase the number of live temporaries in some
9789 * code created by inssel.brg, leading to the well known spills+
9790 * branches problem. Testcase: mcs crash in
9791 * System.MonoCustomAttrs:GetCustomAttributes.
9793 regs = mono_arch_get_global_int_regs (cfg);
9795 cfg->got_var->opcode = OP_REGVAR;
9796 cfg->got_var->dreg = GPOINTER_TO_INT (regs->data);
9797 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
9802 if (cfg->opt & MONO_OPT_LINEARS) {
9805 /* For now, compute aliasing info only if needed for deadce... */
9806 if ((cfg->opt & MONO_OPT_DEADCE) && (! deadce_has_run) && (header->num_clauses == 0)) {
9807 cfg->aliasing_info = mono_build_aliasing_information (cfg);
9810 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
9811 cfg->comp_done &= ~MONO_COMP_LIVENESS;
9812 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
9813 mono_analyze_liveness (cfg);
9815 if (cfg->aliasing_info != NULL) {
9816 mono_aliasing_deadce (cfg->aliasing_info);
9817 deadce_has_run = TRUE;
9820 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
9821 regs = mono_arch_get_global_int_regs (cfg);
9823 regs = g_list_delete_link (regs, regs);
9824 mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs);
9827 if (cfg->aliasing_info != NULL) {
9828 mono_destroy_aliasing_information (cfg->aliasing_info);
9829 cfg->aliasing_info = NULL;
9833 //mono_print_code (cfg);
9837 /* variables are allocated after decompose, since decompose could create temps */
9838 mono_arch_allocate_vars (cfg);
9840 if (cfg->opt & MONO_OPT_CFOLD)
9841 mono_constant_fold (cfg);
9843 mini_select_instructions (cfg);
9846 if (cfg->verbose_level >= 2) {
9847 char *id = mono_method_full_name (cfg->method, FALSE);
9848 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
9852 if (cfg->method->dynamic) {
9853 jinfo = g_malloc0 (sizeof (MonoJitInfo) + (header->num_clauses * sizeof (MonoJitExceptionInfo)));
9855 /* we access cfg->domain->mp */
9856 mono_domain_lock (cfg->domain);
9857 jinfo = mono_mempool_alloc0 (cfg->domain->mp, sizeof (MonoJitInfo) + (header->num_clauses * sizeof (MonoJitExceptionInfo)));
9858 mono_domain_unlock (cfg->domain);
9861 jinfo->method = method;
9862 jinfo->code_start = cfg->native_code;
9863 jinfo->code_size = cfg->code_len;
9864 jinfo->used_regs = cfg->used_int_regs;
9865 jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
9866 jinfo->cas_inited = FALSE; /* initialization delayed at the first stalk walk using this method */
9868 if (header->num_clauses) {
9871 jinfo->num_clauses = header->num_clauses;
9873 for (i = 0; i < header->num_clauses; i++) {
9874 MonoExceptionClause *ec = &header->clauses [i];
9875 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
9876 MonoBasicBlock *tblock;
9879 ei->flags = ec->flags;
9881 exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
9882 ei->exvar_offset = exvar ? exvar->inst_offset : 0;
9884 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
9885 tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->data.filter_offset);
9887 ei->data.filter = cfg->native_code + tblock->native_offset;
9889 ei->data.catch_class = ec->data.catch_class;
9892 tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset);
9894 ei->try_start = cfg->native_code + tblock->native_offset;
9895 g_assert (tblock->native_offset);
9896 tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->try_offset + ec->try_len);
9898 ei->try_end = cfg->native_code + tblock->native_offset;
9899 g_assert (tblock->native_offset);
9900 tblock = g_hash_table_lookup (cfg->bb_hash, ip + ec->handler_offset);
9902 ei->handler_start = cfg->native_code + tblock->native_offset;
9906 cfg->jit_info = jinfo;
9907 #if defined(__arm__)
9908 mono_arch_fixup_jinfo (cfg);
9911 mono_domain_lock (cfg->domain);
9912 mono_jit_info_table_add (cfg->domain, jinfo);
9914 if (cfg->method->dynamic)
9915 mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = jinfo;
9916 mono_domain_unlock (cfg->domain);
9918 /* collect statistics */
9919 mono_jit_stats.allocated_code_size += cfg->code_len;
9920 code_size_ratio = cfg->code_len;
9921 if (code_size_ratio > mono_jit_stats.biggest_method_size) {
9922 mono_jit_stats.biggest_method_size = code_size_ratio;
9923 mono_jit_stats.biggest_method = method;
9925 code_size_ratio = (code_size_ratio * 100) / mono_method_get_header (method)->code_size;
9926 if (code_size_ratio > mono_jit_stats.max_code_size_ratio) {
9927 mono_jit_stats.max_code_size_ratio = code_size_ratio;
9928 mono_jit_stats.max_ratio_method = method;
9930 mono_jit_stats.native_code_size += cfg->code_len;
9932 if (cfg->prof_options & MONO_PROFILE_JIT_COMPILATION)
9933 mono_profiler_method_end_jit (method, jinfo, MONO_PROFILE_OK);
9939 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt)
9942 GHashTable *jit_code_hash;
9943 gpointer code = NULL;
9946 jit_code_hash = target_domain->jit_code_hash;
9948 method = mono_get_inflated_method (method);
9950 #ifdef MONO_USE_AOT_COMPILER
9951 if (!mono_compile_aot && (opt & MONO_OPT_AOT) && !(mono_profiler_get_events () & MONO_PROFILE_JIT_COMPILATION)) {
9953 MonoDomain *domain = mono_domain_get ();
9955 mono_domain_lock (domain);
9957 mono_class_init (method->klass);
9958 if ((info = mono_aot_get_method (domain, method))) {
9959 g_hash_table_insert (domain->jit_code_hash, method, info);
9960 mono_domain_unlock (domain);
9961 mono_runtime_class_init (mono_class_vtable (domain, method->klass));
9962 return info->code_start;
9965 mono_domain_unlock (domain);
9969 if ((method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) ||
9970 (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
9972 MonoMethodPInvoke* piinfo = (MonoMethodPInvoke *) method;
9974 if (method->iflags & METHOD_IMPL_ATTRIBUTE_NATIVE)
9975 g_error ("Method '%s' in assembly '%s' contains native code and mono can't run it. The assembly was probably created by Managed C++.\n", mono_method_full_name (method, TRUE), method->klass->image->name);
9977 if (!piinfo->addr) {
9978 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
9979 piinfo->addr = mono_lookup_internal_call (method);
9981 if (method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)
9982 mono_lookup_pinvoke_call (method, NULL, NULL);
9984 nm = mono_marshal_get_native_wrapper (method);
9985 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
9987 //if (mono_debug_format != MONO_DEBUG_FORMAT_NONE)
9988 //mono_debug_add_wrapper (method, nm);
9989 } else if ((method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME)) {
9990 const char *name = method->name;
9993 if (method->klass->parent == mono_defaults.multicastdelegate_class) {
9994 if (*name == '.' && (strcmp (name, ".ctor") == 0)) {
9995 MonoJitICallInfo *mi = mono_find_jit_icall_by_name ("mono_delegate_ctor");
9997 return mono_get_addr_from_ftnptr ((gpointer)mono_icall_get_wrapper (mi));
9998 } else if (*name == 'I' && (strcmp (name, "Invoke") == 0)) {
9999 nm = mono_marshal_get_delegate_invoke (method);
10000 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
10001 } else if (*name == 'B' && (strcmp (name, "BeginInvoke") == 0)) {
10002 nm = mono_marshal_get_delegate_begin_invoke (method);
10003 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
10004 } else if (*name == 'E' && (strcmp (name, "EndInvoke") == 0)) {
10005 nm = mono_marshal_get_delegate_end_invoke (method);
10006 return mono_get_addr_from_ftnptr (mono_compile_method (nm));
10012 cfg = mini_method_compile (method, opt, target_domain, TRUE, FALSE, 0);
10014 switch (cfg->exception_type) {
10015 case MONO_EXCEPTION_NONE: break;
10016 case MONO_EXCEPTION_TYPE_LOAD:
10017 case MONO_EXCEPTION_MISSING_FIELD:
10018 case MONO_EXCEPTION_MISSING_METHOD: {
10019 /* Throw a type load exception if needed */
10020 MonoLoaderError *error = mono_loader_get_last_error ();
10022 mono_destroy_compile (cfg);
10024 MonoException *ex = mini_loader_error_to_exception (error);
10025 mono_loader_clear_error ();
10026 mono_raise_exception (ex);
10028 g_assert_not_reached ();
10031 case MONO_EXCEPTION_INVALID_PROGRAM: {
10032 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", cfg->exception_message);
10033 mono_destroy_compile (cfg);
10034 mono_raise_exception (ex);
10037 case MONO_EXCEPTION_UNVERIFIABLE_IL: {
10038 MonoException *ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.Security", "VerificationException", cfg->exception_message);
10039 mono_destroy_compile (cfg);
10040 mono_raise_exception (ex);
10043 /* this can only be set if the security manager is active */
10044 case MONO_EXCEPTION_SECURITY_LINKDEMAND: {
10045 MonoAssembly *assembly = mono_image_get_assembly (method->klass->image);
10046 MonoReflectionAssembly *refass = (MonoReflectionAssembly*) mono_assembly_get_object (target_domain, assembly);
10047 MonoReflectionMethod *refmet = mono_method_get_object (target_domain, method, NULL);
10048 MonoSecurityManager* secman = mono_security_manager_get_methods ();
10049 MonoObject *exc = NULL;
10052 args [0] = &cfg->exception_data;
10055 mono_runtime_invoke (secman->linkdemandsecurityexception, NULL, args, &exc);
10057 mono_destroy_compile (cfg);
10060 mono_raise_exception ((MonoException*)exc);
10063 g_assert_not_reached ();
10066 mono_domain_lock (target_domain);
10068 /* Check if some other thread already did the job. In this case, we can
10069 discard the code this thread generated. */
10071 if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
10072 /* We can't use a domain specific method in another domain */
10073 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
10074 code = info->code_start;
10075 // printf("Discarding code for method %s\n", method->name);
10079 if (code == NULL) {
10080 g_hash_table_insert (jit_code_hash, method, cfg->jit_info);
10081 code = cfg->native_code;
10084 mono_destroy_compile (cfg);
10086 if (target_domain->jump_target_hash) {
10087 MonoJumpInfo patch_info;
10088 GSList *list, *tmp;
10089 list = g_hash_table_lookup (target_domain->jump_target_hash, method);
10091 patch_info.next = NULL;
10092 patch_info.ip.i = 0;
10093 patch_info.type = MONO_PATCH_INFO_METHOD_JUMP;
10094 patch_info.data.method = method;
10095 g_hash_table_remove (target_domain->jump_target_hash, method);
10097 for (tmp = list; tmp; tmp = tmp->next)
10098 mono_arch_patch_code (NULL, target_domain, tmp->data, &patch_info, TRUE);
10099 g_slist_free (list);
10102 mono_domain_unlock (target_domain);
10104 mono_runtime_class_init (mono_class_vtable (target_domain, method->klass));
10109 mono_jit_compile_method_with_opt (MonoMethod *method, guint32 opt)
10111 MonoDomain *target_domain, *domain = mono_domain_get ();
10114 MonoJitICallInfo *callinfo = NULL;
10117 * ICALL wrappers are handled specially, since there is only one copy of them
10118 * shared by all appdomains.
10120 if ((method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) && (strstr (method->name, "__icall_wrapper_") == method->name)) {
10121 const char *icall_name;
10123 icall_name = method->name + strlen ("__icall_wrapper_");
10124 g_assert (icall_name);
10125 callinfo = mono_find_jit_icall_by_name (icall_name);
10126 g_assert (callinfo);
10128 /* Must be domain neutral since there is only one copy */
10129 opt |= MONO_OPT_SHARED;
10132 if (opt & MONO_OPT_SHARED)
10133 target_domain = mono_get_root_domain ();
10135 target_domain = domain;
10137 mono_domain_lock (target_domain);
10139 if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
10140 /* We can't use a domain specific method in another domain */
10141 if (! ((domain != target_domain) && !info->domain_neutral)) {
10142 mono_domain_unlock (target_domain);
10143 mono_jit_stats.methods_lookups++;
10144 mono_runtime_class_init (mono_class_vtable (domain, method->klass));
10145 return mono_create_ftnptr (target_domain, info->code_start);
10149 mono_domain_unlock (target_domain);
10150 p = mono_create_ftnptr (target_domain, mono_jit_compile_method_inner (method, target_domain, opt));
10154 if (!callinfo->wrapper) {
10155 callinfo->wrapper = p;
10156 mono_register_jit_icall_wrapper (callinfo, p);
10157 mono_debug_add_icall_wrapper (method, callinfo);
10159 mono_jit_unlock ();
10166 mono_jit_compile_method (MonoMethod *method)
10168 return mono_jit_compile_method_with_opt (method, default_opt);
10172 invalidated_delegate_trampoline (char *desc)
10174 g_error ("Unmanaged code called delegate of type %s which was already garbage collected.\n"
10175 "See http://www.go-mono.com/delegate.html for an explanation and ways to fix this.",
10180 * mono_jit_free_method:
10182 * Free all memory allocated by the JIT for METHOD.
10185 mono_jit_free_method (MonoDomain *domain, MonoMethod *method)
10187 MonoJitDynamicMethodInfo *ji;
10188 gboolean destroy = TRUE;
10190 g_assert (method->dynamic);
10192 mono_domain_lock (domain);
10193 ji = mono_dynamic_code_hash_lookup (domain, method);
10194 mono_domain_unlock (domain);
10198 mono_domain_lock (domain);
10199 g_hash_table_remove (domain->dynamic_code_hash, method);
10200 g_hash_table_remove (domain->jit_code_hash, method);
10201 mono_domain_unlock (domain);
10203 #ifdef MONO_ARCH_HAVE_INVALIDATE_METHOD
10204 if (debug_options.keep_delegates && method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
10206 * Instead of freeing the code, change it to call an error routine
10207 * so people can fix their code.
10209 char *type = mono_type_full_name (&method->klass->byval_arg);
10210 char *type_and_method = g_strdup_printf ("%s.%s", type, method->name);
10213 mono_arch_invalidate_method (ji->ji, invalidated_delegate_trampoline, type_and_method);
10219 * This needs to be done before freeing code_mp, since the code address is the
10220 * key in the table, so if we the code_mp first, another thread can grab the
10221 * same code address and replace our entry in the table.
10223 mono_jit_info_table_remove (domain, ji->ji);
10226 mono_code_manager_destroy (ji->code_mp);
10232 mono_jit_find_compiled_method (MonoDomain *domain, MonoMethod *method)
10234 MonoDomain *target_domain;
10237 if (default_opt & MONO_OPT_SHARED)
10238 target_domain = mono_get_root_domain ();
10240 target_domain = domain;
10242 mono_domain_lock (target_domain);
10244 if ((info = g_hash_table_lookup (target_domain->jit_code_hash, method))) {
10245 /* We can't use a domain specific method in another domain */
10246 if (! ((domain != target_domain) && !info->domain_neutral)) {
10247 mono_domain_unlock (target_domain);
10248 mono_jit_stats.methods_lookups++;
10249 return info->code_start;
10253 mono_domain_unlock (target_domain);
10259 * mono_jit_runtime_invoke:
10260 * @method: the method to invoke
10261 * @obj: this pointer
10262 * @params: array of parameter values.
10263 * @exc: used to catch exceptions objects
10266 mono_jit_runtime_invoke (MonoMethod *method, void *obj, void **params, MonoObject **exc)
10268 MonoMethod *invoke;
10269 MonoObject *(*runtime_invoke) (MonoObject *this, void **params, MonoObject **exc, void* compiled_method);
10270 void* compiled_method;
10272 if (obj == NULL && !(method->flags & METHOD_ATTRIBUTE_STATIC) && !method->string_ctor && (method->wrapper_type == 0)) {
10273 g_warning ("Ignoring invocation of an instance method on a NULL instance.\n");
10277 method = mono_get_inflated_method (method);
10278 invoke = mono_marshal_get_runtime_invoke (method);
10279 runtime_invoke = mono_jit_compile_method (invoke);
10281 /* We need this here becuase mono_marshal_get_runtime_invoke can be place
10282 * the helper method in System.Object and not the target class
10284 mono_runtime_class_init (mono_class_vtable (mono_domain_get (), method->klass));
10286 compiled_method = mono_jit_compile_method (method);
10287 return runtime_invoke (obj, params, exc, compiled_method);
10290 #ifdef PLATFORM_WIN32
10291 #define GET_CONTEXT \
10292 struct sigcontext *ctx = (struct sigcontext*)_dummy;
10295 #define GET_CONTEXT \
10296 void *ctx = context;
10297 #elif defined(sun) // Solaris x86
10298 #define GET_CONTEXT \
10299 ucontext_t *uctx = context; \
10300 struct sigcontext *ctx = (struct sigcontext *)&(uctx->uc_mcontext);
10301 #elif defined (MONO_ARCH_USE_SIGACTION)
10302 #define GET_CONTEXT \
10303 void *ctx = context;
10305 #define GET_CONTEXT \
10306 void **_p = (void **)&_dummy; \
10307 struct sigcontext *ctx = (struct sigcontext *)++_p;
10311 #ifdef MONO_ARCH_USE_SIGACTION
10312 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy, siginfo_t *info, void *context)
10314 #define SIG_HANDLER_SIGNATURE(ftn) ftn (int _dummy)
10318 SIG_HANDLER_SIGNATURE (sigfpe_signal_handler)
10320 MonoException *exc = NULL;
10321 #ifndef MONO_ARCH_USE_SIGACTION
10326 #if defined(MONO_ARCH_HAVE_IS_INT_OVERFLOW)
10327 if (mono_arch_is_int_overflow (ctx, info))
10328 exc = mono_get_exception_arithmetic ();
10330 exc = mono_get_exception_divide_by_zero ();
10332 exc = mono_get_exception_divide_by_zero ();
10335 mono_arch_handle_exception (ctx, exc, FALSE);
10339 SIG_HANDLER_SIGNATURE (sigill_signal_handler)
10341 MonoException *exc;
10344 exc = mono_get_exception_execution_engine ("SIGILL");
10346 mono_arch_handle_exception (ctx, exc, FALSE);
10349 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
10351 #ifndef MONO_ARCH_USE_SIGACTION
10352 #error "Can't use sigaltstack without sigaction"
10358 SIG_HANDLER_SIGNATURE (sigsegv_signal_handler)
10360 MonoException *exc = NULL;
10363 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
10364 MonoJitTlsData *jit_tls = TlsGetValue (mono_jit_tls_id);
10368 #ifdef MONO_ARCH_USE_SIGACTION
10369 if (debug_options.collect_pagefault_stats) {
10370 if (mono_raw_buffer_is_pagefault (info->si_addr)) {
10371 mono_raw_buffer_handle_pagefault (info->si_addr);
10374 if (mono_aot_is_pagefault (info->si_addr)) {
10375 mono_aot_handle_pagefault (info->si_addr);
10381 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
10382 /* Can't allocate memory using Boehm GC on altstack */
10383 if (jit_tls->stack_size &&
10384 ((guint8*)info->si_addr >= (guint8*)jit_tls->end_of_stack - jit_tls->stack_size) &&
10385 ((guint8*)info->si_addr < (guint8*)jit_tls->end_of_stack))
10386 exc = mono_domain_get ()->stack_overflow_ex;
10388 exc = mono_domain_get ()->null_reference_ex;
10391 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
10393 mono_handle_native_sigsegv (ctx);
10396 mono_arch_handle_exception (ctx, exc, FALSE);
10400 SIG_HANDLER_SIGNATURE (sigusr1_signal_handler)
10402 gboolean running_managed;
10403 MonoException *exc;
10404 MonoThread *thread = mono_thread_current ();
10409 if (thread->thread_dump_requested) {
10410 thread->thread_dump_requested = FALSE;
10412 mono_print_thread_dump (ctx);
10417 * This is an async signal, so the code below must not call anything which
10418 * is not async safe. That includes the pthread locking functions. If we
10419 * know that we interrupted managed code, then locking is safe.
10421 ji = mono_jit_info_table_find (mono_domain_get (), mono_arch_ip_from_context(ctx));
10422 running_managed = ji != NULL;
10424 exc = mono_thread_request_interruption (running_managed);
10427 mono_arch_handle_exception (ctx, exc, FALSE);
10431 SIG_HANDLER_SIGNATURE (sigprof_signal_handler)
10435 mono_profiler_stat_hit (mono_arch_ip_from_context (ctx), ctx);
10439 SIG_HANDLER_SIGNATURE (sigquit_signal_handler)
10443 printf ("Full thread dump:\n");
10445 mono_threads_request_thread_dump ();
10448 * print_thread_dump () skips the current thread, since sending a signal
10449 * to it would invoke the signal handler below the sigquit signal handler,
10450 * and signal handlers don't create an lmf, so the stack walk could not
10453 mono_print_thread_dump (ctx);
10457 SIG_HANDLER_SIGNATURE (sigint_signal_handler)
10459 MonoException *exc;
10462 exc = mono_get_exception_execution_engine ("Interrupted (SIGINT).");
10464 mono_arch_handle_exception (ctx, exc, FALSE);
10468 SIG_HANDLER_SIGNATURE (sigusr2_signal_handler)
10470 gboolean enabled = mono_trace_is_enabled ();
10472 mono_trace_enable (!enabled);
10475 #ifndef PLATFORM_WIN32
10477 add_signal_handler (int signo, gpointer handler)
10479 struct sigaction sa;
10481 #ifdef MONO_ARCH_USE_SIGACTION
10482 sa.sa_sigaction = handler;
10483 sigemptyset (&sa.sa_mask);
10484 sa.sa_flags = SA_SIGINFO;
10486 sa.sa_handler = handler;
10487 sigemptyset (&sa.sa_mask);
10490 g_assert (sigaction (signo, &sa, NULL) != -1);
10495 mono_runtime_install_handlers (void)
10497 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
10498 struct sigaction sa;
10501 #ifdef PLATFORM_WIN32
10503 win32_seh_set_handler(SIGFPE, sigfpe_signal_handler);
10504 win32_seh_set_handler(SIGILL, sigill_signal_handler);
10505 win32_seh_set_handler(SIGSEGV, sigsegv_signal_handler);
10506 if (debug_options.handle_sigint)
10507 win32_seh_set_handler(SIGINT, sigint_signal_handler);
10509 #else /* !PLATFORM_WIN32 */
10511 /* libpthreads has its own implementation of sigaction(),
10512 * but it seems to work well with our current exception
10513 * handlers. If not we must call syscall directly instead
10516 if (debug_options.handle_sigint)
10517 add_signal_handler (SIGINT, sigint_signal_handler);
10519 add_signal_handler (SIGFPE, sigfpe_signal_handler);
10520 add_signal_handler (SIGQUIT, sigquit_signal_handler);
10521 add_signal_handler (SIGILL, sigill_signal_handler);
10522 add_signal_handler (SIGBUS, sigsegv_signal_handler);
10523 if (mono_jit_trace_calls != NULL)
10524 add_signal_handler (SIGUSR2, sigusr2_signal_handler);
10526 add_signal_handler (mono_thread_get_abort_signal (), sigusr1_signal_handler);
10527 signal (SIGPIPE, SIG_IGN);
10529 /* catch SIGSEGV */
10530 #ifdef MONO_ARCH_SIGSEGV_ON_ALTSTACK
10531 sa.sa_sigaction = sigsegv_signal_handler;
10532 sigemptyset (&sa.sa_mask);
10533 sa.sa_flags = SA_SIGINFO | SA_ONSTACK;
10534 g_assert (sigaction (SIGSEGV, &sa, NULL) != -1);
10536 add_signal_handler (SIGSEGV, sigsegv_signal_handler);
10539 #endif /* PLATFORM_WIN32 */
10543 #ifdef HAVE_LINUX_RTC_H
10544 #include <linux/rtc.h>
10545 #include <sys/ioctl.h>
10547 static int rtc_fd = -1;
10550 enable_rtc_timer (gboolean enable)
10553 flags = fcntl (rtc_fd, F_GETFL);
10555 perror ("getflags");
10562 if (fcntl (rtc_fd, F_SETFL, flags) == -1) {
10563 perror ("setflags");
10571 setup_stat_profiler (void)
10574 struct itimerval itval;
10575 static int inited = 0;
10576 #ifdef HAVE_LINUX_RTC_H
10577 const char *rtc_freq;
10578 if (!inited && (rtc_freq = g_getenv ("MONO_RTC"))) {
10582 freq = atoi (rtc_freq);
10585 rtc_fd = open ("/dev/rtc", O_RDONLY);
10586 if (rtc_fd == -1) {
10587 perror ("open /dev/rtc");
10590 add_signal_handler (SIGPROF, sigprof_signal_handler);
10591 if (ioctl (rtc_fd, RTC_IRQP_SET, freq) == -1) {
10592 perror ("set rtc freq");
10595 if (ioctl (rtc_fd, RTC_PIE_ON, 0) == -1) {
10596 perror ("start rtc");
10599 if (fcntl (rtc_fd, F_SETSIG, SIGPROF) == -1) {
10603 if (fcntl (rtc_fd, F_SETOWN, getpid ()) == -1) {
10607 enable_rtc_timer (TRUE);
10614 itval.it_interval.tv_usec = 999;
10615 itval.it_interval.tv_sec = 0;
10616 itval.it_value = itval.it_interval;
10617 setitimer (ITIMER_PROF, &itval, NULL);
10621 add_signal_handler (SIGPROF, sigprof_signal_handler);
10625 /* mono_jit_create_remoting_trampoline:
10626 * @method: pointer to the method info
10628 * Creates a trampoline which calls the remoting functions. This
10629 * is used in the vtable of transparent proxies.
10631 * Returns: a pointer to the newly created code
10634 mono_jit_create_remoting_trampoline (MonoMethod *method, MonoRemotingTarget target)
10637 guint8 *addr = NULL;
10639 if ((method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
10640 (mono_method_signature (method)->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class))) {
10641 nm = mono_marshal_get_remoting_invoke_for_target (method, target);
10642 addr = mono_compile_method (nm);
10644 addr = mono_compile_method (method);
10646 return mono_get_addr_from_ftnptr (addr);
10650 mini_parse_debug_options (void)
10652 char *options = getenv ("MONO_DEBUG");
10653 gchar **args, **ptr;
10658 args = g_strsplit (options, ",", -1);
10660 for (ptr = args; ptr && *ptr; ptr++) {
10661 const char *arg = *ptr;
10663 if (!strcmp (arg, "handle-sigint"))
10664 debug_options.handle_sigint = TRUE;
10665 else if (!strcmp (arg, "keep-delegates"))
10666 debug_options.keep_delegates = TRUE;
10667 else if (!strcmp (arg, "collect-pagefault-stats"))
10668 debug_options.collect_pagefault_stats = TRUE;
10670 fprintf (stderr, "Invalid option for the MONO_DEBUG env variable: %s\n", arg);
10671 fprintf (stderr, "Available options: 'handle-sigint', 'keep-delegates', 'collect-pagefault-stats'\n");
10678 mini_init (const char *filename)
10680 MonoDomain *domain;
10682 /* Happens when using the embedding interface */
10683 if (default_opt == 0)
10684 default_opt = mono_parse_default_optimizations (NULL);
10686 InitializeCriticalSection (&jit_mutex);
10688 global_codeman = mono_code_manager_new ();
10689 jit_icall_name_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
10691 mono_arch_cpu_init ();
10693 mono_init_trampolines ();
10695 mono_init_exceptions ();
10697 if (!g_thread_supported ())
10698 g_thread_init (NULL);
10700 if (getenv ("MONO_DEBUG") != NULL)
10701 mini_parse_debug_options ();
10704 * Handle the case when we are called from a thread different from the main thread,
10706 * FIXME: Move this to libgc where it belongs.
10708 * we used to do this only when running on valgrind,
10709 * but it happens also in other setups.
10711 #if defined(HAVE_BOEHM_GC)
10712 #if defined(HAVE_PTHREAD_GETATTR_NP) && defined(HAVE_PTHREAD_ATTR_GETSTACK)
10716 pthread_attr_t attr;
10717 pthread_getattr_np (pthread_self (), &attr);
10718 pthread_attr_getstack (&attr, &sstart, &size);
10719 /*g_print ("stackbottom pth is: %p\n", (char*)sstart + size);*/
10722 * The calculation above doesn't seem to work on ia64, also we need to set
10723 * GC_register_stackbottom as well, but don't know how.
10726 GC_stackbottom = (char*)sstart + size;
10729 #elif defined(HAVE_PTHREAD_GET_STACKSIZE_NP) && defined(HAVE_PTHREAD_GET_STACKADDR_NP)
10730 GC_stackbottom = (char*)pthread_get_stackaddr_np (pthread_self ());
10733 gsize stack_bottom = (gsize)&domain;
10734 stack_bottom += 4095;
10735 stack_bottom &= ~4095;
10736 /*g_print ("stackbottom is: %p\n", (char*)stack_bottom);*/
10737 GC_stackbottom = (char*)stack_bottom;
10741 MONO_GC_PRE_INIT ();
10743 mono_jit_tls_id = TlsAlloc ();
10744 setup_jit_tls_data ((gpointer)-1, mono_thread_abort);
10748 if (default_opt & MONO_OPT_AOT)
10751 mono_runtime_install_handlers ();
10752 mono_threads_install_cleanup (mini_thread_cleanup);
10754 #define JIT_TRAMPOLINES_WORK
10755 #ifdef JIT_TRAMPOLINES_WORK
10756 mono_install_compile_method (mono_jit_compile_method);
10757 mono_install_free_method (mono_jit_free_method);
10758 mono_install_trampoline (mono_create_jit_trampoline);
10759 mono_install_remoting_trampoline (mono_jit_create_remoting_trampoline);
10760 mono_install_delegate_trampoline (mono_create_delegate_trampoline);
10762 #define JIT_INVOKE_WORKS
10763 #ifdef JIT_INVOKE_WORKS
10764 mono_install_runtime_invoke (mono_jit_runtime_invoke);
10765 mono_install_handler (mono_arch_get_throw_exception ());
10767 mono_install_stack_walk (mono_jit_walk_stack);
10768 mono_install_init_vtable (mono_aot_init_vtable);
10769 mono_install_get_cached_class_info (mono_aot_get_cached_class_info);
10770 mono_install_jit_info_find_in_aot (mono_aot_find_jit_info);
10772 if (debug_options.collect_pagefault_stats) {
10773 mono_raw_buffer_set_make_unreadable (TRUE);
10774 mono_aot_set_make_unreadable (TRUE);
10777 domain = mono_init_from_assembly (filename, filename);
10778 mono_icall_init ();
10780 mono_add_internal_call ("System.Diagnostics.StackFrame::get_frame_info",
10781 ves_icall_get_frame_info);
10782 mono_add_internal_call ("System.Diagnostics.StackTrace::get_trace",
10783 ves_icall_get_trace);
10784 mono_add_internal_call ("System.Exception::get_trace",
10785 ves_icall_System_Exception_get_trace);
10786 mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityFrame",
10787 ves_icall_System_Security_SecurityFrame_GetSecurityFrame);
10788 mono_add_internal_call ("System.Security.SecurityFrame::_GetSecurityStack",
10789 ves_icall_System_Security_SecurityFrame_GetSecurityStack);
10790 mono_add_internal_call ("Mono.Runtime::mono_runtime_install_handlers",
10791 mono_runtime_install_handlers);
10794 create_helper_signature ();
10796 #define JIT_CALLS_WORK
10797 #ifdef JIT_CALLS_WORK
10798 /* Needs to be called here since register_jit_icall depends on it */
10799 mono_marshal_init ();
10801 mono_arch_register_lowlevel_calls ();
10802 register_icall (mono_profiler_method_enter, "mono_profiler_method_enter", NULL, TRUE);
10803 register_icall (mono_profiler_method_leave, "mono_profiler_method_leave", NULL, TRUE);
10804 register_icall (mono_trace_enter_method, "mono_trace_enter_method", NULL, TRUE);
10805 register_icall (mono_trace_leave_method, "mono_trace_leave_method", NULL, TRUE);
10806 register_icall (mono_get_lmf_addr, "mono_get_lmf_addr", "ptr", TRUE);
10807 register_icall (mono_jit_thread_attach, "mono_jit_thread_attach", "void", TRUE);
10808 register_icall (mono_domain_get, "mono_domain_get", "ptr", TRUE);
10810 register_icall (mono_arch_get_throw_exception (), "mono_arch_throw_exception", "void object", TRUE);
10811 register_icall (mono_arch_get_rethrow_exception (), "mono_arch_rethrow_exception", "void object", TRUE);
10812 register_icall (mono_arch_get_throw_exception_by_name (), "mono_arch_throw_exception_by_name", "void ptr", TRUE);
10813 #if MONO_ARCH_HAVE_THROW_CORLIB_EXCEPTION
10814 register_icall (mono_arch_get_throw_corlib_exception (), "mono_arch_throw_corlib_exception",
10817 register_icall (mono_thread_get_pending_exception, "mono_thread_get_pending_exception", "object", FALSE);
10818 register_icall (mono_thread_interruption_checkpoint, "mono_thread_interruption_checkpoint", "void", FALSE);
10819 register_icall (mono_thread_force_interruption_checkpoint, "mono_thread_force_interruption_checkpoint", "void", FALSE);
10820 register_icall (mono_load_remote_field_new, "mono_load_remote_field_new", "object object ptr ptr", FALSE);
10821 register_icall (mono_store_remote_field_new, "mono_store_remote_field_new", "void object ptr ptr object", FALSE);
10824 * NOTE, NOTE, NOTE, NOTE:
10825 * when adding emulation for some opcodes, remember to also add a dummy
10826 * rule to the burg files, because we need the arity information to be correct.
10828 #ifndef MONO_ARCH_NO_EMULATE_LONG_MUL_OPTS
10829 mono_register_opcode_emulation (OP_LMUL, "__emul_lmul", "long long long", mono_llmult, TRUE);
10830 mono_register_opcode_emulation (OP_LDIV, "__emul_ldiv", "long long long", mono_lldiv, FALSE);
10831 mono_register_opcode_emulation (OP_LDIV_UN, "__emul_ldiv_un", "long long long", mono_lldiv_un, FALSE);
10832 mono_register_opcode_emulation (OP_LREM, "__emul_lrem", "long long long", mono_llrem, FALSE);
10833 mono_register_opcode_emulation (OP_LREM_UN, "__emul_lrem_un", "long long long", mono_llrem_un, FALSE);
10834 mono_register_opcode_emulation (OP_LMUL_OVF_UN, "__emul_lmul_ovf_un", "long long long", mono_llmult_ovf_un, FALSE);
10835 mono_register_opcode_emulation (OP_LMUL_OVF, "__emul_lmul_ovf", "long long long", mono_llmult_ovf, FALSE);
10838 #ifndef MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS
10839 mono_register_opcode_emulation (OP_LSHL, "__emul_lshl", "long long int32", mono_lshl, TRUE);
10840 mono_register_opcode_emulation (OP_LSHR, "__emul_lshr", "long long int32", mono_lshr, TRUE);
10841 mono_register_opcode_emulation (OP_LSHR_UN, "__emul_lshr_un", "long long int32", mono_lshr_un, TRUE);
10844 #if defined(MONO_ARCH_EMULATE_MUL_DIV) || defined(MONO_ARCH_EMULATE_DIV)
10845 mono_register_opcode_emulation (CEE_DIV, "__emul_idiv", "int32 int32 int32", mono_idiv, TRUE);
10846 mono_register_opcode_emulation (CEE_DIV_UN, "__emul_idiv_un", "int32 int32 int32", mono_idiv_un, TRUE);
10847 mono_register_opcode_emulation (CEE_REM, "__emul_irem", "int32 int32 int32", mono_irem, TRUE);
10848 mono_register_opcode_emulation (CEE_REM_UN, "__emul_irem_un", "int32 int32 int32", mono_irem_un, TRUE);
10851 #ifdef MONO_ARCH_EMULATE_MUL_DIV
10852 mono_register_opcode_emulation (CEE_MUL_OVF, "__emul_imul_ovf", "int32 int32 int32", mono_imul_ovf, TRUE);
10853 mono_register_opcode_emulation (CEE_MUL_OVF_UN, "__emul_imul_ovf_un", "int32 int32 int32", mono_imul_ovf_un, TRUE);
10854 mono_register_opcode_emulation (CEE_MUL, "__emul_imul", "int32 int32 int32", mono_imul, TRUE);
10855 mono_register_opcode_emulation (OP_FDIV, "__emul_fdiv", "double double double", mono_fdiv, TRUE);
10858 mono_register_opcode_emulation (OP_FCONV_TO_U8, "__emul_fconv_to_u8", "ulong double", mono_fconv_u8, FALSE);
10859 mono_register_opcode_emulation (OP_FCONV_TO_U4, "__emul_fconv_to_u4", "uint32 double", mono_fconv_u4, FALSE);
10860 mono_register_opcode_emulation (OP_FCONV_TO_OVF_I8, "__emul_fconv_to_ovf_i8", "long double", mono_fconv_ovf_i8, FALSE);
10861 mono_register_opcode_emulation (OP_FCONV_TO_OVF_U8, "__emul_fconv_to_ovf_u8", "ulong double", mono_fconv_ovf_u8, FALSE);
10863 #ifdef MONO_ARCH_EMULATE_FCONV_TO_I8
10864 mono_register_opcode_emulation (OP_FCONV_TO_I8, "__emul_fconv_to_i8", "long double", mono_fconv_i8, FALSE);
10866 #ifdef MONO_ARCH_EMULATE_CONV_R8_UN
10867 mono_register_opcode_emulation (CEE_CONV_R_UN, "__emul_conv_r_un", "double int32", mono_conv_to_r8_un, FALSE);
10869 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8
10870 mono_register_opcode_emulation (OP_LCONV_TO_R8, "__emul_lconv_to_r8", "double long", mono_lconv_to_r8, FALSE);
10872 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R4
10873 mono_register_opcode_emulation (OP_LCONV_TO_R4, "__emul_lconv_to_r4", "float long", mono_lconv_to_r4, FALSE);
10875 #ifdef MONO_ARCH_EMULATE_LCONV_TO_R8_UN
10876 mono_register_opcode_emulation (OP_LCONV_TO_R_UN, "__emul_lconv_to_r8_un", "double long", mono_lconv_to_r8_un, FALSE);
10878 #ifdef MONO_ARCH_EMULATE_FREM
10879 mono_register_opcode_emulation (OP_FREM, "__emul_frem", "double double double", fmod, FALSE);
10882 #if SIZEOF_VOID_P == 4
10883 mono_register_opcode_emulation (OP_FCONV_TO_U, "__emul_fconv_to_u", "uint32 double", mono_fconv_u4, TRUE);
10886 /* other jit icalls */
10887 register_icall (mono_delegate_ctor, "mono_delegate_ctor", "void object object ptr", FALSE);
10888 register_icall (mono_class_static_field_address , "mono_class_static_field_address",
10889 "ptr ptr ptr", FALSE);
10890 register_icall (mono_ldtoken_wrapper, "mono_ldtoken_wrapper", "ptr ptr ptr ptr", FALSE);
10891 register_icall (mono_get_special_static_data, "mono_get_special_static_data", "ptr int", FALSE);
10892 register_icall (mono_ldstr, "mono_ldstr", "object ptr ptr int32", FALSE);
10893 register_icall (helper_stelem_ref, "helper_stelem_ref", "void ptr int32 object", FALSE);
10894 register_icall (helper_stelem_ref_check, "helper_stelem_ref_check", "void object object", FALSE);
10895 register_icall (mono_object_new, "mono_object_new", "object ptr ptr", FALSE);
10896 register_icall (mono_object_new_specific, "mono_object_new_specific", "object ptr", FALSE);
10897 register_icall (mono_array_new, "mono_array_new", "object ptr ptr int32", FALSE);
10898 register_icall (mono_array_new_specific, "mono_array_new_specific", "object ptr int32", FALSE);
10899 register_icall (mono_runtime_class_init, "mono_runtime_class_init", "void ptr", FALSE);
10900 register_icall (mono_ldftn, "mono_ldftn", "ptr ptr", FALSE);
10901 register_icall (mono_ldftn_nosync, "mono_ldftn_nosync", "ptr ptr", FALSE);
10902 register_icall (mono_ldvirtfn, "mono_ldvirtfn", "ptr object ptr", FALSE);
10903 register_icall (helper_compile_generic_method, "compile_generic_method", "ptr object ptr ptr", FALSE);
10904 register_icall (helper_ldstr, "helper_ldstr", "object ptr int", FALSE);
10907 #define JIT_RUNTIME_WORKS
10908 #ifdef JIT_RUNTIME_WORKS
10909 mono_install_runtime_cleanup ((MonoDomainFunc)mini_cleanup);
10910 mono_runtime_init (domain, mono_thread_start_cb, mono_thread_attach_cb);
10913 mono_thread_attach (domain);
10917 MonoJitStats mono_jit_stats = {0};
10920 print_jit_stats (void)
10922 if (mono_jit_stats.enabled) {
10923 g_print ("Mono Jit statistics\n");
10924 g_print ("Compiled methods: %ld\n", mono_jit_stats.methods_compiled);
10925 g_print ("Methods from AOT: %ld\n", mono_jit_stats.methods_aot);
10926 g_print ("Methods cache lookup: %ld\n", mono_jit_stats.methods_lookups);
10927 g_print ("Method trampolines: %ld\n", mono_jit_stats.method_trampolines);
10928 g_print ("Basic blocks: %ld\n", mono_jit_stats.basic_blocks);
10929 g_print ("Max basic blocks: %ld\n", mono_jit_stats.max_basic_blocks);
10930 g_print ("Allocated vars: %ld\n", mono_jit_stats.allocate_var);
10931 g_print ("Analyze stack repeat: %ld\n", mono_jit_stats.analyze_stack_repeat);
10932 g_print ("Compiled CIL code size: %ld\n", mono_jit_stats.cil_code_size);
10933 g_print ("Native code size: %ld\n", mono_jit_stats.native_code_size);
10934 g_print ("Max code size ratio: %.2f (%s::%s)\n", mono_jit_stats.max_code_size_ratio/100.0,
10935 mono_jit_stats.max_ratio_method->klass->name, mono_jit_stats.max_ratio_method->name);
10936 g_print ("Biggest method: %ld (%s::%s)\n", mono_jit_stats.biggest_method_size,
10937 mono_jit_stats.biggest_method->klass->name, mono_jit_stats.biggest_method->name);
10938 g_print ("Code reallocs: %ld\n", mono_jit_stats.code_reallocs);
10939 g_print ("Allocated code size: %ld\n", mono_jit_stats.allocated_code_size);
10940 g_print ("Inlineable methods: %ld\n", mono_jit_stats.inlineable_methods);
10941 g_print ("Inlined methods: %ld\n", mono_jit_stats.inlined_methods);
10943 g_print ("\nCreated object count: %ld\n", mono_stats.new_object_count);
10944 g_print ("Initialized classes: %ld\n", mono_stats.initialized_class_count);
10945 g_print ("Used classes: %ld\n", mono_stats.used_class_count);
10946 g_print ("Static data size: %ld\n", mono_stats.class_static_data_size);
10947 g_print ("VTable data size: %ld\n", mono_stats.class_vtable_size);
10949 g_print ("\nGeneric instances: %ld\n", mono_stats.generic_instance_count);
10950 g_print ("Initialized classes: %ld\n", mono_stats.generic_class_count);
10951 g_print ("Inflated methods: %ld / %ld\n", mono_stats.inflated_method_count_2,
10952 mono_stats.inflated_method_count);
10953 g_print ("Inflated types: %ld\n", mono_stats.inflated_type_count);
10954 g_print ("Generics metadata size: %ld\n", mono_stats.generics_metadata_size);
10956 if (mono_use_security_manager) {
10957 g_print ("\nDecl security check : %ld\n", mono_jit_stats.cas_declsec_check);
10958 g_print ("LinkDemand (user) : %ld\n", mono_jit_stats.cas_linkdemand);
10959 g_print ("LinkDemand (icall) : %ld\n", mono_jit_stats.cas_linkdemand_icall);
10960 g_print ("LinkDemand (pinvoke) : %ld\n", mono_jit_stats.cas_linkdemand_pinvoke);
10961 g_print ("LinkDemand (aptc) : %ld\n", mono_jit_stats.cas_linkdemand_aptc);
10962 g_print ("Demand (code gen) : %ld\n", mono_jit_stats.cas_demand_generation);
10964 if (debug_options.collect_pagefault_stats) {
10965 g_print ("Metadata pagefaults : %d\n", mono_raw_buffer_get_n_pagefaults ());
10966 g_print ("AOT pagefaults : %d\n", mono_aot_get_n_pagefaults ());
10972 mini_cleanup (MonoDomain *domain)
10974 #ifdef HAVE_LINUX_RTC_H
10976 enable_rtc_timer (FALSE);
10980 * mono_runtime_cleanup() and mono_domain_finalize () need to
10981 * be called early since they need the execution engine still
10982 * fully working (mono_domain_finalize may invoke managed finalizers
10983 * and mono_runtime_cleanup will wait for other threads to finish).
10985 mono_domain_finalize (domain, 2000);
10987 mono_runtime_cleanup (domain);
10989 mono_profiler_shutdown ();
10991 mono_debug_cleanup ();
10993 mono_icall_cleanup ();
10995 #ifdef PLATFORM_WIN32
10996 win32_seh_cleanup();
10999 mono_domain_free (domain, TRUE);
11001 mono_code_manager_destroy (global_codeman);
11002 g_hash_table_destroy (jit_icall_name_hash);
11003 if (class_init_hash_addr)
11004 g_hash_table_destroy (class_init_hash_addr);
11006 print_jit_stats ();
11007 mono_counters_dump (-1, stdout);
11011 mono_set_defaults (int verbose_level, guint32 opts)
11013 mini_verbose = verbose_level;
11014 default_opt = opts;
11018 mono_precompile_assembly (MonoAssembly *ass, void *user_data)
11020 GHashTable *assemblies = (GHashTable*)user_data;
11021 MonoImage *image = mono_assembly_get_image (ass);
11022 MonoMethod *method, *invoke;
11025 if (g_hash_table_lookup (assemblies, ass))
11028 g_hash_table_insert (assemblies, ass, ass);
11030 if (mini_verbose > 0)
11031 printf ("PRECOMPILE: %s.\n", mono_image_get_filename (image));
11033 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_METHOD); ++i) {
11034 method = mono_get_method (image, MONO_TOKEN_METHOD_DEF | (i + 1), NULL);
11035 if (method->flags & METHOD_ATTRIBUTE_ABSTRACT)
11039 if (mini_verbose > 1) {
11040 char * desc = mono_method_full_name (method, TRUE);
11041 g_print ("Compiling %d %s\n", count, desc);
11044 mono_compile_method (method);
11045 if (strcmp (method->name, "Finalize") == 0) {
11046 invoke = mono_marshal_get_runtime_invoke (method);
11047 mono_compile_method (invoke);
11049 if (method->klass->marshalbyref && mono_method_signature (method)->hasthis) {
11050 invoke = mono_marshal_get_remoting_invoke_with_check (method);
11051 mono_compile_method (invoke);
11055 /* Load and precompile referenced assemblies as well */
11056 for (i = 0; i < mono_image_get_table_rows (image, MONO_TABLE_ASSEMBLYREF); ++i) {
11057 mono_assembly_load_reference (image, i);
11058 if (image->references [i])
11059 mono_precompile_assembly (image->references [i], assemblies);
11063 void mono_precompile_assemblies ()
11065 GHashTable *assemblies = g_hash_table_new (NULL, NULL);
11067 mono_assembly_foreach ((GFunc)mono_precompile_assembly, assemblies);
11069 g_hash_table_destroy (assemblies);