[Sockets]: Always reset internal SAEA completion when reattempting connection in...
[mono-project.git] / mono / mini / mini.c
blob75c3eef0312e4e1f8a13468c1926654bc27784bb
1 /**
2 * \file
3 * The new Mono code generator.
5 * Authors:
6 * Paolo Molaro (lupus@ximian.com)
7 * Dietmar Maurer (dietmar@ximian.com)
9 * Copyright 2002-2003 Ximian, Inc.
10 * Copyright 2003-2010 Novell, Inc.
11 * Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
12 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
15 #include <config.h>
16 #ifdef HAVE_ALLOCA_H
17 #include <alloca.h>
18 #endif
19 #ifdef HAVE_UNISTD_H
20 #include <unistd.h>
21 #endif
22 #include <math.h>
23 #ifdef HAVE_SYS_TIME_H
24 #include <sys/time.h>
25 #endif
27 #include <mono/utils/memcheck.h>
29 #include <mono/metadata/assembly.h>
30 #include <mono/metadata/loader.h>
31 #include <mono/metadata/tabledefs.h>
32 #include <mono/metadata/class.h>
33 #include <mono/metadata/object.h>
34 #include <mono/metadata/tokentype.h>
35 #include <mono/metadata/tabledefs.h>
36 #include <mono/metadata/threads.h>
37 #include <mono/metadata/appdomain.h>
38 #include <mono/metadata/debug-helpers.h>
39 #include <mono/metadata/profiler-private.h>
40 #include <mono/metadata/mono-config.h>
41 #include <mono/metadata/environment.h>
42 #include <mono/metadata/mono-debug.h>
43 #include <mono/metadata/gc-internals.h>
44 #include <mono/metadata/threads-types.h>
45 #include <mono/metadata/verify.h>
46 #include <mono/metadata/verify-internals.h>
47 #include <mono/metadata/mempool-internals.h>
48 #include <mono/metadata/attach.h>
49 #include <mono/metadata/runtime.h>
50 #include <mono/metadata/attrdefs.h>
51 #include <mono/utils/mono-math.h>
52 #include <mono/utils/mono-compiler.h>
53 #include <mono/utils/mono-counters.h>
54 #include <mono/utils/mono-error-internals.h>
55 #include <mono/utils/mono-logger-internals.h>
56 #include <mono/utils/mono-mmap.h>
57 #include <mono/utils/mono-path.h>
58 #include <mono/utils/mono-tls.h>
59 #include <mono/utils/mono-hwcap.h>
60 #include <mono/utils/dtrace.h>
61 #include <mono/utils/mono-threads.h>
62 #include <mono/utils/mono-threads-coop.h>
63 #include <mono/utils/unlocked.h>
64 #include <mono/utils/mono-time.h>
66 #include "mini.h"
67 #include "seq-points.h"
68 #include "tasklets.h"
69 #include <string.h>
70 #include <ctype.h>
71 #include "trace.h"
72 #include "version.h"
73 #include "ir-emit.h"
75 #include "jit-icalls.h"
77 #include "mini-gc.h"
78 #include "debugger-agent.h"
79 #include "llvm-runtime.h"
80 #include "mini-llvm.h"
81 #include "lldb.h"
82 #include "aot-runtime.h"
83 #include "mini-runtime.h"
85 MonoCallSpec *mono_jit_trace_calls;
86 MonoMethodDesc *mono_inject_async_exc_method;
87 int mono_inject_async_exc_pos;
88 MonoMethodDesc *mono_break_at_bb_method;
89 int mono_break_at_bb_bb_num;
90 gboolean mono_do_x86_stack_align = TRUE;
91 gboolean mono_using_xdebug;
93 /* Counters */
94 static guint32 discarded_code;
95 static gint64 discarded_jit_time;
96 static guint32 jinfo_try_holes_size;
98 #define mono_jit_lock() mono_os_mutex_lock (&jit_mutex)
99 #define mono_jit_unlock() mono_os_mutex_unlock (&jit_mutex)
100 static mono_mutex_t jit_mutex;
102 #ifndef DISABLE_JIT
103 static MonoBackend *current_backend;
105 gpointer
106 mono_realloc_native_code (MonoCompile *cfg)
108 return g_realloc (cfg->native_code, cfg->code_size);
111 typedef struct {
112 MonoExceptionClause *clause;
113 MonoBasicBlock *basic_block;
114 int start_offset;
115 } TryBlockHole;
118 * mono_emit_unwind_op:
120 * Add an unwind op with the given parameters for the list of unwind ops stored in
121 * cfg->unwind_ops.
123 void
124 mono_emit_unwind_op (MonoCompile *cfg, int when, int tag, int reg, int val)
126 MonoUnwindOp *op = (MonoUnwindOp *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoUnwindOp));
128 op->op = tag;
129 op->reg = reg;
130 op->val = val;
131 op->when = when;
133 cfg->unwind_ops = g_slist_append_mempool (cfg->mempool, cfg->unwind_ops, op);
134 if (cfg->verbose_level > 1) {
135 switch (tag) {
136 case DW_CFA_def_cfa:
137 printf ("CFA: [%x] def_cfa: %s+0x%x\n", when, mono_arch_regname (reg), val);
138 break;
139 case DW_CFA_def_cfa_register:
140 printf ("CFA: [%x] def_cfa_reg: %s\n", when, mono_arch_regname (reg));
141 break;
142 case DW_CFA_def_cfa_offset:
143 printf ("CFA: [%x] def_cfa_offset: 0x%x\n", when, val);
144 break;
145 case DW_CFA_offset:
146 printf ("CFA: [%x] offset: %s at cfa-0x%x\n", when, mono_arch_regname (reg), -val);
147 break;
153 * mono_unlink_bblock:
155 * Unlink two basic blocks.
157 void
158 mono_unlink_bblock (MonoCompile *cfg, MonoBasicBlock *from, MonoBasicBlock* to)
160 int i, pos;
161 gboolean found;
163 found = FALSE;
164 for (i = 0; i < from->out_count; ++i) {
165 if (to == from->out_bb [i]) {
166 found = TRUE;
167 break;
170 if (found) {
171 pos = 0;
172 for (i = 0; i < from->out_count; ++i) {
173 if (from->out_bb [i] != to)
174 from->out_bb [pos ++] = from->out_bb [i];
176 g_assert (pos == from->out_count - 1);
177 from->out_count--;
180 found = FALSE;
181 for (i = 0; i < to->in_count; ++i) {
182 if (from == to->in_bb [i]) {
183 found = TRUE;
184 break;
187 if (found) {
188 pos = 0;
189 for (i = 0; i < to->in_count; ++i) {
190 if (to->in_bb [i] != from)
191 to->in_bb [pos ++] = to->in_bb [i];
193 g_assert (pos == to->in_count - 1);
194 to->in_count--;
199 * mono_bblocks_linked:
201 * Return whenever BB1 and BB2 are linked in the CFG.
203 gboolean
204 mono_bblocks_linked (MonoBasicBlock *bb1, MonoBasicBlock *bb2)
206 int i;
208 for (i = 0; i < bb1->out_count; ++i) {
209 if (bb1->out_bb [i] == bb2)
210 return TRUE;
213 return FALSE;
216 static int
217 mono_find_block_region_notry (MonoCompile *cfg, int offset)
219 MonoMethodHeader *header = cfg->header;
220 MonoExceptionClause *clause;
221 int i;
223 for (i = 0; i < header->num_clauses; ++i) {
224 clause = &header->clauses [i];
225 if ((clause->flags == MONO_EXCEPTION_CLAUSE_FILTER) && (offset >= clause->data.filter_offset) &&
226 (offset < (clause->handler_offset)))
227 return ((i + 1) << 8) | MONO_REGION_FILTER | clause->flags;
229 if (MONO_OFFSET_IN_HANDLER (clause, offset)) {
230 if (clause->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
231 return ((i + 1) << 8) | MONO_REGION_FINALLY | clause->flags;
232 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FAULT)
233 return ((i + 1) << 8) | MONO_REGION_FAULT | clause->flags;
234 else
235 return ((i + 1) << 8) | MONO_REGION_CATCH | clause->flags;
239 return -1;
243 * mono_get_block_region_notry:
245 * Return the region corresponding to REGION, ignoring try clauses nested inside
246 * finally clauses.
249 mono_get_block_region_notry (MonoCompile *cfg, int region)
251 if ((region & (0xf << 4)) == MONO_REGION_TRY) {
252 MonoMethodHeader *header = cfg->header;
255 * This can happen if a try clause is nested inside a finally clause.
257 int clause_index = (region >> 8) - 1;
258 g_assert (clause_index >= 0 && clause_index < header->num_clauses);
260 region = mono_find_block_region_notry (cfg, header->clauses [clause_index].try_offset);
263 return region;
266 MonoInst *
267 mono_find_spvar_for_region (MonoCompile *cfg, int region)
269 region = mono_get_block_region_notry (cfg, region);
271 return (MonoInst *)g_hash_table_lookup (cfg->spvars, GINT_TO_POINTER (region));
274 static void
275 df_visit (MonoBasicBlock *start, int *dfn, MonoBasicBlock **array)
277 int i;
279 array [*dfn] = start;
280 /* g_print ("visit %d at %p (BB%ld)\n", *dfn, start->cil_code, start->block_num); */
281 for (i = 0; i < start->out_count; ++i) {
282 if (start->out_bb [i]->dfn)
283 continue;
284 (*dfn)++;
285 start->out_bb [i]->dfn = *dfn;
286 start->out_bb [i]->df_parent = start;
287 array [*dfn] = start->out_bb [i];
288 df_visit (start->out_bb [i], dfn, array);
292 guint32
293 mono_reverse_branch_op (guint32 opcode)
295 static const int reverse_map [] = {
296 CEE_BNE_UN, CEE_BLT, CEE_BLE, CEE_BGT, CEE_BGE,
297 CEE_BEQ, CEE_BLT_UN, CEE_BLE_UN, CEE_BGT_UN, CEE_BGE_UN
299 static const int reverse_fmap [] = {
300 OP_FBNE_UN, OP_FBLT, OP_FBLE, OP_FBGT, OP_FBGE,
301 OP_FBEQ, OP_FBLT_UN, OP_FBLE_UN, OP_FBGT_UN, OP_FBGE_UN
303 static const int reverse_lmap [] = {
304 OP_LBNE_UN, OP_LBLT, OP_LBLE, OP_LBGT, OP_LBGE,
305 OP_LBEQ, OP_LBLT_UN, OP_LBLE_UN, OP_LBGT_UN, OP_LBGE_UN
307 static const int reverse_imap [] = {
308 OP_IBNE_UN, OP_IBLT, OP_IBLE, OP_IBGT, OP_IBGE,
309 OP_IBEQ, OP_IBLT_UN, OP_IBLE_UN, OP_IBGT_UN, OP_IBGE_UN
312 if (opcode >= CEE_BEQ && opcode <= CEE_BLT_UN) {
313 opcode = reverse_map [opcode - CEE_BEQ];
314 } else if (opcode >= OP_FBEQ && opcode <= OP_FBLT_UN) {
315 opcode = reverse_fmap [opcode - OP_FBEQ];
316 } else if (opcode >= OP_LBEQ && opcode <= OP_LBLT_UN) {
317 opcode = reverse_lmap [opcode - OP_LBEQ];
318 } else if (opcode >= OP_IBEQ && opcode <= OP_IBLT_UN) {
319 opcode = reverse_imap [opcode - OP_IBEQ];
320 } else
321 g_assert_not_reached ();
323 return opcode;
326 guint
327 mono_type_to_store_membase (MonoCompile *cfg, MonoType *type)
329 type = mini_get_underlying_type (type);
331 handle_enum:
332 switch (type->type) {
333 case MONO_TYPE_I1:
334 case MONO_TYPE_U1:
335 return OP_STOREI1_MEMBASE_REG;
336 case MONO_TYPE_I2:
337 case MONO_TYPE_U2:
338 return OP_STOREI2_MEMBASE_REG;
339 case MONO_TYPE_I4:
340 case MONO_TYPE_U4:
341 return OP_STOREI4_MEMBASE_REG;
342 case MONO_TYPE_I:
343 case MONO_TYPE_U:
344 case MONO_TYPE_PTR:
345 case MONO_TYPE_FNPTR:
346 return OP_STORE_MEMBASE_REG;
347 case MONO_TYPE_CLASS:
348 case MONO_TYPE_STRING:
349 case MONO_TYPE_OBJECT:
350 case MONO_TYPE_SZARRAY:
351 case MONO_TYPE_ARRAY:
352 return OP_STORE_MEMBASE_REG;
353 case MONO_TYPE_I8:
354 case MONO_TYPE_U8:
355 return OP_STOREI8_MEMBASE_REG;
356 case MONO_TYPE_R4:
357 return OP_STORER4_MEMBASE_REG;
358 case MONO_TYPE_R8:
359 return OP_STORER8_MEMBASE_REG;
360 case MONO_TYPE_VALUETYPE:
361 if (m_class_is_enumtype (type->data.klass)) {
362 type = mono_class_enum_basetype_internal (type->data.klass);
363 goto handle_enum;
365 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type_internal (type)))
366 return OP_STOREX_MEMBASE;
367 return OP_STOREV_MEMBASE;
368 case MONO_TYPE_TYPEDBYREF:
369 return OP_STOREV_MEMBASE;
370 case MONO_TYPE_GENERICINST:
371 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type_internal (type)))
372 return OP_STOREX_MEMBASE;
373 type = m_class_get_byval_arg (type->data.generic_class->container_class);
374 goto handle_enum;
375 case MONO_TYPE_VAR:
376 case MONO_TYPE_MVAR:
377 g_assert (mini_type_var_is_vt (type));
378 return OP_STOREV_MEMBASE;
379 default:
380 g_error ("unknown type 0x%02x in type_to_store_membase", type->type);
382 return -1;
385 guint
386 mono_type_to_load_membase (MonoCompile *cfg, MonoType *type)
388 type = mini_get_underlying_type (type);
390 switch (type->type) {
391 case MONO_TYPE_I1:
392 return OP_LOADI1_MEMBASE;
393 case MONO_TYPE_U1:
394 return OP_LOADU1_MEMBASE;
395 case MONO_TYPE_I2:
396 return OP_LOADI2_MEMBASE;
397 case MONO_TYPE_U2:
398 return OP_LOADU2_MEMBASE;
399 case MONO_TYPE_I4:
400 return OP_LOADI4_MEMBASE;
401 case MONO_TYPE_U4:
402 return OP_LOADU4_MEMBASE;
403 case MONO_TYPE_I:
404 case MONO_TYPE_U:
405 case MONO_TYPE_PTR:
406 case MONO_TYPE_FNPTR:
407 return OP_LOAD_MEMBASE;
408 case MONO_TYPE_CLASS:
409 case MONO_TYPE_STRING:
410 case MONO_TYPE_OBJECT:
411 case MONO_TYPE_SZARRAY:
412 case MONO_TYPE_ARRAY:
413 return OP_LOAD_MEMBASE;
414 case MONO_TYPE_I8:
415 case MONO_TYPE_U8:
416 return OP_LOADI8_MEMBASE;
417 case MONO_TYPE_R4:
418 return OP_LOADR4_MEMBASE;
419 case MONO_TYPE_R8:
420 return OP_LOADR8_MEMBASE;
421 case MONO_TYPE_VALUETYPE:
422 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type_internal (type)))
423 return OP_LOADX_MEMBASE;
424 case MONO_TYPE_TYPEDBYREF:
425 return OP_LOADV_MEMBASE;
426 case MONO_TYPE_GENERICINST:
427 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type_internal (type)))
428 return OP_LOADX_MEMBASE;
429 if (mono_type_generic_inst_is_valuetype (type))
430 return OP_LOADV_MEMBASE;
431 else
432 return OP_LOAD_MEMBASE;
433 break;
434 case MONO_TYPE_VAR:
435 case MONO_TYPE_MVAR:
436 g_assert (cfg->gshared);
437 g_assert (mini_type_var_is_vt (type));
438 return OP_LOADV_MEMBASE;
439 default:
440 g_error ("unknown type 0x%02x in type_to_load_membase", type->type);
442 return -1;
445 guint
446 mini_type_to_stind (MonoCompile* cfg, MonoType *type)
448 type = mini_get_underlying_type (type);
449 if (cfg->gshared && !type->byref && (type->type == MONO_TYPE_VAR || type->type == MONO_TYPE_MVAR)) {
450 g_assert (mini_type_var_is_vt (type));
451 return CEE_STOBJ;
453 return mono_type_to_stind (type);
457 mono_op_imm_to_op (int opcode)
459 switch (opcode) {
460 case OP_ADD_IMM:
461 #if SIZEOF_REGISTER == 4
462 return OP_IADD;
463 #else
464 return OP_LADD;
465 #endif
466 case OP_IADD_IMM:
467 return OP_IADD;
468 case OP_LADD_IMM:
469 return OP_LADD;
470 case OP_ISUB_IMM:
471 return OP_ISUB;
472 case OP_LSUB_IMM:
473 return OP_LSUB;
474 case OP_IMUL_IMM:
475 return OP_IMUL;
476 case OP_LMUL_IMM:
477 return OP_LMUL;
478 case OP_AND_IMM:
479 #if SIZEOF_REGISTER == 4
480 return OP_IAND;
481 #else
482 return OP_LAND;
483 #endif
484 case OP_OR_IMM:
485 #if SIZEOF_REGISTER == 4
486 return OP_IOR;
487 #else
488 return OP_LOR;
489 #endif
490 case OP_XOR_IMM:
491 #if SIZEOF_REGISTER == 4
492 return OP_IXOR;
493 #else
494 return OP_LXOR;
495 #endif
496 case OP_IAND_IMM:
497 return OP_IAND;
498 case OP_LAND_IMM:
499 return OP_LAND;
500 case OP_IOR_IMM:
501 return OP_IOR;
502 case OP_LOR_IMM:
503 return OP_LOR;
504 case OP_IXOR_IMM:
505 return OP_IXOR;
506 case OP_LXOR_IMM:
507 return OP_LXOR;
508 case OP_ISHL_IMM:
509 return OP_ISHL;
510 case OP_LSHL_IMM:
511 return OP_LSHL;
512 case OP_ISHR_IMM:
513 return OP_ISHR;
514 case OP_LSHR_IMM:
515 return OP_LSHR;
516 case OP_ISHR_UN_IMM:
517 return OP_ISHR_UN;
518 case OP_LSHR_UN_IMM:
519 return OP_LSHR_UN;
520 case OP_IDIV_IMM:
521 return OP_IDIV;
522 case OP_LDIV_IMM:
523 return OP_LDIV;
524 case OP_IDIV_UN_IMM:
525 return OP_IDIV_UN;
526 case OP_LDIV_UN_IMM:
527 return OP_LDIV_UN;
528 case OP_IREM_UN_IMM:
529 return OP_IREM_UN;
530 case OP_LREM_UN_IMM:
531 return OP_LREM_UN;
532 case OP_IREM_IMM:
533 return OP_IREM;
534 case OP_LREM_IMM:
535 return OP_LREM;
536 case OP_DIV_IMM:
537 #if SIZEOF_REGISTER == 4
538 return OP_IDIV;
539 #else
540 return OP_LDIV;
541 #endif
542 case OP_REM_IMM:
543 #if SIZEOF_REGISTER == 4
544 return OP_IREM;
545 #else
546 return OP_LREM;
547 #endif
548 case OP_ADDCC_IMM:
549 return OP_ADDCC;
550 case OP_ADC_IMM:
551 return OP_ADC;
552 case OP_SUBCC_IMM:
553 return OP_SUBCC;
554 case OP_SBB_IMM:
555 return OP_SBB;
556 case OP_IADC_IMM:
557 return OP_IADC;
558 case OP_ISBB_IMM:
559 return OP_ISBB;
560 case OP_COMPARE_IMM:
561 return OP_COMPARE;
562 case OP_ICOMPARE_IMM:
563 return OP_ICOMPARE;
564 case OP_LOCALLOC_IMM:
565 return OP_LOCALLOC;
568 return -1;
572 * mono_decompose_op_imm:
574 * Replace the OP_.._IMM INS with its non IMM variant.
576 void
577 mono_decompose_op_imm (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins)
579 int opcode2 = mono_op_imm_to_op (ins->opcode);
580 MonoInst *temp;
581 guint32 dreg;
582 const char *spec = INS_INFO (ins->opcode);
584 if (spec [MONO_INST_SRC2] == 'l') {
585 dreg = mono_alloc_lreg (cfg);
587 /* Load the 64bit constant using decomposed ops */
588 MONO_INST_NEW (cfg, temp, OP_ICONST);
589 temp->inst_c0 = ins_get_l_low (ins);
590 temp->dreg = MONO_LVREG_LS (dreg);
591 mono_bblock_insert_before_ins (bb, ins, temp);
593 MONO_INST_NEW (cfg, temp, OP_ICONST);
594 temp->inst_c0 = ins_get_l_high (ins);
595 temp->dreg = MONO_LVREG_MS (dreg);
596 } else {
597 dreg = mono_alloc_ireg (cfg);
599 MONO_INST_NEW (cfg, temp, OP_ICONST);
600 temp->inst_c0 = ins->inst_imm;
601 temp->dreg = dreg;
604 mono_bblock_insert_before_ins (bb, ins, temp);
606 if (opcode2 == -1)
607 g_error ("mono_op_imm_to_op failed for %s\n", mono_inst_name (ins->opcode));
608 ins->opcode = opcode2;
610 if (ins->opcode == OP_LOCALLOC)
611 ins->sreg1 = dreg;
612 else
613 ins->sreg2 = dreg;
615 bb->max_vreg = MAX (bb->max_vreg, cfg->next_vreg);
618 static void
619 set_vreg_to_inst (MonoCompile *cfg, int vreg, MonoInst *inst)
621 if (vreg >= cfg->vreg_to_inst_len) {
622 MonoInst **tmp = cfg->vreg_to_inst;
623 int size = cfg->vreg_to_inst_len;
625 while (vreg >= cfg->vreg_to_inst_len)
626 cfg->vreg_to_inst_len = cfg->vreg_to_inst_len ? cfg->vreg_to_inst_len * 2 : 32;
627 cfg->vreg_to_inst = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst*) * cfg->vreg_to_inst_len);
628 if (size)
629 memcpy (cfg->vreg_to_inst, tmp, size * sizeof (MonoInst*));
631 cfg->vreg_to_inst [vreg] = inst;
634 #define mono_type_is_long(type) (!(type)->byref && ((mono_type_get_underlying_type (type)->type == MONO_TYPE_I8) || (mono_type_get_underlying_type (type)->type == MONO_TYPE_U8)))
635 #define mono_type_is_float(type) (!(type)->byref && (((type)->type == MONO_TYPE_R8) || ((type)->type == MONO_TYPE_R4)))
637 MonoInst*
638 mono_compile_create_var_for_vreg (MonoCompile *cfg, MonoType *type, int opcode, int vreg)
640 MonoInst *inst;
641 int num = cfg->num_varinfo;
642 gboolean regpair;
644 type = mini_get_underlying_type (type);
646 if ((num + 1) >= cfg->varinfo_count) {
647 int orig_count = cfg->varinfo_count;
648 cfg->varinfo_count = cfg->varinfo_count ? (cfg->varinfo_count * 2) : 32;
649 cfg->varinfo = (MonoInst **)g_realloc (cfg->varinfo, sizeof (MonoInst*) * cfg->varinfo_count);
650 cfg->vars = (MonoMethodVar *)g_realloc (cfg->vars, sizeof (MonoMethodVar) * cfg->varinfo_count);
651 memset (&cfg->vars [orig_count], 0, (cfg->varinfo_count - orig_count) * sizeof (MonoMethodVar));
654 cfg->stat_allocate_var++;
656 MONO_INST_NEW (cfg, inst, opcode);
657 inst->inst_c0 = num;
658 inst->inst_vtype = type;
659 inst->klass = mono_class_from_mono_type_internal (type);
660 mini_type_to_eval_stack_type (cfg, type, inst);
661 /* if set to 1 the variable is native */
662 inst->backend.is_pinvoke = 0;
663 inst->dreg = vreg;
665 if (mono_class_has_failure (inst->klass))
666 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
668 if (cfg->compute_gc_maps) {
669 if (type->byref) {
670 mono_mark_vreg_as_mp (cfg, vreg);
671 } else {
672 if ((MONO_TYPE_ISSTRUCT (type) && m_class_has_references (inst->klass)) || mini_type_is_reference (type)) {
673 inst->flags |= MONO_INST_GC_TRACK;
674 mono_mark_vreg_as_ref (cfg, vreg);
679 cfg->varinfo [num] = inst;
681 cfg->vars [num].idx = num;
682 cfg->vars [num].vreg = vreg;
683 cfg->vars [num].range.first_use.pos.bid = 0xffff;
684 cfg->vars [num].reg = -1;
686 if (vreg != -1)
687 set_vreg_to_inst (cfg, vreg, inst);
689 #if SIZEOF_REGISTER == 4
690 if (mono_arch_is_soft_float ()) {
691 regpair = mono_type_is_long (type) || mono_type_is_float (type);
692 } else {
693 regpair = mono_type_is_long (type);
695 #else
696 regpair = FALSE;
697 #endif
699 if (regpair) {
700 MonoInst *tree;
703 * These two cannot be allocated using create_var_for_vreg since that would
704 * put it into the cfg->varinfo array, confusing many parts of the JIT.
708 * Set flags to VOLATILE so SSA skips it.
711 if (cfg->verbose_level >= 4) {
712 printf (" Create LVAR R%d (R%d, R%d)\n", inst->dreg, MONO_LVREG_LS (inst->dreg), MONO_LVREG_MS (inst->dreg));
715 if (mono_arch_is_soft_float () && cfg->opt & MONO_OPT_SSA) {
716 if (mono_type_is_float (type))
717 inst->flags = MONO_INST_VOLATILE;
720 /* Allocate a dummy MonoInst for the first vreg */
721 MONO_INST_NEW (cfg, tree, OP_LOCAL);
722 tree->dreg = MONO_LVREG_LS (inst->dreg);
723 if (cfg->opt & MONO_OPT_SSA)
724 tree->flags = MONO_INST_VOLATILE;
725 tree->inst_c0 = num;
726 tree->type = STACK_I4;
727 tree->inst_vtype = mono_get_int32_type ();
728 tree->klass = mono_class_from_mono_type_internal (tree->inst_vtype);
730 set_vreg_to_inst (cfg, MONO_LVREG_LS (inst->dreg), tree);
732 /* Allocate a dummy MonoInst for the second vreg */
733 MONO_INST_NEW (cfg, tree, OP_LOCAL);
734 tree->dreg = MONO_LVREG_MS (inst->dreg);
735 if (cfg->opt & MONO_OPT_SSA)
736 tree->flags = MONO_INST_VOLATILE;
737 tree->inst_c0 = num;
738 tree->type = STACK_I4;
739 tree->inst_vtype = mono_get_int32_type ();
740 tree->klass = mono_class_from_mono_type_internal (tree->inst_vtype);
742 set_vreg_to_inst (cfg, MONO_LVREG_MS (inst->dreg), tree);
745 cfg->num_varinfo++;
746 if (cfg->verbose_level > 2)
747 g_print ("created temp %d (R%d) of type %s\n", num, vreg, mono_type_get_name (type));
749 return inst;
752 MonoInst*
753 mono_compile_create_var (MonoCompile *cfg, MonoType *type, int opcode)
755 int dreg;
757 #ifdef ENABLE_NETCORE
758 if (type->type == MONO_TYPE_VALUETYPE && !type->byref) {
759 MonoClass *klass = mono_class_from_mono_type_internal (type);
760 if (m_class_is_enumtype (klass) && m_class_get_image (klass) == mono_get_corlib () && !strcmp (m_class_get_name (klass), "StackCrawlMark")) {
761 if (!(cfg->method->flags & METHOD_ATTRIBUTE_REQSECOBJ))
762 g_error ("Method '%s' which contains a StackCrawlMark local variable must be decorated with [System.Security.DynamicSecurityMethod].", mono_method_get_full_name (cfg->method));
765 #endif
767 type = mini_get_underlying_type (type);
769 if (mono_type_is_long (type))
770 dreg = mono_alloc_dreg (cfg, STACK_I8);
771 else if (mono_arch_is_soft_float () && mono_type_is_float (type))
772 dreg = mono_alloc_dreg (cfg, STACK_R8);
773 else
774 /* All the others are unified */
775 dreg = mono_alloc_preg (cfg);
777 return mono_compile_create_var_for_vreg (cfg, type, opcode, dreg);
780 MonoInst*
781 mini_get_int_to_float_spill_area (MonoCompile *cfg)
783 #ifdef TARGET_X86
784 if (!cfg->iconv_raw_var) {
785 cfg->iconv_raw_var = mono_compile_create_var (cfg, mono_get_int32_type (), OP_LOCAL);
786 cfg->iconv_raw_var->flags |= MONO_INST_VOLATILE; /*FIXME, use the don't regalloc flag*/
788 return cfg->iconv_raw_var;
789 #else
790 return NULL;
791 #endif
794 void
795 mono_mark_vreg_as_ref (MonoCompile *cfg, int vreg)
797 if (vreg >= cfg->vreg_is_ref_len) {
798 gboolean *tmp = cfg->vreg_is_ref;
799 int size = cfg->vreg_is_ref_len;
801 while (vreg >= cfg->vreg_is_ref_len)
802 cfg->vreg_is_ref_len = cfg->vreg_is_ref_len ? cfg->vreg_is_ref_len * 2 : 32;
803 cfg->vreg_is_ref = (gboolean *)mono_mempool_alloc0 (cfg->mempool, sizeof (gboolean) * cfg->vreg_is_ref_len);
804 if (size)
805 memcpy (cfg->vreg_is_ref, tmp, size * sizeof (gboolean));
807 cfg->vreg_is_ref [vreg] = TRUE;
810 void
811 mono_mark_vreg_as_mp (MonoCompile *cfg, int vreg)
813 if (vreg >= cfg->vreg_is_mp_len) {
814 gboolean *tmp = cfg->vreg_is_mp;
815 int size = cfg->vreg_is_mp_len;
817 while (vreg >= cfg->vreg_is_mp_len)
818 cfg->vreg_is_mp_len = cfg->vreg_is_mp_len ? cfg->vreg_is_mp_len * 2 : 32;
819 cfg->vreg_is_mp = (gboolean *)mono_mempool_alloc0 (cfg->mempool, sizeof (gboolean) * cfg->vreg_is_mp_len);
820 if (size)
821 memcpy (cfg->vreg_is_mp, tmp, size * sizeof (gboolean));
823 cfg->vreg_is_mp [vreg] = TRUE;
826 static MonoType*
827 type_from_stack_type (MonoInst *ins)
829 switch (ins->type) {
830 case STACK_I4: return mono_get_int32_type ();
831 case STACK_I8: return m_class_get_byval_arg (mono_defaults.int64_class);
832 case STACK_PTR: return mono_get_int_type ();
833 case STACK_R8: return m_class_get_byval_arg (mono_defaults.double_class);
834 case STACK_MP:
836 * this if used to be commented without any specific reason, but
837 * it breaks #80235 when commented
839 if (ins->klass)
840 return m_class_get_this_arg (ins->klass);
841 else
842 return m_class_get_this_arg (mono_defaults.object_class);
843 case STACK_OBJ:
844 /* ins->klass may not be set for ldnull.
845 * Also, if we have a boxed valuetype, we want an object lass,
846 * not the valuetype class
848 if (ins->klass && !m_class_is_valuetype (ins->klass))
849 return m_class_get_byval_arg (ins->klass);
850 return mono_get_object_type ();
851 case STACK_VTYPE: return m_class_get_byval_arg (ins->klass);
852 default:
853 g_error ("stack type %d to montype not handled\n", ins->type);
855 return NULL;
858 MonoType*
859 mono_type_from_stack_type (MonoInst *ins)
861 return type_from_stack_type (ins);
865 * mono_add_ins_to_end:
867 * Same as MONO_ADD_INS, but add INST before any branches at the end of BB.
869 void
870 mono_add_ins_to_end (MonoBasicBlock *bb, MonoInst *inst)
872 int opcode;
874 if (!bb->code) {
875 MONO_ADD_INS (bb, inst);
876 return;
879 switch (bb->last_ins->opcode) {
880 case OP_BR:
881 case OP_BR_REG:
882 case CEE_BEQ:
883 case CEE_BGE:
884 case CEE_BGT:
885 case CEE_BLE:
886 case CEE_BLT:
887 case CEE_BNE_UN:
888 case CEE_BGE_UN:
889 case CEE_BGT_UN:
890 case CEE_BLE_UN:
891 case CEE_BLT_UN:
892 case OP_SWITCH:
893 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
894 break;
895 default:
896 if (MONO_IS_COND_BRANCH_OP (bb->last_ins)) {
897 /* Need to insert the ins before the compare */
898 if (bb->code == bb->last_ins) {
899 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
900 return;
903 if (bb->code->next == bb->last_ins) {
904 /* Only two instructions */
905 opcode = bb->code->opcode;
907 if ((opcode == OP_COMPARE) || (opcode == OP_COMPARE_IMM) || (opcode == OP_ICOMPARE) || (opcode == OP_ICOMPARE_IMM) || (opcode == OP_FCOMPARE) || (opcode == OP_LCOMPARE) || (opcode == OP_LCOMPARE_IMM) || (opcode == OP_RCOMPARE)) {
908 /* NEW IR */
909 mono_bblock_insert_before_ins (bb, bb->code, inst);
910 } else {
911 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
913 } else {
914 opcode = bb->last_ins->prev->opcode;
916 if ((opcode == OP_COMPARE) || (opcode == OP_COMPARE_IMM) || (opcode == OP_ICOMPARE) || (opcode == OP_ICOMPARE_IMM) || (opcode == OP_FCOMPARE) || (opcode == OP_LCOMPARE) || (opcode == OP_LCOMPARE_IMM) || (opcode == OP_RCOMPARE)) {
917 /* NEW IR */
918 mono_bblock_insert_before_ins (bb, bb->last_ins->prev, inst);
919 } else {
920 mono_bblock_insert_before_ins (bb, bb->last_ins, inst);
924 else
925 MONO_ADD_INS (bb, inst);
926 break;
930 void
931 mono_create_jump_table (MonoCompile *cfg, MonoInst *label, MonoBasicBlock **bbs, int num_blocks)
933 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfo));
934 MonoJumpInfoBBTable *table;
936 table = (MonoJumpInfoBBTable *)mono_mempool_alloc (cfg->mempool, sizeof (MonoJumpInfoBBTable));
937 table->table = bbs;
938 table->table_size = num_blocks;
940 ji->ip.label = label;
941 ji->type = MONO_PATCH_INFO_SWITCH;
942 ji->data.table = table;
943 ji->next = cfg->patch_info;
944 cfg->patch_info = ji;
947 gboolean
948 mini_assembly_can_skip_verification (MonoDomain *domain, MonoMethod *method)
950 MonoAssembly *assembly = m_class_get_image (method->klass)->assembly;
951 if (method->wrapper_type != MONO_WRAPPER_NONE && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
952 return FALSE;
953 if (assembly->in_gac || assembly->image == mono_defaults.corlib)
954 return FALSE;
955 return mono_assembly_has_skip_verification (assembly);
959 * mini_method_verify:
961 * Verify the method using the verfier.
963 * Returns true if the method is invalid.
965 static gboolean
966 mini_method_verify (MonoCompile *cfg, MonoMethod *method, gboolean fail_compile)
968 GSList *tmp, *res;
969 gboolean is_fulltrust;
971 if (method->verification_success)
972 return FALSE;
974 if (!mono_verifier_is_enabled_for_method (method))
975 return FALSE;
977 /*skip verification implies the assembly must be */
978 is_fulltrust = mono_verifier_is_method_full_trust (method) || mini_assembly_can_skip_verification (cfg->domain, method);
980 res = mono_method_verify_with_current_settings (method, cfg->skip_visibility, is_fulltrust);
982 if (res) {
983 for (tmp = res; tmp; tmp = tmp->next) {
984 MonoVerifyInfoExtended *info = (MonoVerifyInfoExtended *)tmp->data;
985 if (info->info.status == MONO_VERIFY_ERROR) {
986 if (fail_compile) {
987 char *method_name = mono_method_full_name (method, TRUE);
988 cfg->exception_type = (MonoExceptionType)info->exception_type;
989 cfg->exception_message = g_strdup_printf ("Error verifying %s: %s", method_name, info->info.message);
990 g_free (method_name);
992 mono_free_verify_list (res);
993 return TRUE;
995 if (info->info.status == MONO_VERIFY_NOT_VERIFIABLE && (!is_fulltrust || info->exception_type == MONO_EXCEPTION_METHOD_ACCESS || info->exception_type == MONO_EXCEPTION_FIELD_ACCESS)) {
996 if (fail_compile) {
997 char *method_name = mono_method_full_name (method, TRUE);
998 char *msg = g_strdup_printf ("Error verifying %s: %s", method_name, info->info.message);
1000 if (info->exception_type == MONO_EXCEPTION_METHOD_ACCESS)
1001 mono_error_set_generic_error (cfg->error, "System", "MethodAccessException", "%s", msg);
1002 else if (info->exception_type == MONO_EXCEPTION_FIELD_ACCESS)
1003 mono_error_set_generic_error (cfg->error, "System", "FieldAccessException", "%s", msg);
1004 else if (info->exception_type == MONO_EXCEPTION_UNVERIFIABLE_IL)
1005 mono_error_set_generic_error (cfg->error, "System.Security", "VerificationException", "%s", msg);
1006 if (!is_ok (cfg->error)) {
1007 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
1008 g_free (msg);
1009 } else {
1010 cfg->exception_type = (MonoExceptionType)info->exception_type;
1011 cfg->exception_message = msg;
1013 g_free (method_name);
1015 mono_free_verify_list (res);
1016 return TRUE;
1019 mono_free_verify_list (res);
1021 method->verification_success = 1;
1022 return FALSE;
1025 /*Returns true if something went wrong*/
1026 gboolean
1027 mono_compile_is_broken (MonoCompile *cfg, MonoMethod *method, gboolean fail_compile)
1029 MonoMethod *method_definition = method;
1030 gboolean dont_verify = m_class_get_image (method->klass)->assembly->corlib_internal;
1032 while (method_definition->is_inflated) {
1033 MonoMethodInflated *imethod = (MonoMethodInflated *) method_definition;
1034 method_definition = imethod->declaring;
1037 return !dont_verify && mini_method_verify (cfg, method_definition, fail_compile);
1040 static void
1041 mono_dynamic_code_hash_insert (MonoDomain *domain, MonoMethod *method, MonoJitDynamicMethodInfo *ji)
1043 if (!domain_jit_info (domain)->dynamic_code_hash)
1044 domain_jit_info (domain)->dynamic_code_hash = g_hash_table_new (NULL, NULL);
1045 g_hash_table_insert (domain_jit_info (domain)->dynamic_code_hash, method, ji);
1048 static MonoJitDynamicMethodInfo*
1049 mono_dynamic_code_hash_lookup (MonoDomain *domain, MonoMethod *method)
1051 MonoJitDynamicMethodInfo *res;
1053 if (domain_jit_info (domain)->dynamic_code_hash)
1054 res = (MonoJitDynamicMethodInfo *)g_hash_table_lookup (domain_jit_info (domain)->dynamic_code_hash, method);
1055 else
1056 res = NULL;
1057 return res;
1060 typedef struct {
1061 MonoClass *vtype;
1062 GList *active, *inactive;
1063 GSList *slots;
1064 } StackSlotInfo;
1066 static gint
1067 compare_by_interval_start_pos_func (gconstpointer a, gconstpointer b)
1069 MonoMethodVar *v1 = (MonoMethodVar*)a;
1070 MonoMethodVar *v2 = (MonoMethodVar*)b;
1072 if (v1 == v2)
1073 return 0;
1074 else if (v1->interval->range && v2->interval->range)
1075 return v1->interval->range->from - v2->interval->range->from;
1076 else if (v1->interval->range)
1077 return -1;
1078 else
1079 return 1;
1082 #if 0
1083 #define LSCAN_DEBUG(a) do { a; } while (0)
1084 #else
1085 #define LSCAN_DEBUG(a)
1086 #endif
1088 static gint32*
1089 mono_allocate_stack_slots2 (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
1091 int i, slot, offset, size;
1092 guint32 align;
1093 MonoMethodVar *vmv;
1094 MonoInst *inst;
1095 gint32 *offsets;
1096 GList *vars = NULL, *l, *unhandled;
1097 StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
1098 MonoType *t;
1099 int nvtypes;
1100 int vtype_stack_slots_size = 256;
1101 gboolean reuse_slot;
1103 LSCAN_DEBUG (printf ("Allocate Stack Slots 2 for %s:\n", mono_method_full_name (cfg->method, TRUE)));
1105 scalar_stack_slots = (StackSlotInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
1106 vtype_stack_slots = NULL;
1107 nvtypes = 0;
1109 offsets = (gint32 *)mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
1110 for (i = 0; i < cfg->num_varinfo; ++i)
1111 offsets [i] = -1;
1113 for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1114 inst = cfg->varinfo [i];
1115 vmv = MONO_VARINFO (cfg, i);
1117 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
1118 continue;
1120 vars = g_list_prepend (vars, vmv);
1123 vars = g_list_sort (vars, compare_by_interval_start_pos_func);
1125 /* Sanity check */
1127 i = 0;
1128 for (unhandled = vars; unhandled; unhandled = unhandled->next) {
1129 MonoMethodVar *current = unhandled->data;
1131 if (current->interval->range) {
1132 g_assert (current->interval->range->from >= i);
1133 i = current->interval->range->from;
1138 offset = 0;
1139 *stack_align = 0;
1140 for (unhandled = vars; unhandled; unhandled = unhandled->next) {
1141 MonoMethodVar *current = (MonoMethodVar *)unhandled->data;
1143 vmv = current;
1144 inst = cfg->varinfo [vmv->idx];
1146 t = mono_type_get_underlying_type (inst->inst_vtype);
1147 if (cfg->gsharedvt && mini_is_gsharedvt_variable_type (t))
1148 continue;
1150 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
1151 * pinvoke wrappers when they call functions returning structures */
1152 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (t) && t->type != MONO_TYPE_TYPEDBYREF) {
1153 size = mono_class_native_size (mono_class_from_mono_type_internal (t), &align);
1155 else {
1156 int ialign;
1158 size = mini_type_stack_size (t, &ialign);
1159 align = ialign;
1161 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type_internal (t)))
1162 align = 16;
1165 reuse_slot = TRUE;
1166 if (cfg->disable_reuse_stack_slots)
1167 reuse_slot = FALSE;
1169 t = mini_get_underlying_type (t);
1170 switch (t->type) {
1171 case MONO_TYPE_GENERICINST:
1172 if (!mono_type_generic_inst_is_valuetype (t)) {
1173 slot_info = &scalar_stack_slots [t->type];
1174 break;
1176 /* Fall through */
1177 case MONO_TYPE_VALUETYPE:
1178 if (!vtype_stack_slots)
1179 vtype_stack_slots = (StackSlotInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * vtype_stack_slots_size);
1180 for (i = 0; i < nvtypes; ++i)
1181 if (t->data.klass == vtype_stack_slots [i].vtype)
1182 break;
1183 if (i < nvtypes)
1184 slot_info = &vtype_stack_slots [i];
1185 else {
1186 if (nvtypes == vtype_stack_slots_size) {
1187 int new_slots_size = vtype_stack_slots_size * 2;
1188 StackSlotInfo* new_slots = (StackSlotInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * new_slots_size);
1190 memcpy (new_slots, vtype_stack_slots, sizeof (StackSlotInfo) * vtype_stack_slots_size);
1192 vtype_stack_slots = new_slots;
1193 vtype_stack_slots_size = new_slots_size;
1195 vtype_stack_slots [nvtypes].vtype = t->data.klass;
1196 slot_info = &vtype_stack_slots [nvtypes];
1197 nvtypes ++;
1199 if (cfg->disable_reuse_ref_stack_slots)
1200 reuse_slot = FALSE;
1201 break;
1203 case MONO_TYPE_PTR:
1204 case MONO_TYPE_I:
1205 case MONO_TYPE_U:
1206 #if TARGET_SIZEOF_VOID_P == 4
1207 case MONO_TYPE_I4:
1208 #else
1209 case MONO_TYPE_I8:
1210 #endif
1211 if (cfg->disable_ref_noref_stack_slot_share) {
1212 slot_info = &scalar_stack_slots [MONO_TYPE_I];
1213 break;
1215 /* Fall through */
1217 case MONO_TYPE_CLASS:
1218 case MONO_TYPE_OBJECT:
1219 case MONO_TYPE_ARRAY:
1220 case MONO_TYPE_SZARRAY:
1221 case MONO_TYPE_STRING:
1222 /* Share non-float stack slots of the same size */
1223 slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
1224 if (cfg->disable_reuse_ref_stack_slots)
1225 reuse_slot = FALSE;
1226 break;
1228 default:
1229 slot_info = &scalar_stack_slots [t->type];
1232 slot = 0xffffff;
1233 if (cfg->comp_done & MONO_COMP_LIVENESS) {
1234 int pos;
1235 gboolean changed;
1237 //printf ("START %2d %08x %08x\n", vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
1239 if (!current->interval->range) {
1240 if (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))
1241 pos = ~0;
1242 else {
1243 /* Dead */
1244 inst->flags |= MONO_INST_IS_DEAD;
1245 continue;
1248 else
1249 pos = current->interval->range->from;
1251 LSCAN_DEBUG (printf ("process R%d ", inst->dreg));
1252 if (current->interval->range)
1253 LSCAN_DEBUG (mono_linterval_print (current->interval));
1254 LSCAN_DEBUG (printf ("\n"));
1256 /* Check for intervals in active which expired or inactive */
1257 changed = TRUE;
1258 /* FIXME: Optimize this */
1259 while (changed) {
1260 changed = FALSE;
1261 for (l = slot_info->active; l != NULL; l = l->next) {
1262 MonoMethodVar *v = (MonoMethodVar*)l->data;
1264 if (v->interval->last_range->to < pos) {
1265 slot_info->active = g_list_delete_link (slot_info->active, l);
1266 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [v->idx]));
1267 LSCAN_DEBUG (printf ("Interval R%d has expired, adding 0x%x to slots\n", cfg->varinfo [v->idx]->dreg, offsets [v->idx]));
1268 changed = TRUE;
1269 break;
1271 else if (!mono_linterval_covers (v->interval, pos)) {
1272 slot_info->inactive = g_list_append (slot_info->inactive, v);
1273 slot_info->active = g_list_delete_link (slot_info->active, l);
1274 LSCAN_DEBUG (printf ("Interval R%d became inactive\n", cfg->varinfo [v->idx]->dreg));
1275 changed = TRUE;
1276 break;
1281 /* Check for intervals in inactive which expired or active */
1282 changed = TRUE;
1283 /* FIXME: Optimize this */
1284 while (changed) {
1285 changed = FALSE;
1286 for (l = slot_info->inactive; l != NULL; l = l->next) {
1287 MonoMethodVar *v = (MonoMethodVar*)l->data;
1289 if (v->interval->last_range->to < pos) {
1290 slot_info->inactive = g_list_delete_link (slot_info->inactive, l);
1291 // FIXME: Enabling this seems to cause impossible to debug crashes
1292 //slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [v->idx]));
1293 LSCAN_DEBUG (printf ("Interval R%d has expired, adding 0x%x to slots\n", cfg->varinfo [v->idx]->dreg, offsets [v->idx]));
1294 changed = TRUE;
1295 break;
1297 else if (mono_linterval_covers (v->interval, pos)) {
1298 slot_info->active = g_list_append (slot_info->active, v);
1299 slot_info->inactive = g_list_delete_link (slot_info->inactive, l);
1300 LSCAN_DEBUG (printf ("\tInterval R%d became active\n", cfg->varinfo [v->idx]->dreg));
1301 changed = TRUE;
1302 break;
1308 * This also handles the case when the variable is used in an
1309 * exception region, as liveness info is not computed there.
1312 * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
1313 * opcodes.
1315 if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
1316 if (slot_info->slots) {
1317 slot = GPOINTER_TO_INT (slot_info->slots->data);
1319 slot_info->slots = slot_info->slots->next;
1322 /* FIXME: We might want to consider the inactive intervals as well if slot_info->slots is empty */
1324 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
1328 #if 0
1330 static int count = 0;
1331 count ++;
1333 if (count == atoi (g_getenv ("COUNT3")))
1334 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
1335 if (count > atoi (g_getenv ("COUNT3")))
1336 slot = 0xffffff;
1337 else
1338 mono_print_ins (inst);
1340 #endif
1342 LSCAN_DEBUG (printf ("R%d %s -> 0x%x\n", inst->dreg, mono_type_full_name (t), slot));
1344 if (inst->flags & MONO_INST_LMF) {
1345 size = MONO_ABI_SIZEOF (MonoLMF);
1346 align = sizeof (target_mgreg_t);
1347 reuse_slot = FALSE;
1350 if (!reuse_slot)
1351 slot = 0xffffff;
1353 if (slot == 0xffffff) {
1355 * Allways allocate valuetypes to sizeof (target_mgreg_t) to allow more
1356 * efficient copying (and to work around the fact that OP_MEMCPY
1357 * and OP_MEMSET ignores alignment).
1359 if (MONO_TYPE_ISSTRUCT (t)) {
1360 align = MAX (align, sizeof (target_mgreg_t));
1361 align = MAX (align, mono_class_min_align (mono_class_from_mono_type_internal (t)));
1364 if (backward) {
1365 offset += size;
1366 offset += align - 1;
1367 offset &= ~(align - 1);
1368 slot = offset;
1370 else {
1371 offset += align - 1;
1372 offset &= ~(align - 1);
1373 slot = offset;
1374 offset += size;
1377 if (*stack_align == 0)
1378 *stack_align = align;
1381 offsets [vmv->idx] = slot;
1383 g_list_free (vars);
1384 for (i = 0; i < MONO_TYPE_PINNED; ++i) {
1385 if (scalar_stack_slots [i].active)
1386 g_list_free (scalar_stack_slots [i].active);
1388 for (i = 0; i < nvtypes; ++i) {
1389 if (vtype_stack_slots [i].active)
1390 g_list_free (vtype_stack_slots [i].active);
1393 cfg->stat_locals_stack_size += offset;
1395 *stack_size = offset;
1396 return offsets;
1400 * mono_allocate_stack_slots:
1402 * Allocate stack slots for all non register allocated variables using a
1403 * linear scan algorithm.
1404 * Returns: an array of stack offsets.
1405 * STACK_SIZE is set to the amount of stack space needed.
1406 * STACK_ALIGN is set to the alignment needed by the locals area.
1408 gint32*
1409 mono_allocate_stack_slots (MonoCompile *cfg, gboolean backward, guint32 *stack_size, guint32 *stack_align)
1411 int i, slot, offset, size;
1412 guint32 align;
1413 MonoMethodVar *vmv;
1414 MonoInst *inst;
1415 gint32 *offsets;
1416 GList *vars = NULL, *l;
1417 StackSlotInfo *scalar_stack_slots, *vtype_stack_slots, *slot_info;
1418 MonoType *t;
1419 int nvtypes;
1420 int vtype_stack_slots_size = 256;
1421 gboolean reuse_slot;
1423 if ((cfg->num_varinfo > 0) && MONO_VARINFO (cfg, 0)->interval)
1424 return mono_allocate_stack_slots2 (cfg, backward, stack_size, stack_align);
1426 scalar_stack_slots = (StackSlotInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * MONO_TYPE_PINNED);
1427 vtype_stack_slots = NULL;
1428 nvtypes = 0;
1430 offsets = (gint32 *)mono_mempool_alloc (cfg->mempool, sizeof (gint32) * cfg->num_varinfo);
1431 for (i = 0; i < cfg->num_varinfo; ++i)
1432 offsets [i] = -1;
1434 for (i = cfg->locals_start; i < cfg->num_varinfo; i++) {
1435 inst = cfg->varinfo [i];
1436 vmv = MONO_VARINFO (cfg, i);
1438 if ((inst->flags & MONO_INST_IS_DEAD) || inst->opcode == OP_REGVAR || inst->opcode == OP_REGOFFSET)
1439 continue;
1441 vars = g_list_prepend (vars, vmv);
1444 vars = mono_varlist_sort (cfg, vars, 0);
1445 offset = 0;
1446 *stack_align = sizeof (target_mgreg_t);
1447 for (l = vars; l; l = l->next) {
1448 vmv = (MonoMethodVar *)l->data;
1449 inst = cfg->varinfo [vmv->idx];
1451 t = mono_type_get_underlying_type (inst->inst_vtype);
1452 if (cfg->gsharedvt && mini_is_gsharedvt_variable_type (t))
1453 continue;
1455 /* inst->backend.is_pinvoke indicates native sized value types, this is used by the
1456 * pinvoke wrappers when they call functions returning structures */
1457 if (inst->backend.is_pinvoke && MONO_TYPE_ISSTRUCT (t) && t->type != MONO_TYPE_TYPEDBYREF) {
1458 size = mono_class_native_size (mono_class_from_mono_type_internal (t), &align);
1459 } else {
1460 int ialign;
1462 size = mini_type_stack_size (t, &ialign);
1463 align = ialign;
1465 if (mono_class_has_failure (mono_class_from_mono_type_internal (t)))
1466 mono_cfg_set_exception (cfg, MONO_EXCEPTION_TYPE_LOAD);
1468 if (MONO_CLASS_IS_SIMD (cfg, mono_class_from_mono_type_internal (t)))
1469 align = 16;
1472 reuse_slot = TRUE;
1473 if (cfg->disable_reuse_stack_slots)
1474 reuse_slot = FALSE;
1476 t = mini_get_underlying_type (t);
1477 switch (t->type) {
1478 case MONO_TYPE_GENERICINST:
1479 if (!mono_type_generic_inst_is_valuetype (t)) {
1480 slot_info = &scalar_stack_slots [t->type];
1481 break;
1483 /* Fall through */
1484 case MONO_TYPE_VALUETYPE:
1485 if (!vtype_stack_slots)
1486 vtype_stack_slots = (StackSlotInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * vtype_stack_slots_size);
1487 for (i = 0; i < nvtypes; ++i)
1488 if (t->data.klass == vtype_stack_slots [i].vtype)
1489 break;
1490 if (i < nvtypes)
1491 slot_info = &vtype_stack_slots [i];
1492 else {
1493 if (nvtypes == vtype_stack_slots_size) {
1494 int new_slots_size = vtype_stack_slots_size * 2;
1495 StackSlotInfo* new_slots = (StackSlotInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (StackSlotInfo) * new_slots_size);
1497 memcpy (new_slots, vtype_stack_slots, sizeof (StackSlotInfo) * vtype_stack_slots_size);
1499 vtype_stack_slots = new_slots;
1500 vtype_stack_slots_size = new_slots_size;
1502 vtype_stack_slots [nvtypes].vtype = t->data.klass;
1503 slot_info = &vtype_stack_slots [nvtypes];
1504 nvtypes ++;
1506 if (cfg->disable_reuse_ref_stack_slots)
1507 reuse_slot = FALSE;
1508 break;
1510 case MONO_TYPE_PTR:
1511 case MONO_TYPE_I:
1512 case MONO_TYPE_U:
1513 #if TARGET_SIZEOF_VOID_P == 4
1514 case MONO_TYPE_I4:
1515 #else
1516 case MONO_TYPE_I8:
1517 #endif
1518 if (cfg->disable_ref_noref_stack_slot_share) {
1519 slot_info = &scalar_stack_slots [MONO_TYPE_I];
1520 break;
1522 /* Fall through */
1524 case MONO_TYPE_CLASS:
1525 case MONO_TYPE_OBJECT:
1526 case MONO_TYPE_ARRAY:
1527 case MONO_TYPE_SZARRAY:
1528 case MONO_TYPE_STRING:
1529 /* Share non-float stack slots of the same size */
1530 slot_info = &scalar_stack_slots [MONO_TYPE_CLASS];
1531 if (cfg->disable_reuse_ref_stack_slots)
1532 reuse_slot = FALSE;
1533 break;
1534 case MONO_TYPE_VAR:
1535 case MONO_TYPE_MVAR:
1536 slot_info = &scalar_stack_slots [t->type];
1537 break;
1538 default:
1539 slot_info = &scalar_stack_slots [t->type];
1540 break;
1543 slot = 0xffffff;
1544 if (cfg->comp_done & MONO_COMP_LIVENESS) {
1545 //printf ("START %2d %08x %08x\n", vmv->idx, vmv->range.first_use.abs_pos, vmv->range.last_use.abs_pos);
1547 /* expire old intervals in active */
1548 while (slot_info->active) {
1549 MonoMethodVar *amv = (MonoMethodVar *)slot_info->active->data;
1551 if (amv->range.last_use.abs_pos > vmv->range.first_use.abs_pos)
1552 break;
1554 //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);
1556 slot_info->active = g_list_delete_link (slot_info->active, slot_info->active);
1557 slot_info->slots = g_slist_prepend_mempool (cfg->mempool, slot_info->slots, GINT_TO_POINTER (offsets [amv->idx]));
1561 * This also handles the case when the variable is used in an
1562 * exception region, as liveness info is not computed there.
1565 * FIXME: All valuetypes are marked as INDIRECT because of LDADDR
1566 * opcodes.
1568 if (! (inst->flags & (MONO_INST_VOLATILE|MONO_INST_INDIRECT))) {
1569 if (slot_info->slots) {
1570 slot = GPOINTER_TO_INT (slot_info->slots->data);
1572 slot_info->slots = slot_info->slots->next;
1575 slot_info->active = mono_varlist_insert_sorted (cfg, slot_info->active, vmv, TRUE);
1579 #if 0
1581 static int count = 0;
1582 count ++;
1584 if (count == atoi (g_getenv ("COUNT")))
1585 printf ("LAST: %s\n", mono_method_full_name (cfg->method, TRUE));
1586 if (count > atoi (g_getenv ("COUNT")))
1587 slot = 0xffffff;
1588 else
1589 mono_print_ins (inst);
1591 #endif
1593 if (inst->flags & MONO_INST_LMF) {
1595 * This variable represents a MonoLMF structure, which has no corresponding
1596 * CLR type, so hard-code its size/alignment.
1598 size = MONO_ABI_SIZEOF (MonoLMF);
1599 align = sizeof (target_mgreg_t);
1600 reuse_slot = FALSE;
1603 if (!reuse_slot)
1604 slot = 0xffffff;
1606 if (slot == 0xffffff) {
1608 * Allways allocate valuetypes to sizeof (target_mgreg_t) to allow more
1609 * efficient copying (and to work around the fact that OP_MEMCPY
1610 * and OP_MEMSET ignores alignment).
1612 if (MONO_TYPE_ISSTRUCT (t)) {
1613 align = MAX (align, sizeof (target_mgreg_t));
1614 align = MAX (align, mono_class_min_align (mono_class_from_mono_type_internal (t)));
1616 * Align the size too so the code generated for passing vtypes in
1617 * registers doesn't overwrite random locals.
1619 size = (size + (align - 1)) & ~(align -1);
1622 if (backward) {
1623 offset += size;
1624 offset += align - 1;
1625 offset &= ~(align - 1);
1626 slot = offset;
1628 else {
1629 offset += align - 1;
1630 offset &= ~(align - 1);
1631 slot = offset;
1632 offset += size;
1635 *stack_align = MAX (*stack_align, align);
1638 offsets [vmv->idx] = slot;
1640 g_list_free (vars);
1641 for (i = 0; i < MONO_TYPE_PINNED; ++i) {
1642 if (scalar_stack_slots [i].active)
1643 g_list_free (scalar_stack_slots [i].active);
1645 for (i = 0; i < nvtypes; ++i) {
1646 if (vtype_stack_slots [i].active)
1647 g_list_free (vtype_stack_slots [i].active);
1650 cfg->stat_locals_stack_size += offset;
1652 *stack_size = offset;
1653 return offsets;
1656 #define EMUL_HIT_SHIFT 3
1657 #define EMUL_HIT_MASK ((1 << EMUL_HIT_SHIFT) - 1)
1658 /* small hit bitmap cache */
1659 static mono_byte emul_opcode_hit_cache [(OP_LAST>>EMUL_HIT_SHIFT) + 1] = {0};
1660 static short emul_opcode_num = 0;
1661 static short emul_opcode_alloced = 0;
1662 static short *emul_opcode_opcodes;
1663 static MonoJitICallInfo **emul_opcode_map;
1665 MonoJitICallInfo *
1666 mono_find_jit_opcode_emulation (int opcode)
1668 g_assert (opcode >= 0 && opcode <= OP_LAST);
1669 if (emul_opcode_hit_cache [opcode >> (EMUL_HIT_SHIFT + 3)] & (1 << (opcode & EMUL_HIT_MASK))) {
1670 int i;
1671 for (i = 0; i < emul_opcode_num; ++i) {
1672 if (emul_opcode_opcodes [i] == opcode)
1673 return emul_opcode_map [i];
1676 return NULL;
1679 void
1680 mini_register_opcode_emulation (int opcode, MonoJitICallInfo *info, const char *name, MonoMethodSignature *sig, gpointer func, const char *symbol, gboolean no_wrapper)
1682 g_assert (info);
1683 g_assert (!sig->hasthis);
1684 g_assert (sig->param_count < 3);
1686 mono_register_jit_icall_info (info, func, name, sig, no_wrapper, symbol);
1688 if (emul_opcode_num >= emul_opcode_alloced) {
1689 int incr = emul_opcode_alloced? emul_opcode_alloced/2: 16;
1690 emul_opcode_alloced += incr;
1691 emul_opcode_map = (MonoJitICallInfo **)g_realloc (emul_opcode_map, sizeof (emul_opcode_map [0]) * emul_opcode_alloced);
1692 emul_opcode_opcodes = (short *)g_realloc (emul_opcode_opcodes, sizeof (emul_opcode_opcodes [0]) * emul_opcode_alloced);
1694 emul_opcode_map [emul_opcode_num] = info;
1695 emul_opcode_opcodes [emul_opcode_num] = opcode;
1696 emul_opcode_num++;
1697 emul_opcode_hit_cache [opcode >> (EMUL_HIT_SHIFT + 3)] |= (1 << (opcode & EMUL_HIT_MASK));
1700 static void
1701 print_dfn (MonoCompile *cfg)
1703 int i, j;
1704 char *code;
1705 MonoBasicBlock *bb;
1706 MonoInst *c;
1709 char *method_name = mono_method_full_name (cfg->method, TRUE);
1710 g_print ("IR code for method %s\n", method_name);
1711 g_free (method_name);
1714 for (i = 0; i < cfg->num_bblocks; ++i) {
1715 bb = cfg->bblocks [i];
1716 /*if (bb->cil_code) {
1717 char* code1, *code2;
1718 code1 = mono_disasm_code_one (NULL, cfg->method, bb->cil_code, NULL);
1719 if (bb->last_ins->cil_code)
1720 code2 = mono_disasm_code_one (NULL, cfg->method, bb->last_ins->cil_code, NULL);
1721 else
1722 code2 = g_strdup ("");
1724 code1 [strlen (code1) - 1] = 0;
1725 code = g_strdup_printf ("%s -> %s", code1, code2);
1726 g_free (code1);
1727 g_free (code2);
1728 } else*/
1729 code = g_strdup ("\n");
1730 g_print ("\nBB%d (%d) (len: %d): %s", bb->block_num, i, bb->cil_length, code);
1731 MONO_BB_FOR_EACH_INS (bb, c) {
1732 mono_print_ins_index (-1, c);
1735 g_print ("\tprev:");
1736 for (j = 0; j < bb->in_count; ++j) {
1737 g_print (" BB%d", bb->in_bb [j]->block_num);
1739 g_print ("\t\tsucc:");
1740 for (j = 0; j < bb->out_count; ++j) {
1741 g_print (" BB%d", bb->out_bb [j]->block_num);
1743 g_print ("\n\tidom: BB%d\n", bb->idom? bb->idom->block_num: -1);
1745 if (bb->idom)
1746 g_assert (mono_bitset_test_fast (bb->dominators, bb->idom->dfn));
1748 if (bb->dominators)
1749 mono_blockset_print (cfg, bb->dominators, "\tdominators", bb->idom? bb->idom->dfn: -1);
1750 if (bb->dfrontier)
1751 mono_blockset_print (cfg, bb->dfrontier, "\tdfrontier", -1);
1752 g_free (code);
1755 g_print ("\n");
1758 void
1759 mono_bblock_add_inst (MonoBasicBlock *bb, MonoInst *inst)
1761 MONO_ADD_INS (bb, inst);
1764 void
1765 mono_bblock_insert_after_ins (MonoBasicBlock *bb, MonoInst *ins, MonoInst *ins_to_insert)
1767 if (ins == NULL) {
1768 ins = bb->code;
1769 bb->code = ins_to_insert;
1771 /* Link with next */
1772 ins_to_insert->next = ins;
1773 if (ins)
1774 ins->prev = ins_to_insert;
1776 if (bb->last_ins == NULL)
1777 bb->last_ins = ins_to_insert;
1778 } else {
1779 /* Link with next */
1780 ins_to_insert->next = ins->next;
1781 if (ins->next)
1782 ins->next->prev = ins_to_insert;
1784 /* Link with previous */
1785 ins->next = ins_to_insert;
1786 ins_to_insert->prev = ins;
1788 if (bb->last_ins == ins)
1789 bb->last_ins = ins_to_insert;
1793 void
1794 mono_bblock_insert_before_ins (MonoBasicBlock *bb, MonoInst *ins, MonoInst *ins_to_insert)
1796 if (ins == NULL) {
1797 ins = bb->code;
1798 if (ins)
1799 ins->prev = ins_to_insert;
1800 bb->code = ins_to_insert;
1801 ins_to_insert->next = ins;
1802 if (bb->last_ins == NULL)
1803 bb->last_ins = ins_to_insert;
1804 } else {
1805 /* Link with previous */
1806 if (ins->prev)
1807 ins->prev->next = ins_to_insert;
1808 ins_to_insert->prev = ins->prev;
1810 /* Link with next */
1811 ins->prev = ins_to_insert;
1812 ins_to_insert->next = ins;
1814 if (bb->code == ins)
1815 bb->code = ins_to_insert;
1820 * mono_verify_bblock:
1822 * Verify that the next and prev pointers are consistent inside the instructions in BB.
1824 void
1825 mono_verify_bblock (MonoBasicBlock *bb)
1827 MonoInst *ins, *prev;
1829 prev = NULL;
1830 for (ins = bb->code; ins; ins = ins->next) {
1831 g_assert (ins->prev == prev);
1832 prev = ins;
1834 if (bb->last_ins)
1835 g_assert (!bb->last_ins->next);
1839 * mono_verify_cfg:
1841 * Perform consistency checks on the JIT data structures and the IR
1843 void
1844 mono_verify_cfg (MonoCompile *cfg)
1846 MonoBasicBlock *bb;
1848 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
1849 mono_verify_bblock (bb);
1852 // This will free many fields in cfg to save
1853 // memory. Note that this must be safe to call
1854 // multiple times. It must be idempotent.
1855 void
1856 mono_empty_compile (MonoCompile *cfg)
1858 mono_free_loop_info (cfg);
1860 // These live in the mempool, and so must be freed
1861 // first
1862 for (GSList *l = cfg->headers_to_free; l; l = l->next) {
1863 mono_metadata_free_mh ((MonoMethodHeader *)l->data);
1865 cfg->headers_to_free = NULL;
1867 if (cfg->mempool) {
1868 //mono_mempool_stats (cfg->mempool);
1869 mono_mempool_destroy (cfg->mempool);
1870 cfg->mempool = NULL;
1873 g_free (cfg->varinfo);
1874 cfg->varinfo = NULL;
1876 g_free (cfg->vars);
1877 cfg->vars = NULL;
1879 if (cfg->rs) {
1880 mono_regstate_free (cfg->rs);
1881 cfg->rs = NULL;
1885 void
1886 mono_destroy_compile (MonoCompile *cfg)
1888 mono_empty_compile (cfg);
1890 mono_metadata_free_mh (cfg->header);
1892 g_hash_table_destroy (cfg->spvars);
1893 g_hash_table_destroy (cfg->exvars);
1894 g_list_free (cfg->ldstr_list);
1895 g_hash_table_destroy (cfg->token_info_hash);
1896 g_hash_table_destroy (cfg->abs_patches);
1898 mono_debug_free_method (cfg);
1900 g_free (cfg->varinfo);
1901 g_free (cfg->vars);
1902 g_free (cfg->exception_message);
1903 g_free (cfg);
1906 void
1907 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
1909 if (type == MONO_PATCH_INFO_NONE)
1910 return;
1912 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfo));
1914 ji->ip.i = ip;
1915 ji->type = type;
1916 ji->data.target = target;
1917 ji->next = cfg->patch_info;
1919 cfg->patch_info = ji;
1922 void
1923 mono_add_patch_info_rel (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target, int relocation)
1925 if (type == MONO_PATCH_INFO_NONE)
1926 return;
1928 MonoJumpInfo *ji = (MonoJumpInfo *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoJumpInfo));
1930 ji->ip.i = ip;
1931 ji->type = type;
1932 ji->relocation = relocation;
1933 ji->data.target = target;
1934 ji->next = cfg->patch_info;
1936 cfg->patch_info = ji;
1939 void
1940 mono_remove_patch_info (MonoCompile *cfg, int ip)
1942 MonoJumpInfo **ji = &cfg->patch_info;
1944 while (*ji) {
1945 if ((*ji)->ip.i == ip)
1946 *ji = (*ji)->next;
1947 else
1948 ji = &((*ji)->next);
1952 void
1953 mono_add_seq_point (MonoCompile *cfg, MonoBasicBlock *bb, MonoInst *ins, int native_offset)
1955 ins->inst_offset = native_offset;
1956 g_ptr_array_add (cfg->seq_points, ins);
1957 if (bb) {
1958 bb->seq_points = g_slist_prepend_mempool (cfg->mempool, bb->seq_points, ins);
1959 bb->last_seq_point = ins;
1963 void
1964 mono_add_var_location (MonoCompile *cfg, MonoInst *var, gboolean is_reg, int reg, int offset, int from, int to)
1966 MonoDwarfLocListEntry *entry = (MonoDwarfLocListEntry *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoDwarfLocListEntry));
1968 if (is_reg)
1969 g_assert (offset == 0);
1971 entry->is_reg = is_reg;
1972 entry->reg = reg;
1973 entry->offset = offset;
1974 entry->from = from;
1975 entry->to = to;
1977 if (var == cfg->args [0])
1978 cfg->this_loclist = g_slist_append_mempool (cfg->mempool, cfg->this_loclist, entry);
1979 else if (var == cfg->rgctx_var)
1980 cfg->rgctx_loclist = g_slist_append_mempool (cfg->mempool, cfg->rgctx_loclist, entry);
1983 static void
1984 mono_apply_volatile (MonoInst *inst, MonoBitSet *set, gsize index)
1986 inst->flags |= mono_bitset_test_safe (set, index) ? MONO_INST_VOLATILE : 0;
1989 static void
1990 mono_compile_create_vars (MonoCompile *cfg)
1992 MonoMethodSignature *sig;
1993 MonoMethodHeader *header;
1994 int i;
1996 header = cfg->header;
1998 sig = mono_method_signature_internal (cfg->method);
2000 if (!MONO_TYPE_IS_VOID (sig->ret)) {
2001 cfg->ret = mono_compile_create_var (cfg, sig->ret, OP_ARG);
2002 /* Inhibit optimizations */
2003 cfg->ret->flags |= MONO_INST_VOLATILE;
2005 if (cfg->verbose_level > 2)
2006 g_print ("creating vars\n");
2008 cfg->args = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, (sig->param_count + sig->hasthis) * sizeof (MonoInst*));
2010 if (sig->hasthis) {
2011 MonoInst* arg = mono_compile_create_var (cfg, m_class_get_this_arg (cfg->method->klass), OP_ARG);
2012 mono_apply_volatile (arg, header->volatile_args, 0);
2013 cfg->args [0] = arg;
2014 cfg->this_arg = arg;
2017 for (i = 0; i < sig->param_count; ++i) {
2018 MonoInst* arg = mono_compile_create_var (cfg, sig->params [i], OP_ARG);
2019 mono_apply_volatile (arg, header->volatile_args, i + sig->hasthis);
2020 cfg->args [i + sig->hasthis] = arg;
2023 if (cfg->verbose_level > 2) {
2024 if (cfg->ret) {
2025 printf ("\treturn : ");
2026 mono_print_ins (cfg->ret);
2029 if (sig->hasthis) {
2030 printf ("\tthis: ");
2031 mono_print_ins (cfg->args [0]);
2034 for (i = 0; i < sig->param_count; ++i) {
2035 printf ("\targ [%d]: ", i);
2036 mono_print_ins (cfg->args [i + sig->hasthis]);
2040 cfg->locals_start = cfg->num_varinfo;
2041 cfg->locals = (MonoInst **)mono_mempool_alloc0 (cfg->mempool, header->num_locals * sizeof (MonoInst*));
2043 if (cfg->verbose_level > 2)
2044 g_print ("creating locals\n");
2046 for (i = 0; i < header->num_locals; ++i) {
2047 if (cfg->verbose_level > 2)
2048 g_print ("\tlocal [%d]: ", i);
2049 cfg->locals [i] = mono_compile_create_var (cfg, header->locals [i], OP_LOCAL);
2050 mono_apply_volatile (cfg->locals [i], header->volatile_locals, i);
2053 if (cfg->verbose_level > 2)
2054 g_print ("locals done\n");
2056 #ifdef ENABLE_LLVM
2057 if (COMPILE_LLVM (cfg))
2058 mono_llvm_create_vars (cfg);
2059 else
2060 mono_arch_create_vars (cfg);
2061 #else
2062 mono_arch_create_vars (cfg);
2063 #endif
2065 if (cfg->method->save_lmf && cfg->create_lmf_var) {
2066 MonoInst *lmf_var = mono_compile_create_var (cfg, mono_get_int_type (), OP_LOCAL);
2067 lmf_var->flags |= MONO_INST_VOLATILE;
2068 lmf_var->flags |= MONO_INST_LMF;
2069 cfg->lmf_var = lmf_var;
2073 void
2074 mono_print_code (MonoCompile *cfg, const char* msg)
2076 MonoBasicBlock *bb;
2078 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2079 mono_print_bb (bb, msg);
2082 static void
2083 mono_postprocess_patches (MonoCompile *cfg)
2085 MonoJumpInfo *patch_info;
2086 int i;
2088 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2089 switch (patch_info->type) {
2090 case MONO_PATCH_INFO_ABS: {
2092 * Change patches of type MONO_PATCH_INFO_ABS into patches describing the
2093 * absolute address.
2095 if (cfg->abs_patches) {
2096 MonoJumpInfo *abs_ji = (MonoJumpInfo *)g_hash_table_lookup (cfg->abs_patches, patch_info->data.target);
2097 if (abs_ji) {
2098 patch_info->type = abs_ji->type;
2099 patch_info->data.target = abs_ji->data.target;
2102 break;
2104 case MONO_PATCH_INFO_SWITCH: {
2105 gpointer *table;
2106 if (cfg->method->dynamic) {
2107 table = (void **)mono_code_manager_reserve (cfg->dynamic_info->code_mp, sizeof (gpointer) * patch_info->data.table->table_size);
2108 } else {
2109 table = (void **)mono_domain_code_reserve (cfg->domain, sizeof (gpointer) * patch_info->data.table->table_size);
2112 for (i = 0; i < patch_info->data.table->table_size; i++) {
2113 /* Might be NULL if the switch is eliminated */
2114 if (patch_info->data.table->table [i]) {
2115 g_assert (patch_info->data.table->table [i]->native_offset);
2116 table [i] = GINT_TO_POINTER (patch_info->data.table->table [i]->native_offset);
2117 } else {
2118 table [i] = NULL;
2121 patch_info->data.table->table = (MonoBasicBlock**)table;
2122 break;
2124 default:
2125 /* do nothing */
2126 break;
2131 /* Those patches require the JitInfo of the compiled method already be in place when used */
2132 static void
2133 mono_postprocess_patches_after_ji_publish (MonoCompile *cfg)
2135 MonoJumpInfo *patch_info;
2137 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
2138 switch (patch_info->type) {
2139 case MONO_PATCH_INFO_METHOD_JUMP: {
2140 unsigned char *ip = cfg->native_code + patch_info->ip.i;
2142 mini_register_jump_site (cfg->domain, patch_info->data.method, ip);
2143 break;
2145 default:
2146 /* do nothing */
2147 break;
2152 void
2153 mono_codegen (MonoCompile *cfg)
2155 MonoBasicBlock *bb;
2156 int max_epilog_size;
2157 guint8 *code;
2158 MonoDomain *code_domain;
2159 guint unwindlen = 0;
2161 if (mono_using_xdebug)
2163 * Recent gdb versions have trouble processing symbol files containing
2164 * overlapping address ranges, so allocate all code from the code manager
2165 * of the root domain. (#666152).
2167 code_domain = mono_get_root_domain ();
2168 else
2169 code_domain = cfg->domain;
2171 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2172 cfg->spill_count = 0;
2173 /* we reuse dfn here */
2174 /* bb->dfn = bb_count++; */
2176 mono_arch_lowering_pass (cfg, bb);
2178 if (cfg->opt & MONO_OPT_PEEPHOLE)
2179 mono_arch_peephole_pass_1 (cfg, bb);
2181 mono_local_regalloc (cfg, bb);
2183 if (cfg->opt & MONO_OPT_PEEPHOLE)
2184 mono_arch_peephole_pass_2 (cfg, bb);
2186 if (cfg->gen_seq_points && !cfg->gen_sdb_seq_points)
2187 mono_bb_deduplicate_op_il_seq_points (cfg, bb);
2190 code = mono_arch_emit_prolog (cfg);
2192 set_code_cursor (cfg, code);
2193 cfg->prolog_end = cfg->code_len;
2194 cfg->cfa_reg = cfg->cur_cfa_reg;
2195 cfg->cfa_offset = cfg->cur_cfa_offset;
2197 mono_debug_open_method (cfg);
2199 /* emit code all basic blocks */
2200 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2201 bb->native_offset = cfg->code_len;
2202 bb->real_native_offset = cfg->code_len;
2203 //if ((bb == cfg->bb_entry) || !(bb->region == -1 && !bb->dfn))
2204 mono_arch_output_basic_block (cfg, bb);
2205 bb->native_length = cfg->code_len - bb->native_offset;
2207 if (bb == cfg->bb_exit) {
2208 cfg->epilog_begin = cfg->code_len;
2209 mono_arch_emit_epilog (cfg);
2210 cfg->epilog_end = cfg->code_len;
2213 if (bb->clause_holes) {
2214 GList *tmp;
2215 for (tmp = bb->clause_holes; tmp; tmp = tmp->prev)
2216 mono_cfg_add_try_hole (cfg, ((MonoLeaveClause *) tmp->data)->clause, cfg->native_code + bb->native_offset, bb);
2220 mono_arch_emit_exceptions (cfg);
2222 max_epilog_size = 0;
2224 /* we always allocate code in cfg->domain->code_mp to increase locality */
2225 cfg->code_size = cfg->code_len + max_epilog_size;
2227 /* fixme: align to MONO_ARCH_CODE_ALIGNMENT */
2229 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
2230 if (!cfg->compile_aot)
2231 unwindlen = mono_arch_unwindinfo_init_method_unwind_info (cfg);
2232 #endif
2234 if (cfg->method->dynamic) {
2235 /* Allocate the code into a separate memory pool so it can be freed */
2236 cfg->dynamic_info = g_new0 (MonoJitDynamicMethodInfo, 1);
2237 cfg->dynamic_info->code_mp = mono_code_manager_new_dynamic ();
2238 mono_domain_lock (cfg->domain);
2239 mono_dynamic_code_hash_insert (cfg->domain, cfg->method, cfg->dynamic_info);
2240 mono_domain_unlock (cfg->domain);
2242 if (mono_using_xdebug)
2243 /* See the comment for cfg->code_domain */
2244 code = (guint8 *)mono_domain_code_reserve (code_domain, cfg->code_size + cfg->thunk_area + unwindlen);
2245 else
2246 code = (guint8 *)mono_code_manager_reserve (cfg->dynamic_info->code_mp, cfg->code_size + cfg->thunk_area + unwindlen);
2247 } else {
2248 code = (guint8 *)mono_domain_code_reserve (code_domain, cfg->code_size + cfg->thunk_area + unwindlen);
2251 if (cfg->thunk_area) {
2252 cfg->thunks_offset = cfg->code_size + unwindlen;
2253 cfg->thunks = code + cfg->thunks_offset;
2254 memset (cfg->thunks, 0, cfg->thunk_area);
2257 g_assert (code);
2258 memcpy (code, cfg->native_code, cfg->code_len);
2259 g_free (cfg->native_code);
2260 cfg->native_code = code;
2261 code = cfg->native_code + cfg->code_len;
2263 /* g_assert (((int)cfg->native_code & (MONO_ARCH_CODE_ALIGNMENT - 1)) == 0); */
2264 mono_postprocess_patches (cfg);
2266 #ifdef VALGRIND_JIT_REGISTER_MAP
2267 if (valgrind_register){
2268 char* nm = mono_method_full_name (cfg->method, TRUE);
2269 VALGRIND_JIT_REGISTER_MAP (nm, cfg->native_code, cfg->native_code + cfg->code_len);
2270 g_free (nm);
2272 #endif
2274 if (cfg->verbose_level > 0) {
2275 char* nm = mono_method_get_full_name (cfg->method);
2276 g_print ("Method %s emitted at %p to %p (code length %d) [%s]\n",
2277 nm,
2278 cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
2279 g_free (nm);
2283 gboolean is_generic = FALSE;
2285 if (cfg->method->is_inflated || mono_method_get_generic_container (cfg->method) ||
2286 mono_class_is_gtd (cfg->method->klass) || mono_class_is_ginst (cfg->method->klass)) {
2287 is_generic = TRUE;
2290 if (cfg->gshared)
2291 g_assert (is_generic);
2294 #ifdef MONO_ARCH_HAVE_SAVE_UNWIND_INFO
2295 mono_arch_save_unwind_info (cfg);
2296 #endif
2298 #ifdef MONO_ARCH_HAVE_PATCH_CODE_NEW
2300 MonoJumpInfo *ji;
2301 gpointer target;
2303 for (ji = cfg->patch_info; ji; ji = ji->next) {
2304 if (cfg->compile_aot) {
2305 switch (ji->type) {
2306 case MONO_PATCH_INFO_BB:
2307 case MONO_PATCH_INFO_LABEL:
2308 break;
2309 default:
2310 /* No need to patch these */
2311 continue;
2315 if (ji->type == MONO_PATCH_INFO_NONE)
2316 continue;
2318 target = mono_resolve_patch_target (cfg->method, cfg->domain, cfg->native_code, ji, cfg->run_cctors, cfg->error);
2319 if (!is_ok (cfg->error)) {
2320 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
2321 return;
2323 mono_arch_patch_code_new (cfg, cfg->domain, cfg->native_code, ji, target);
2326 #else
2327 mono_arch_patch_code (cfg, cfg->method, cfg->domain, cfg->native_code, cfg->patch_info, cfg->run_cctors, cfg->error);
2328 if (!is_ok (cfg->error)) {
2329 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
2330 return;
2332 #endif
2334 if (cfg->method->dynamic) {
2335 if (mono_using_xdebug)
2336 mono_domain_code_commit (code_domain, cfg->native_code, cfg->code_size, cfg->code_len);
2337 else
2338 mono_code_manager_commit (cfg->dynamic_info->code_mp, cfg->native_code, cfg->code_size, cfg->code_len);
2339 } else {
2340 mono_domain_code_commit (code_domain, cfg->native_code, cfg->code_size, cfg->code_len);
2342 MONO_PROFILER_RAISE (jit_code_buffer, (cfg->native_code, cfg->code_len, MONO_PROFILER_CODE_BUFFER_METHOD, cfg->method));
2344 mono_arch_flush_icache (cfg->native_code, cfg->code_len);
2346 mono_debug_close_method (cfg);
2348 #ifdef MONO_ARCH_HAVE_UNWIND_TABLE
2349 if (!cfg->compile_aot)
2350 mono_arch_unwindinfo_install_method_unwind_info (&cfg->arch.unwindinfo, cfg->native_code, cfg->code_len);
2351 #endif
2354 static void
2355 compute_reachable (MonoBasicBlock *bb)
2357 int i;
2359 if (!(bb->flags & BB_VISITED)) {
2360 bb->flags |= BB_VISITED;
2361 for (i = 0; i < bb->out_count; ++i)
2362 compute_reachable (bb->out_bb [i]);
2366 static void mono_bb_ordering (MonoCompile *cfg)
2368 int dfn = 0;
2369 /* Depth-first ordering on basic blocks */
2370 cfg->bblocks = (MonoBasicBlock **)mono_mempool_alloc (cfg->mempool, sizeof (MonoBasicBlock*) * (cfg->num_bblocks + 1));
2372 cfg->max_block_num = cfg->num_bblocks;
2374 df_visit (cfg->bb_entry, &dfn, cfg->bblocks);
2376 #if defined(__GNUC__) && __GNUC__ == 7 && defined(__x86_64__)
2377 /* workaround for an AMD specific issue that only happens on GCC 7 so far,
2378 * for more information see https://github.com/mono/mono/issues/9298 */
2379 mono_memory_barrier ();
2380 #endif
2381 g_assertf (cfg->num_bblocks >= dfn, "cfg->num_bblocks=%d, dfn=%d\n", cfg->num_bblocks, dfn);
2383 if (cfg->num_bblocks != dfn + 1) {
2384 MonoBasicBlock *bb;
2386 cfg->num_bblocks = dfn + 1;
2388 /* remove unreachable code, because the code in them may be
2389 * inconsistent (access to dead variables for example) */
2390 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2391 bb->flags &= ~BB_VISITED;
2392 compute_reachable (cfg->bb_entry);
2393 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2394 if (bb->flags & BB_EXCEPTION_HANDLER)
2395 compute_reachable (bb);
2396 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2397 if (!(bb->flags & BB_VISITED)) {
2398 if (cfg->verbose_level > 1)
2399 g_print ("found unreachable code in BB%d\n", bb->block_num);
2400 bb->code = bb->last_ins = NULL;
2401 while (bb->out_count)
2402 mono_unlink_bblock (cfg, bb, bb->out_bb [0]);
2405 for (bb = cfg->bb_entry; bb; bb = bb->next_bb)
2406 bb->flags &= ~BB_VISITED;
2410 static void
2411 mono_handle_out_of_line_bblock (MonoCompile *cfg)
2413 MonoBasicBlock *bb;
2414 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2415 if (bb->next_bb && bb->next_bb->out_of_line && bb->last_ins && !MONO_IS_BRANCH_OP (bb->last_ins)) {
2416 MonoInst *ins;
2417 MONO_INST_NEW (cfg, ins, OP_BR);
2418 MONO_ADD_INS (bb, ins);
2419 ins->inst_target_bb = bb->next_bb;
2424 static MonoJitInfo*
2425 create_jit_info (MonoCompile *cfg, MonoMethod *method_to_compile)
2427 GSList *tmp;
2428 MonoMethodHeader *header;
2429 MonoJitInfo *jinfo;
2430 MonoJitInfoFlags flags = JIT_INFO_NONE;
2431 int num_clauses, num_holes = 0;
2432 guint32 stack_size = 0;
2434 g_assert (method_to_compile == cfg->method);
2435 header = cfg->header;
2437 if (cfg->gshared)
2438 flags |= JIT_INFO_HAS_GENERIC_JIT_INFO;
2440 if (cfg->arch_eh_jit_info) {
2441 MonoJitArgumentInfo *arg_info;
2442 MonoMethodSignature *sig = mono_method_signature_internal (cfg->method_to_register);
2445 * This cannot be computed during stack walking, as
2446 * mono_arch_get_argument_info () is not signal safe.
2448 arg_info = g_newa (MonoJitArgumentInfo, sig->param_count + 1);
2449 stack_size = mono_arch_get_argument_info (sig, sig->param_count, arg_info);
2451 if (stack_size)
2452 flags |= JIT_INFO_HAS_ARCH_EH_INFO;
2455 if (cfg->has_unwind_info_for_epilog && !(flags & JIT_INFO_HAS_ARCH_EH_INFO))
2456 flags |= JIT_INFO_HAS_ARCH_EH_INFO;
2458 if (cfg->thunk_area)
2459 flags |= JIT_INFO_HAS_THUNK_INFO;
2461 if (cfg->try_block_holes) {
2462 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
2463 TryBlockHole *hole = (TryBlockHole *)tmp->data;
2464 MonoExceptionClause *ec = hole->clause;
2465 int hole_end = hole->basic_block->native_offset + hole->basic_block->native_length;
2466 MonoBasicBlock *clause_last_bb = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
2467 g_assert (clause_last_bb);
2469 /* Holes at the end of a try region can be represented by simply reducing the size of the block itself.*/
2470 if (clause_last_bb->native_offset != hole_end)
2471 ++num_holes;
2473 if (num_holes)
2474 flags |= JIT_INFO_HAS_TRY_BLOCK_HOLES;
2475 if (G_UNLIKELY (cfg->verbose_level >= 4))
2476 printf ("Number of try block holes %d\n", num_holes);
2479 if (COMPILE_LLVM (cfg))
2480 num_clauses = cfg->llvm_ex_info_len;
2481 else
2482 num_clauses = header->num_clauses;
2484 if (cfg->method->dynamic)
2485 jinfo = (MonoJitInfo *)g_malloc0 (mono_jit_info_size (flags, num_clauses, num_holes));
2486 else
2487 jinfo = (MonoJitInfo *)mono_domain_alloc0 (cfg->domain, mono_jit_info_size (flags, num_clauses, num_holes));
2488 jinfo_try_holes_size += num_holes * sizeof (MonoTryBlockHoleJitInfo);
2490 mono_jit_info_init (jinfo, cfg->method_to_register, cfg->native_code, cfg->code_len, flags, num_clauses, num_holes);
2491 jinfo->domain_neutral = (cfg->opt & MONO_OPT_SHARED) != 0;
2493 if (COMPILE_LLVM (cfg))
2494 jinfo->from_llvm = TRUE;
2496 if (cfg->gshared) {
2497 MonoInst *inst;
2498 MonoGenericJitInfo *gi;
2499 GSList *loclist = NULL;
2501 gi = mono_jit_info_get_generic_jit_info (jinfo);
2502 g_assert (gi);
2504 if (cfg->method->dynamic)
2505 gi->generic_sharing_context = g_new0 (MonoGenericSharingContext, 1);
2506 else
2507 gi->generic_sharing_context = (MonoGenericSharingContext *)mono_domain_alloc0 (cfg->domain, sizeof (MonoGenericSharingContext));
2508 mini_init_gsctx (cfg->method->dynamic ? NULL : cfg->domain, NULL, cfg->gsctx_context, gi->generic_sharing_context);
2510 if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
2511 mini_method_get_context (method_to_compile)->method_inst ||
2512 m_class_is_valuetype (method_to_compile->klass)) {
2513 g_assert (cfg->rgctx_var);
2516 gi->has_this = 1;
2518 if ((method_to_compile->flags & METHOD_ATTRIBUTE_STATIC) ||
2519 mini_method_get_context (method_to_compile)->method_inst ||
2520 m_class_is_valuetype (method_to_compile->klass)) {
2521 inst = cfg->rgctx_var;
2522 if (!COMPILE_LLVM (cfg))
2523 g_assert (inst->opcode == OP_REGOFFSET);
2524 loclist = cfg->rgctx_loclist;
2525 } else {
2526 inst = cfg->args [0];
2527 loclist = cfg->this_loclist;
2530 if (loclist) {
2531 /* Needed to handle async exceptions */
2532 GSList *l;
2533 int i;
2535 gi->nlocs = g_slist_length (loclist);
2536 if (cfg->method->dynamic)
2537 gi->locations = (MonoDwarfLocListEntry *)g_malloc0 (gi->nlocs * sizeof (MonoDwarfLocListEntry));
2538 else
2539 gi->locations = (MonoDwarfLocListEntry *)mono_domain_alloc0 (cfg->domain, gi->nlocs * sizeof (MonoDwarfLocListEntry));
2540 i = 0;
2541 for (l = loclist; l; l = l->next) {
2542 memcpy (&(gi->locations [i]), l->data, sizeof (MonoDwarfLocListEntry));
2543 i ++;
2547 if (COMPILE_LLVM (cfg)) {
2548 g_assert (cfg->llvm_this_reg != -1);
2549 gi->this_in_reg = 0;
2550 gi->this_reg = cfg->llvm_this_reg;
2551 gi->this_offset = cfg->llvm_this_offset;
2552 } else if (inst->opcode == OP_REGVAR) {
2553 gi->this_in_reg = 1;
2554 gi->this_reg = inst->dreg;
2555 } else {
2556 g_assert (inst->opcode == OP_REGOFFSET);
2557 #ifdef TARGET_X86
2558 g_assert (inst->inst_basereg == X86_EBP);
2559 #elif defined(TARGET_AMD64)
2560 g_assert (inst->inst_basereg == X86_EBP || inst->inst_basereg == X86_ESP);
2561 #endif
2562 g_assert (inst->inst_offset >= G_MININT32 && inst->inst_offset <= G_MAXINT32);
2564 gi->this_in_reg = 0;
2565 gi->this_reg = inst->inst_basereg;
2566 gi->this_offset = inst->inst_offset;
2570 if (num_holes) {
2571 MonoTryBlockHoleTableJitInfo *table;
2572 int i;
2574 table = mono_jit_info_get_try_block_hole_table_info (jinfo);
2575 table->num_holes = (guint16)num_holes;
2576 i = 0;
2577 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
2578 guint32 start_bb_offset;
2579 MonoTryBlockHoleJitInfo *hole;
2580 TryBlockHole *hole_data = (TryBlockHole *)tmp->data;
2581 MonoExceptionClause *ec = hole_data->clause;
2582 int hole_end = hole_data->basic_block->native_offset + hole_data->basic_block->native_length;
2583 MonoBasicBlock *clause_last_bb = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
2584 g_assert (clause_last_bb);
2586 /* Holes at the end of a try region can be represented by simply reducing the size of the block itself.*/
2587 if (clause_last_bb->native_offset == hole_end)
2588 continue;
2590 start_bb_offset = hole_data->start_offset - hole_data->basic_block->native_offset;
2591 hole = &table->holes [i++];
2592 hole->clause = hole_data->clause - &header->clauses [0];
2593 hole->offset = (guint32)hole_data->start_offset;
2594 hole->length = (guint16)(hole_data->basic_block->native_length - start_bb_offset);
2596 if (G_UNLIKELY (cfg->verbose_level >= 4))
2597 printf ("\tTry block hole at eh clause %d offset %x length %x\n", hole->clause, hole->offset, hole->length);
2599 g_assert (i == num_holes);
2602 if (jinfo->has_arch_eh_info) {
2603 MonoArchEHJitInfo *info;
2605 info = mono_jit_info_get_arch_eh_info (jinfo);
2607 info->stack_size = stack_size;
2610 if (cfg->thunk_area) {
2611 MonoThunkJitInfo *info;
2613 info = mono_jit_info_get_thunk_info (jinfo);
2614 info->thunks_offset = cfg->thunks_offset;
2615 info->thunks_size = cfg->thunk_area;
2618 if (COMPILE_LLVM (cfg)) {
2619 if (num_clauses)
2620 memcpy (&jinfo->clauses [0], &cfg->llvm_ex_info [0], num_clauses * sizeof (MonoJitExceptionInfo));
2621 } else if (header->num_clauses) {
2622 int i;
2624 for (i = 0; i < header->num_clauses; i++) {
2625 MonoExceptionClause *ec = &header->clauses [i];
2626 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
2627 MonoBasicBlock *tblock;
2628 MonoInst *exvar;
2630 ei->flags = ec->flags;
2632 if (G_UNLIKELY (cfg->verbose_level >= 4))
2633 printf ("IL clause: try 0x%x-0x%x handler 0x%x-0x%x filter 0x%x\n", ec->try_offset, ec->try_offset + ec->try_len, ec->handler_offset, ec->handler_offset + ec->handler_len, ec->flags == MONO_EXCEPTION_CLAUSE_FILTER ? ec->data.filter_offset : 0);
2635 exvar = mono_find_exvar_for_offset (cfg, ec->handler_offset);
2636 ei->exvar_offset = exvar ? exvar->inst_offset : 0;
2638 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER) {
2639 tblock = cfg->cil_offset_to_bb [ec->data.filter_offset];
2640 g_assert (tblock);
2641 ei->data.filter = cfg->native_code + tblock->native_offset;
2642 } else {
2643 ei->data.catch_class = ec->data.catch_class;
2646 tblock = cfg->cil_offset_to_bb [ec->try_offset];
2647 g_assert (tblock);
2648 g_assert (tblock->native_offset);
2649 ei->try_start = cfg->native_code + tblock->native_offset;
2650 if (tblock->extend_try_block) {
2652 * Extend the try block backwards to include parts of the previous call
2653 * instruction.
2655 ei->try_start = (guint8*)ei->try_start - cfg->backend->monitor_enter_adjustment;
2657 if (ec->try_offset + ec->try_len < header->code_size)
2658 tblock = cfg->cil_offset_to_bb [ec->try_offset + ec->try_len];
2659 else
2660 tblock = cfg->bb_exit;
2661 if (G_UNLIKELY (cfg->verbose_level >= 4))
2662 printf ("looking for end of try [%d, %d] -> %p (code size %d)\n", ec->try_offset, ec->try_len, tblock, header->code_size);
2663 g_assert (tblock);
2664 if (!tblock->native_offset) {
2665 int j, end;
2666 for (j = ec->try_offset + ec->try_len, end = ec->try_offset; j >= end; --j) {
2667 MonoBasicBlock *bb = cfg->cil_offset_to_bb [j];
2668 if (bb && bb->native_offset) {
2669 tblock = bb;
2670 break;
2674 ei->try_end = cfg->native_code + tblock->native_offset;
2675 g_assert (tblock->native_offset);
2676 tblock = cfg->cil_offset_to_bb [ec->handler_offset];
2677 g_assert (tblock);
2678 ei->handler_start = cfg->native_code + tblock->native_offset;
2680 for (tmp = cfg->try_block_holes; tmp; tmp = tmp->next) {
2681 TryBlockHole *hole = (TryBlockHole *)tmp->data;
2682 gpointer hole_end = cfg->native_code + (hole->basic_block->native_offset + hole->basic_block->native_length);
2683 if (hole->clause == ec && hole_end == ei->try_end) {
2684 if (G_UNLIKELY (cfg->verbose_level >= 4))
2685 printf ("\tShortening try block %d from %x to %x\n", i, (int)((guint8*)ei->try_end - cfg->native_code), hole->start_offset);
2687 ei->try_end = cfg->native_code + hole->start_offset;
2688 break;
2692 if (ec->flags == MONO_EXCEPTION_CLAUSE_FINALLY) {
2693 int end_offset;
2694 if (ec->handler_offset + ec->handler_len < header->code_size) {
2695 tblock = cfg->cil_offset_to_bb [ec->handler_offset + ec->handler_len];
2696 if (tblock->native_offset) {
2697 end_offset = tblock->native_offset;
2698 } else {
2699 int j, end;
2701 for (j = ec->handler_offset + ec->handler_len, end = ec->handler_offset; j >= end; --j) {
2702 MonoBasicBlock *bb = cfg->cil_offset_to_bb [j];
2703 if (bb && bb->native_offset) {
2704 tblock = bb;
2705 break;
2708 end_offset = tblock->native_offset + tblock->native_length;
2710 } else {
2711 end_offset = cfg->epilog_begin;
2713 ei->data.handler_end = cfg->native_code + end_offset;
2718 if (G_UNLIKELY (cfg->verbose_level >= 4)) {
2719 int i;
2720 for (i = 0; i < jinfo->num_clauses; i++) {
2721 MonoJitExceptionInfo *ei = &jinfo->clauses [i];
2722 int start = (guint8*)ei->try_start - cfg->native_code;
2723 int end = (guint8*)ei->try_end - cfg->native_code;
2724 int handler = (guint8*)ei->handler_start - cfg->native_code;
2725 int handler_end = (guint8*)ei->data.handler_end - cfg->native_code;
2727 printf ("JitInfo EH clause %d flags %x try %x-%x handler %x-%x\n", i, ei->flags, start, end, handler, handler_end);
2731 if (cfg->encoded_unwind_ops) {
2732 /* Generated by LLVM */
2733 jinfo->unwind_info = mono_cache_unwind_info (cfg->encoded_unwind_ops, cfg->encoded_unwind_ops_len);
2734 g_free (cfg->encoded_unwind_ops);
2735 } else if (cfg->unwind_ops) {
2736 guint32 info_len;
2737 guint8 *unwind_info = mono_unwind_ops_encode (cfg->unwind_ops, &info_len);
2738 guint32 unwind_desc;
2740 unwind_desc = mono_cache_unwind_info (unwind_info, info_len);
2742 if (cfg->has_unwind_info_for_epilog) {
2743 MonoArchEHJitInfo *info;
2745 info = mono_jit_info_get_arch_eh_info (jinfo);
2746 g_assert (info);
2747 info->epilog_size = cfg->code_len - cfg->epilog_begin;
2749 jinfo->unwind_info = unwind_desc;
2750 g_free (unwind_info);
2751 } else {
2752 jinfo->unwind_info = cfg->used_int_regs;
2755 return jinfo;
2758 /* Return whenever METHOD is a gsharedvt method */
2759 static gboolean
2760 is_gsharedvt_method (MonoMethod *method)
2762 MonoGenericContext *context;
2763 MonoGenericInst *inst;
2764 int i;
2766 if (!method->is_inflated)
2767 return FALSE;
2768 context = mono_method_get_context (method);
2769 inst = context->class_inst;
2770 if (inst) {
2771 for (i = 0; i < inst->type_argc; ++i)
2772 if (mini_is_gsharedvt_gparam (inst->type_argv [i]))
2773 return TRUE;
2775 inst = context->method_inst;
2776 if (inst) {
2777 for (i = 0; i < inst->type_argc; ++i)
2778 if (mini_is_gsharedvt_gparam (inst->type_argv [i]))
2779 return TRUE;
2781 return FALSE;
2784 static gboolean
2785 is_open_method (MonoMethod *method)
2787 MonoGenericContext *context;
2789 if (!method->is_inflated)
2790 return FALSE;
2791 context = mono_method_get_context (method);
2792 if (context->class_inst && context->class_inst->is_open)
2793 return TRUE;
2794 if (context->method_inst && context->method_inst->is_open)
2795 return TRUE;
2796 return FALSE;
2799 static void
2800 mono_insert_nop_in_empty_bb (MonoCompile *cfg)
2802 MonoBasicBlock *bb;
2803 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2804 if (bb->code)
2805 continue;
2806 MonoInst *nop;
2807 MONO_INST_NEW (cfg, nop, OP_NOP);
2808 MONO_ADD_INS (bb, nop);
2811 static void
2812 insert_safepoint (MonoCompile *cfg, MonoBasicBlock *bblock)
2814 MonoInst *poll_addr, *ins;
2816 if (cfg->disable_gc_safe_points)
2817 return;
2819 if (cfg->verbose_level > 1)
2820 printf ("ADDING SAFE POINT TO BB %d\n", bblock->block_num);
2822 g_assert (mini_safepoints_enabled ());
2823 NEW_AOTCONST (cfg, poll_addr, MONO_PATCH_INFO_GC_SAFE_POINT_FLAG, (gpointer)&mono_polling_required);
2825 MONO_INST_NEW (cfg, ins, OP_GC_SAFE_POINT);
2826 ins->sreg1 = poll_addr->dreg;
2828 if (bblock->flags & BB_EXCEPTION_HANDLER) {
2829 MonoInst *eh_op = bblock->code;
2831 if (eh_op && eh_op->opcode != OP_START_HANDLER && eh_op->opcode != OP_GET_EX_OBJ) {
2832 eh_op = NULL;
2833 } else {
2834 MonoInst *next_eh_op = eh_op ? eh_op->next : NULL;
2835 // skip all EH relateds ops
2836 while (next_eh_op && (next_eh_op->opcode == OP_START_HANDLER || next_eh_op->opcode == OP_GET_EX_OBJ)) {
2837 eh_op = next_eh_op;
2838 next_eh_op = eh_op->next;
2842 mono_bblock_insert_after_ins (bblock, eh_op, poll_addr);
2843 mono_bblock_insert_after_ins (bblock, poll_addr, ins);
2844 } else if (bblock == cfg->bb_entry) {
2845 mono_bblock_insert_after_ins (bblock, bblock->last_ins, poll_addr);
2846 mono_bblock_insert_after_ins (bblock, poll_addr, ins);
2848 } else {
2849 mono_bblock_insert_before_ins (bblock, NULL, poll_addr);
2850 mono_bblock_insert_after_ins (bblock, poll_addr, ins);
2855 This code inserts safepoints into managed code at important code paths.
2856 Those are:
2858 -the first basic block
2859 -landing BB for exception handlers
2860 -loop body starts.
2863 static void
2864 insert_safepoints (MonoCompile *cfg)
2866 MonoBasicBlock *bb;
2868 g_assert (mini_safepoints_enabled ());
2870 #ifndef MONO_LLVM_LOADED
2871 if (COMPILE_LLVM (cfg)) {
2872 if (!cfg->llvm_only) {
2873 /* We rely on LLVM's safepoints insertion capabilities. */
2874 if (cfg->verbose_level > 1)
2875 printf ("SKIPPING SAFEPOINTS for code compiled with LLVM\n");
2876 return;
2879 #endif
2881 if (cfg->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
2882 WrapperInfo *info = mono_marshal_get_wrapper_info (cfg->method);
2883 /* These wrappers are called from the wrapper for the polling function, leading to potential stack overflow */
2884 if (info && info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER &&
2885 (info->d.icall.jit_icall_id == MONO_JIT_ICALL_mono_threads_state_poll ||
2886 info->d.icall.jit_icall_id == MONO_JIT_ICALL_mono_thread_interruption_checkpoint ||
2887 info->d.icall.jit_icall_id == MONO_JIT_ICALL_mono_threads_exit_gc_safe_region_unbalanced)) {
2888 if (cfg->verbose_level > 1)
2889 printf ("SKIPPING SAFEPOINTS for the polling function icall\n");
2890 return;
2894 if (cfg->method->wrapper_type == MONO_WRAPPER_NATIVE_TO_MANAGED) {
2895 if (cfg->verbose_level > 1)
2896 printf ("SKIPPING SAFEPOINTS for native-to-managed wrappers.\n");
2897 return;
2900 if (cfg->method->wrapper_type == MONO_WRAPPER_OTHER) {
2901 WrapperInfo *info = mono_marshal_get_wrapper_info (cfg->method);
2903 if (info && (info->subtype == WRAPPER_SUBTYPE_INTERP_IN || info->subtype == WRAPPER_SUBTYPE_INTERP_LMF)) {
2904 /* These wrappers shouldn't do any icalls */
2905 if (cfg->verbose_level > 1)
2906 printf ("SKIPPING SAFEPOINTS for interp-in wrappers.\n");
2907 return;
2911 if (cfg->verbose_level > 1)
2912 printf ("INSERTING SAFEPOINTS\n");
2913 if (cfg->verbose_level > 2)
2914 mono_print_code (cfg, "BEFORE SAFEPOINTS");
2916 /* if the method doesn't contain
2917 * (1) a call (so it's a leaf method)
2918 * (2) and no loops
2919 * we can skip the GC safepoint on method entry. */
2920 gboolean requires_safepoint = cfg->has_calls;
2922 for (bb = cfg->bb_entry->next_bb; bb; bb = bb->next_bb) {
2923 if (bb->loop_body_start || (bb->flags & BB_EXCEPTION_HANDLER)) {
2924 requires_safepoint = TRUE;
2925 insert_safepoint (cfg, bb);
2929 if (requires_safepoint)
2930 insert_safepoint (cfg, cfg->bb_entry);
2932 if (cfg->verbose_level > 2)
2933 mono_print_code (cfg, "AFTER SAFEPOINTS");
2938 static void
2939 mono_insert_branches_between_bblocks (MonoCompile *cfg)
2941 MonoBasicBlock *bb;
2943 /* Add branches between non-consecutive bblocks */
2944 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2945 if (bb->last_ins && MONO_IS_COND_BRANCH_OP (bb->last_ins) &&
2946 bb->last_ins->inst_false_bb && bb->next_bb != bb->last_ins->inst_false_bb) {
2947 /* we are careful when inverting, since bugs like #59580
2948 * could show up when dealing with NaNs.
2950 if (MONO_IS_COND_BRANCH_NOFP(bb->last_ins) && bb->next_bb == bb->last_ins->inst_true_bb) {
2951 MonoBasicBlock *tmp = bb->last_ins->inst_true_bb;
2952 bb->last_ins->inst_true_bb = bb->last_ins->inst_false_bb;
2953 bb->last_ins->inst_false_bb = tmp;
2955 bb->last_ins->opcode = mono_reverse_branch_op (bb->last_ins->opcode);
2956 } else {
2957 MonoInst *inst = (MonoInst *)mono_mempool_alloc0 (cfg->mempool, sizeof (MonoInst));
2958 inst->opcode = OP_BR;
2959 inst->inst_target_bb = bb->last_ins->inst_false_bb;
2960 mono_bblock_add_inst (bb, inst);
2965 if (cfg->verbose_level >= 4) {
2966 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2967 MonoInst *tree = bb->code;
2968 g_print ("DUMP BLOCK %d:\n", bb->block_num);
2969 if (!tree)
2970 continue;
2971 for (; tree; tree = tree->next) {
2972 mono_print_ins_index (-1, tree);
2977 /* FIXME: */
2978 for (bb = cfg->bb_entry; bb; bb = bb->next_bb) {
2979 bb->max_vreg = cfg->next_vreg;
2983 static void
2984 init_backend (MonoBackend *backend)
2986 #ifdef MONO_ARCH_NEED_GOT_VAR
2987 backend->need_got_var = 1;
2988 #endif
2989 #ifdef MONO_ARCH_HAVE_CARD_TABLE_WBARRIER
2990 backend->have_card_table_wb = 1;
2991 #endif
2992 #ifdef MONO_ARCH_HAVE_OP_GENERIC_CLASS_INIT
2993 backend->have_op_generic_class_init = 1;
2994 #endif
2995 #ifdef MONO_ARCH_EMULATE_MUL_DIV
2996 backend->emulate_mul_div = 1;
2997 #endif
2998 #ifdef MONO_ARCH_EMULATE_DIV
2999 backend->emulate_div = 1;
3000 #endif
3001 #if !defined(MONO_ARCH_NO_EMULATE_LONG_SHIFT_OPS)
3002 backend->emulate_long_shift_opts = 1;
3003 #endif
3004 #ifdef MONO_ARCH_HAVE_OBJC_GET_SELECTOR
3005 backend->have_objc_get_selector = 1;
3006 #endif
3007 #ifdef MONO_ARCH_HAVE_GENERALIZED_IMT_TRAMPOLINE
3008 backend->have_generalized_imt_trampoline = 1;
3009 #endif
3010 #ifdef MONO_ARCH_GSHARED_SUPPORTED
3011 backend->gshared_supported = 1;
3012 #endif
3013 if (MONO_ARCH_USE_FPSTACK)
3014 backend->use_fpstack = 1;
3015 // Does the ABI have a volatile non-parameter register, so tailcall
3016 // can pass context to generics or interfaces?
3017 backend->have_volatile_non_param_register = MONO_ARCH_HAVE_VOLATILE_NON_PARAM_REGISTER;
3018 #ifdef MONO_ARCH_HAVE_OP_TAILCALL_MEMBASE
3019 backend->have_op_tailcall_membase = 1;
3020 #endif
3021 #ifdef MONO_ARCH_HAVE_OP_TAILCALL_REG
3022 backend->have_op_tailcall_reg = 1;
3023 #endif
3024 #ifndef MONO_ARCH_MONITOR_ENTER_ADJUSTMENT
3025 backend->monitor_enter_adjustment = 1;
3026 #else
3027 backend->monitor_enter_adjustment = MONO_ARCH_MONITOR_ENTER_ADJUSTMENT;
3028 #endif
3029 #if defined(MONO_ARCH_ILP32)
3030 backend->ilp32 = 1;
3031 #endif
3032 #ifdef MONO_ARCH_NEED_DIV_CHECK
3033 backend->need_div_check = 1;
3034 #endif
3035 #ifdef NO_UNALIGNED_ACCESS
3036 backend->no_unaligned_access = 1;
3037 #endif
3038 #ifdef MONO_ARCH_DYN_CALL_PARAM_AREA
3039 backend->dyn_call_param_area = MONO_ARCH_DYN_CALL_PARAM_AREA;
3040 #endif
3041 #ifdef MONO_ARCH_NO_DIV_WITH_MUL
3042 backend->disable_div_with_mul = 1;
3043 #endif
3044 #ifdef MONO_ARCH_EXPLICIT_NULL_CHECKS
3045 backend->explicit_null_checks = 1;
3046 #endif
3047 #ifdef MONO_ARCH_HAVE_OPTIMIZED_DIV
3048 backend->optimized_div = 1;
3049 #endif
3052 static gboolean
3053 is_simd_supported (MonoCompile *cfg)
3055 // FIXME: Clean this up
3056 #ifdef TARGET_WASM
3057 if ((mini_get_cpu_features (cfg) & MONO_CPU_WASM_SIMD) == 0)
3058 return FALSE;
3059 #else
3060 if (cfg->llvm_only)
3061 return FALSE;
3062 #endif
3063 return TRUE;
3067 * mini_method_compile:
3068 * @method: the method to compile
3069 * @opts: the optimization flags to use
3070 * @domain: the domain where the method will be compiled in
3071 * @flags: compilation flags
3072 * @parts: debug flag
3074 * Returns: a MonoCompile* pointer. Caller must check the exception_type
3075 * field in the returned struct to see if compilation succeded.
3077 MonoCompile*
3078 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFlags flags, int parts, int aot_method_index)
3080 MonoMethodHeader *header;
3081 MonoMethodSignature *sig;
3082 MonoCompile *cfg;
3083 int i;
3084 gboolean try_generic_shared, try_llvm = FALSE;
3085 MonoMethod *method_to_compile, *method_to_register;
3086 gboolean method_is_gshared = FALSE;
3087 gboolean run_cctors = (flags & JIT_FLAG_RUN_CCTORS) ? 1 : 0;
3088 gboolean compile_aot = (flags & JIT_FLAG_AOT) ? 1 : 0;
3089 gboolean full_aot = (flags & JIT_FLAG_FULL_AOT) ? 1 : 0;
3090 gboolean disable_direct_icalls = (flags & JIT_FLAG_NO_DIRECT_ICALLS) ? 1 : 0;
3091 gboolean gsharedvt_method = FALSE;
3092 #ifdef ENABLE_LLVM
3093 gboolean llvm = (flags & JIT_FLAG_LLVM) ? 1 : 0;
3094 #endif
3095 static gboolean verbose_method_inited;
3096 static char **verbose_method_names;
3098 mono_atomic_inc_i32 (&mono_jit_stats.methods_compiled);
3099 MONO_PROFILER_RAISE (jit_begin, (method));
3100 if (MONO_METHOD_COMPILE_BEGIN_ENABLED ())
3101 MONO_PROBE_METHOD_COMPILE_BEGIN (method);
3103 gsharedvt_method = is_gsharedvt_method (method);
3106 * In AOT mode, method can be the following:
3107 * - a gsharedvt method.
3108 * - a method inflated with type parameters. This is for ref/partial sharing.
3109 * - a method inflated with concrete types.
3111 if (compile_aot) {
3112 if (is_open_method (method)) {
3113 try_generic_shared = TRUE;
3114 method_is_gshared = TRUE;
3115 } else {
3116 try_generic_shared = FALSE;
3118 g_assert (opts & MONO_OPT_GSHARED);
3119 } else {
3120 try_generic_shared = mono_class_generic_sharing_enabled (method->klass) &&
3121 (opts & MONO_OPT_GSHARED) && mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE);
3122 if (mini_is_gsharedvt_sharable_method (method)) {
3124 if (!mono_debug_count ())
3125 try_generic_shared = FALSE;
3131 if (try_generic_shared && !mono_debug_count ())
3132 try_generic_shared = FALSE;
3135 if (opts & MONO_OPT_GSHARED) {
3136 if (try_generic_shared)
3137 mono_atomic_inc_i32 (&mono_stats.generics_sharable_methods);
3138 else if (mono_method_is_generic_impl (method))
3139 mono_atomic_inc_i32 (&mono_stats.generics_unsharable_methods);
3142 #ifdef ENABLE_LLVM
3143 try_llvm = mono_use_llvm || llvm;
3144 #endif
3146 #ifndef MONO_ARCH_FLOAT32_SUPPORTED
3147 opts &= ~MONO_OPT_FLOAT32;
3148 #endif
3150 restart_compile:
3151 if (method_is_gshared) {
3152 method_to_compile = method;
3153 } else {
3154 if (try_generic_shared) {
3155 ERROR_DECL (error);
3156 method_to_compile = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
3157 mono_error_assert_ok (error);
3158 } else {
3159 method_to_compile = method;
3163 cfg = g_new0 (MonoCompile, 1);
3164 cfg->method = method_to_compile;
3165 cfg->mempool = mono_mempool_new ();
3166 cfg->opt = opts;
3167 cfg->run_cctors = run_cctors;
3168 cfg->domain = domain;
3169 cfg->verbose_level = mini_verbose;
3170 cfg->compile_aot = compile_aot;
3171 cfg->full_aot = full_aot;
3172 cfg->disable_omit_fp = mini_debug_options.disable_omit_fp;
3173 cfg->skip_visibility = method->skip_visibility;
3174 cfg->orig_method = method;
3175 cfg->gen_seq_points = !mini_debug_options.no_seq_points_compact_data || mini_debug_options.gen_sdb_seq_points;
3176 cfg->gen_sdb_seq_points = mini_debug_options.gen_sdb_seq_points;
3177 cfg->llvm_only = (flags & JIT_FLAG_LLVM_ONLY) != 0;
3178 cfg->interp = (flags & JIT_FLAG_INTERP) != 0;
3179 cfg->use_current_cpu = (flags & JIT_FLAG_USE_CURRENT_CPU) != 0;
3180 cfg->backend = current_backend;
3182 if (cfg->method->wrapper_type == MONO_WRAPPER_ALLOC) {
3183 /* We can't have seq points inside gc critical regions */
3184 cfg->gen_seq_points = FALSE;
3185 cfg->gen_sdb_seq_points = FALSE;
3187 /* coop requires loop detection to happen */
3188 if (mini_safepoints_enabled ())
3189 cfg->opt |= MONO_OPT_LOOP;
3190 cfg->disable_llvm_implicit_null_checks = mini_debug_options.llvm_disable_implicit_null_checks;
3191 if (cfg->backend->explicit_null_checks || mini_debug_options.explicit_null_checks) {
3192 /* some platforms have null pages, so we can't SIGSEGV */
3193 cfg->explicit_null_checks = TRUE;
3194 cfg->disable_llvm_implicit_null_checks = TRUE;
3195 } else {
3196 cfg->explicit_null_checks = flags & JIT_FLAG_EXPLICIT_NULL_CHECKS;
3198 cfg->soft_breakpoints = mini_debug_options.soft_breakpoints;
3199 cfg->check_pinvoke_callconv = mini_debug_options.check_pinvoke_callconv;
3200 cfg->disable_direct_icalls = disable_direct_icalls;
3201 cfg->direct_pinvoke = (flags & JIT_FLAG_DIRECT_PINVOKE) != 0;
3202 if (try_generic_shared)
3203 cfg->gshared = TRUE;
3204 cfg->compile_llvm = try_llvm;
3205 cfg->token_info_hash = g_hash_table_new (NULL, NULL);
3206 if (cfg->compile_aot)
3207 cfg->method_index = aot_method_index;
3209 if (cfg->compile_llvm)
3210 cfg->explicit_null_checks = TRUE;
3213 if (!mono_debug_count ())
3214 cfg->opt &= ~MONO_OPT_FLOAT32;
3216 if (!is_simd_supported (cfg))
3217 cfg->opt &= ~MONO_OPT_SIMD;
3218 cfg->r4fp = (cfg->opt & MONO_OPT_FLOAT32) ? 1 : 0;
3219 cfg->r4_stack_type = cfg->r4fp ? STACK_R4 : STACK_R8;
3221 if (cfg->gen_seq_points)
3222 cfg->seq_points = g_ptr_array_new ();
3223 cfg->error = (MonoError*)&cfg->error_value;
3224 error_init (cfg->error);
3226 if (cfg->compile_aot && !try_generic_shared && (method->is_generic || mono_class_is_gtd (method->klass) || method_is_gshared)) {
3227 cfg->exception_type = MONO_EXCEPTION_GENERIC_SHARING_FAILED;
3228 return cfg;
3231 if (cfg->gshared && (gsharedvt_method || mini_is_gsharedvt_sharable_method (method))) {
3232 MonoMethodInflated *inflated;
3233 MonoGenericContext *context;
3235 if (gsharedvt_method) {
3236 g_assert (method->is_inflated);
3237 inflated = (MonoMethodInflated*)method;
3238 context = &inflated->context;
3240 /* We are compiling a gsharedvt method directly */
3241 g_assert (compile_aot);
3242 } else {
3243 g_assert (method_to_compile->is_inflated);
3244 inflated = (MonoMethodInflated*)method_to_compile;
3245 context = &inflated->context;
3248 mini_init_gsctx (NULL, cfg->mempool, context, &cfg->gsctx);
3249 cfg->gsctx_context = context;
3251 cfg->gsharedvt = TRUE;
3252 if (!cfg->llvm_only) {
3253 cfg->disable_llvm = TRUE;
3254 cfg->exception_message = g_strdup ("gsharedvt");
3258 if (cfg->gshared) {
3259 method_to_register = method_to_compile;
3260 } else {
3261 g_assert (method == method_to_compile);
3262 method_to_register = method;
3264 cfg->method_to_register = method_to_register;
3266 ERROR_DECL (err);
3267 sig = mono_method_signature_checked (cfg->method, err);
3268 if (!sig) {
3269 cfg->exception_type = MONO_EXCEPTION_TYPE_LOAD;
3270 cfg->exception_message = g_strdup (mono_error_get_message (err));
3271 mono_error_cleanup (err);
3272 if (MONO_METHOD_COMPILE_END_ENABLED ())
3273 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3274 return cfg;
3277 header = cfg->header = mono_method_get_header_checked (cfg->method, cfg->error);
3278 if (!header) {
3279 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
3280 if (MONO_METHOD_COMPILE_END_ENABLED ())
3281 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3282 return cfg;
3285 #ifdef ENABLE_LLVM
3287 static gboolean inited;
3289 if (!inited)
3290 inited = TRUE;
3293 * Check for methods which cannot be compiled by LLVM early, to avoid
3294 * the extra compilation pass.
3296 if (COMPILE_LLVM (cfg)) {
3297 mono_llvm_check_method_supported (cfg);
3298 if (cfg->disable_llvm) {
3299 if (cfg->verbose_level >= (cfg->llvm_only ? 0 : 1)) {
3300 //nm = mono_method_full_name (cfg->method, TRUE);
3301 printf ("LLVM failed for '%s.%s': %s\n", m_class_get_name (method->klass), method->name, cfg->exception_message);
3302 //g_free (nm);
3304 if (cfg->llvm_only) {
3305 g_free (cfg->exception_message);
3306 cfg->disable_aot = TRUE;
3307 return cfg;
3309 mono_destroy_compile (cfg);
3310 try_llvm = FALSE;
3311 goto restart_compile;
3315 #endif
3317 cfg->prof_flags = mono_profiler_get_call_instrumentation_flags (cfg->method);
3318 cfg->prof_coverage = mono_profiler_coverage_instrumentation_enabled (cfg->method);
3320 gboolean trace = mono_jit_trace_calls != NULL && mono_trace_eval (cfg->method);
3321 if (trace)
3322 cfg->prof_flags = (MonoProfilerCallInstrumentationFlags)(
3323 MONO_PROFILER_CALL_INSTRUMENTATION_ENTER | MONO_PROFILER_CALL_INSTRUMENTATION_ENTER_CONTEXT |
3324 MONO_PROFILER_CALL_INSTRUMENTATION_LEAVE | MONO_PROFILER_CALL_INSTRUMENTATION_LEAVE_CONTEXT);
3326 /* The debugger has no liveness information, so avoid sharing registers/stack slots */
3327 if (mini_debug_options.mdb_optimizations || MONO_CFG_PROFILE_CALL_CONTEXT (cfg)) {
3328 cfg->disable_reuse_registers = TRUE;
3329 cfg->disable_reuse_stack_slots = TRUE;
3331 * This decreases the change the debugger will read registers/stack slots which are
3332 * not yet initialized.
3334 cfg->disable_initlocals_opt = TRUE;
3336 cfg->extend_live_ranges = TRUE;
3338 /* The debugger needs all locals to be on the stack or in a global register */
3339 cfg->disable_vreg_to_lvreg = TRUE;
3341 /* Don't remove unused variables when running inside the debugger since the user
3342 * may still want to view them. */
3343 cfg->disable_deadce_vars = TRUE;
3345 cfg->opt &= ~MONO_OPT_DEADCE;
3346 cfg->opt &= ~MONO_OPT_INLINE;
3347 cfg->opt &= ~MONO_OPT_COPYPROP;
3348 cfg->opt &= ~MONO_OPT_CONSPROP;
3350 /* This is needed for the soft debugger, which doesn't like code after the epilog */
3351 cfg->disable_out_of_line_bblocks = TRUE;
3354 if (mono_using_xdebug) {
3356 * Make each variable use its own register/stack slot and extend
3357 * their liveness to cover the whole method, making them displayable
3358 * in gdb even after they are dead.
3360 cfg->disable_reuse_registers = TRUE;
3361 cfg->disable_reuse_stack_slots = TRUE;
3362 cfg->extend_live_ranges = TRUE;
3363 cfg->compute_precise_live_ranges = TRUE;
3366 mini_gc_init_cfg (cfg);
3368 if (method->wrapper_type == MONO_WRAPPER_OTHER) {
3369 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
3371 if ((info && (info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_IN_SIG || info->subtype == WRAPPER_SUBTYPE_GSHAREDVT_OUT_SIG))) {
3372 cfg->disable_gc_safe_points = TRUE;
3373 /* This is safe, these wrappers only store to the stack */
3374 cfg->gen_write_barriers = FALSE;
3378 if (COMPILE_LLVM (cfg)) {
3379 cfg->opt |= MONO_OPT_ABCREM;
3382 if (!verbose_method_inited) {
3383 char *env = g_getenv ("MONO_VERBOSE_METHOD");
3384 if (env != NULL)
3385 verbose_method_names = g_strsplit (env, ";", -1);
3387 verbose_method_inited = TRUE;
3389 if (verbose_method_names) {
3390 int i;
3392 for (i = 0; verbose_method_names [i] != NULL; i++){
3393 const char *name = verbose_method_names [i];
3395 if ((strchr (name, '.') > name) || strchr (name, ':')) {
3396 MonoMethodDesc *desc;
3398 desc = mono_method_desc_new (name, TRUE);
3399 if (desc) {
3400 if (mono_method_desc_full_match (desc, cfg->method)) {
3401 cfg->verbose_level = 4;
3403 mono_method_desc_free (desc);
3405 } else {
3406 if (strcmp (cfg->method->name, name) == 0)
3407 cfg->verbose_level = 4;
3412 cfg->intvars = (guint16 *)mono_mempool_alloc0 (cfg->mempool, sizeof (guint16) * STACK_MAX * header->max_stack);
3414 if (cfg->verbose_level > 0) {
3415 char *method_name;
3417 method_name = mono_method_get_full_name (method);
3418 g_print ("converting %s%s%smethod %s\n", COMPILE_LLVM (cfg) ? "llvm " : "", cfg->gsharedvt ? "gsharedvt " : "", (cfg->gshared && !cfg->gsharedvt) ? "gshared " : "", method_name);
3420 if (COMPILE_LLVM (cfg))
3421 g_print ("converting llvm method %s\n", method_name = mono_method_full_name (method, TRUE));
3422 else if (cfg->gsharedvt)
3423 g_print ("converting gsharedvt method %s\n", method_name = mono_method_full_name (method_to_compile, TRUE));
3424 else if (cfg->gshared)
3425 g_print ("converting shared method %s\n", method_name = mono_method_full_name (method_to_compile, TRUE));
3426 else
3427 g_print ("converting method %s\n", method_name = mono_method_full_name (method, TRUE));
3429 g_free (method_name);
3432 if (cfg->opt & MONO_OPT_ABCREM)
3433 cfg->opt |= MONO_OPT_SSA;
3435 cfg->rs = mono_regstate_new ();
3436 cfg->next_vreg = cfg->rs->next_vreg;
3438 /* FIXME: Fix SSA to handle branches inside bblocks */
3439 if (cfg->opt & MONO_OPT_SSA)
3440 cfg->enable_extended_bblocks = FALSE;
3443 * FIXME: This confuses liveness analysis because variables which are assigned after
3444 * a branch inside a bblock become part of the kill set, even though the assignment
3445 * might not get executed. This causes the optimize_initlocals pass to delete some
3446 * assignments which are needed.
3447 * Also, the mono_if_conversion pass needs to be modified to recognize the code
3448 * created by this.
3450 //cfg->enable_extended_bblocks = TRUE;
3452 /*We must verify the method before doing any IR generation as mono_compile_create_vars can assert.*/
3453 if (mono_compile_is_broken (cfg, cfg->method, TRUE)) {
3454 if (mini_debug_options.break_on_unverified)
3455 G_BREAKPOINT ();
3456 return cfg;
3460 * create MonoInst* which represents arguments and local variables
3462 mono_compile_create_vars (cfg);
3464 mono_cfg_dump_create_context (cfg);
3465 mono_cfg_dump_begin_group (cfg);
3467 MONO_TIME_TRACK (mono_jit_stats.jit_method_to_ir, i = mono_method_to_ir (cfg, method_to_compile, NULL, NULL, NULL, NULL, 0, FALSE));
3468 mono_cfg_dump_ir (cfg, "method-to-ir");
3470 if (cfg->gdump_ctx != NULL) {
3471 /* workaround for graph visualization, as it doesn't handle empty basic blocks properly */
3472 mono_insert_nop_in_empty_bb (cfg);
3473 mono_cfg_dump_ir (cfg, "mono_insert_nop_in_empty_bb");
3476 if (i < 0) {
3477 if (try_generic_shared && cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3478 if (compile_aot) {
3479 if (MONO_METHOD_COMPILE_END_ENABLED ())
3480 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3481 return cfg;
3483 mono_destroy_compile (cfg);
3484 try_generic_shared = FALSE;
3485 goto restart_compile;
3487 g_assert (cfg->exception_type != MONO_EXCEPTION_GENERIC_SHARING_FAILED);
3489 if (MONO_METHOD_COMPILE_END_ENABLED ())
3490 MONO_PROBE_METHOD_COMPILE_END (method, FALSE);
3491 /* cfg contains the details of the failure, so let the caller cleanup */
3492 return cfg;
3495 cfg->stat_basic_blocks += cfg->num_bblocks;
3497 if (COMPILE_LLVM (cfg)) {
3498 MonoInst *ins;
3500 /* The IR has to be in SSA form for LLVM */
3501 cfg->opt |= MONO_OPT_SSA;
3503 // FIXME:
3504 if (cfg->ret) {
3505 // Allow SSA on the result value
3506 cfg->ret->flags &= ~MONO_INST_VOLATILE;
3508 // Add an explicit return instruction referencing the return value
3509 MONO_INST_NEW (cfg, ins, OP_SETRET);
3510 ins->sreg1 = cfg->ret->dreg;
3512 MONO_ADD_INS (cfg->bb_exit, ins);
3515 cfg->opt &= ~MONO_OPT_LINEARS;
3517 /* FIXME: */
3518 cfg->opt &= ~MONO_OPT_BRANCH;
3521 /* todo: remove code when we have verified that the liveness for try/catch blocks
3522 * works perfectly
3525 * Currently, this can't be commented out since exception blocks are not
3526 * processed during liveness analysis.
3527 * It is also needed, because otherwise the local optimization passes would
3528 * delete assignments in cases like this:
3529 * r1 <- 1
3530 * <something which throws>
3531 * r1 <- 2
3532 * This also allows SSA to be run on methods containing exception clauses, since
3533 * SSA will ignore variables marked VOLATILE.
3535 MONO_TIME_TRACK (mono_jit_stats.jit_liveness_handle_exception_clauses, mono_liveness_handle_exception_clauses (cfg));
3536 mono_cfg_dump_ir (cfg, "liveness_handle_exception_clauses");
3538 MONO_TIME_TRACK (mono_jit_stats.jit_handle_out_of_line_bblock, mono_handle_out_of_line_bblock (cfg));
3539 mono_cfg_dump_ir (cfg, "handle_out_of_line_bblock");
3541 /*g_print ("numblocks = %d\n", cfg->num_bblocks);*/
3543 if (!COMPILE_LLVM (cfg)) {
3544 MONO_TIME_TRACK (mono_jit_stats.jit_decompose_long_opts, mono_decompose_long_opts (cfg));
3545 mono_cfg_dump_ir (cfg, "decompose_long_opts");
3548 /* Should be done before branch opts */
3549 if (cfg->opt & (MONO_OPT_CONSPROP | MONO_OPT_COPYPROP)) {
3550 MONO_TIME_TRACK (mono_jit_stats.jit_local_cprop, mono_local_cprop (cfg));
3551 mono_cfg_dump_ir (cfg, "local_cprop");
3554 if (cfg->flags & MONO_CFG_HAS_TYPE_CHECK) {
3555 MONO_TIME_TRACK (mono_jit_stats.jit_decompose_typechecks, mono_decompose_typechecks (cfg));
3556 if (cfg->gdump_ctx != NULL) {
3557 /* workaround for graph visualization, as it doesn't handle empty basic blocks properly */
3558 mono_insert_nop_in_empty_bb (cfg);
3560 mono_cfg_dump_ir (cfg, "decompose_typechecks");
3564 * Should be done after cprop which can do strength reduction on
3565 * some of these ops, after propagating immediates.
3567 if (cfg->has_emulated_ops) {
3568 MONO_TIME_TRACK (mono_jit_stats.jit_local_emulate_ops, mono_local_emulate_ops (cfg));
3569 mono_cfg_dump_ir (cfg, "local_emulate_ops");
3572 if (cfg->opt & MONO_OPT_BRANCH) {
3573 MONO_TIME_TRACK (mono_jit_stats.jit_optimize_branches, mono_optimize_branches (cfg));
3574 mono_cfg_dump_ir (cfg, "optimize_branches");
3577 /* This must be done _before_ global reg alloc and _after_ decompose */
3578 MONO_TIME_TRACK (mono_jit_stats.jit_handle_global_vregs, mono_handle_global_vregs (cfg));
3579 mono_cfg_dump_ir (cfg, "handle_global_vregs");
3580 if (cfg->opt & MONO_OPT_DEADCE) {
3581 MONO_TIME_TRACK (mono_jit_stats.jit_local_deadce, mono_local_deadce (cfg));
3582 mono_cfg_dump_ir (cfg, "local_deadce");
3584 if (cfg->opt & MONO_OPT_ALIAS_ANALYSIS) {
3585 MONO_TIME_TRACK (mono_jit_stats.jit_local_alias_analysis, mono_local_alias_analysis (cfg));
3586 mono_cfg_dump_ir (cfg, "local_alias_analysis");
3588 /* Disable this for LLVM to make the IR easier to handle */
3589 if (!COMPILE_LLVM (cfg)) {
3590 MONO_TIME_TRACK (mono_jit_stats.jit_if_conversion, mono_if_conversion (cfg));
3591 mono_cfg_dump_ir (cfg, "if_conversion");
3594 mono_threads_safepoint ();
3596 MONO_TIME_TRACK (mono_jit_stats.jit_bb_ordering, mono_bb_ordering (cfg));
3597 mono_cfg_dump_ir (cfg, "bb_ordering");
3599 if (((cfg->num_varinfo > 2000) || (cfg->num_bblocks > 1000)) && !cfg->compile_aot) {
3601 * we disable some optimizations if there are too many variables
3602 * because JIT time may become too expensive. The actual number needs
3603 * to be tweaked and eventually the non-linear algorithms should be fixed.
3605 cfg->opt &= ~ (MONO_OPT_LINEARS | MONO_OPT_COPYPROP | MONO_OPT_CONSPROP);
3606 cfg->disable_ssa = TRUE;
3609 if (cfg->num_varinfo > 10000 && !cfg->llvm_only)
3610 /* Disable llvm for overly complex methods */
3611 cfg->disable_ssa = TRUE;
3613 if (cfg->opt & MONO_OPT_LOOP) {
3614 MONO_TIME_TRACK (mono_jit_stats.jit_compile_dominator_info, mono_compile_dominator_info (cfg, MONO_COMP_DOM | MONO_COMP_IDOM));
3615 MONO_TIME_TRACK (mono_jit_stats.jit_compute_natural_loops, mono_compute_natural_loops (cfg));
3618 if (mono_threads_are_safepoints_enabled ()) {
3619 MONO_TIME_TRACK (mono_jit_stats.jit_insert_safepoints, insert_safepoints (cfg));
3620 mono_cfg_dump_ir (cfg, "insert_safepoints");
3623 /* after method_to_ir */
3624 if (parts == 1) {
3625 if (MONO_METHOD_COMPILE_END_ENABLED ())
3626 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
3627 return cfg;
3631 if (header->num_clauses)
3632 cfg->disable_ssa = TRUE;
3635 //#define DEBUGSSA "logic_run"
3636 //#define DEBUGSSA_CLASS "Tests"
3637 #ifdef DEBUGSSA
3639 if (!cfg->disable_ssa) {
3640 mono_local_cprop (cfg);
3642 #ifndef DISABLE_SSA
3643 mono_ssa_compute (cfg);
3644 #endif
3646 #else
3647 if (cfg->opt & MONO_OPT_SSA) {
3648 if (!(cfg->comp_done & MONO_COMP_SSA) && !cfg->disable_ssa) {
3649 #ifndef DISABLE_SSA
3650 MONO_TIME_TRACK (mono_jit_stats.jit_ssa_compute, mono_ssa_compute (cfg));
3651 mono_cfg_dump_ir (cfg, "ssa_compute");
3652 #endif
3654 if (cfg->verbose_level >= 2) {
3655 print_dfn (cfg);
3659 #endif
3661 /* after SSA translation */
3662 if (parts == 2) {
3663 if (MONO_METHOD_COMPILE_END_ENABLED ())
3664 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
3665 return cfg;
3668 if ((cfg->opt & MONO_OPT_CONSPROP) || (cfg->opt & MONO_OPT_COPYPROP)) {
3669 if (cfg->comp_done & MONO_COMP_SSA && !COMPILE_LLVM (cfg)) {
3670 #ifndef DISABLE_SSA
3671 MONO_TIME_TRACK (mono_jit_stats.jit_ssa_cprop, mono_ssa_cprop (cfg));
3672 mono_cfg_dump_ir (cfg, "ssa_cprop");
3673 #endif
3677 #ifndef DISABLE_SSA
3678 if (cfg->comp_done & MONO_COMP_SSA && !COMPILE_LLVM (cfg)) {
3679 //mono_ssa_strength_reduction (cfg);
3681 if (cfg->opt & MONO_OPT_DEADCE) {
3682 MONO_TIME_TRACK (mono_jit_stats.jit_ssa_deadce, mono_ssa_deadce (cfg));
3683 mono_cfg_dump_ir (cfg, "ssa_deadce");
3686 if ((cfg->flags & (MONO_CFG_HAS_LDELEMA|MONO_CFG_HAS_CHECK_THIS)) && (cfg->opt & MONO_OPT_ABCREM)) {
3687 MONO_TIME_TRACK (mono_jit_stats.jit_perform_abc_removal, mono_perform_abc_removal (cfg));
3688 mono_cfg_dump_ir (cfg, "perform_abc_removal");
3691 MONO_TIME_TRACK (mono_jit_stats.jit_ssa_remove, mono_ssa_remove (cfg));
3692 mono_cfg_dump_ir (cfg, "ssa_remove");
3693 MONO_TIME_TRACK (mono_jit_stats.jit_local_cprop2, mono_local_cprop (cfg));
3694 mono_cfg_dump_ir (cfg, "local_cprop2");
3695 MONO_TIME_TRACK (mono_jit_stats.jit_handle_global_vregs2, mono_handle_global_vregs (cfg));
3696 mono_cfg_dump_ir (cfg, "handle_global_vregs2");
3697 if (cfg->opt & MONO_OPT_DEADCE) {
3698 MONO_TIME_TRACK (mono_jit_stats.jit_local_deadce2, mono_local_deadce (cfg));
3699 mono_cfg_dump_ir (cfg, "local_deadce2");
3702 if (cfg->opt & MONO_OPT_BRANCH) {
3703 MONO_TIME_TRACK (mono_jit_stats.jit_optimize_branches2, mono_optimize_branches (cfg));
3704 mono_cfg_dump_ir (cfg, "optimize_branches2");
3707 #endif
3709 if (cfg->comp_done & MONO_COMP_SSA && COMPILE_LLVM (cfg)) {
3710 mono_ssa_loop_invariant_code_motion (cfg);
3711 mono_cfg_dump_ir (cfg, "loop_invariant_code_motion");
3712 /* This removes MONO_INST_FAULT flags too so perform it unconditionally */
3713 if (cfg->opt & MONO_OPT_ABCREM) {
3714 mono_perform_abc_removal (cfg);
3715 mono_cfg_dump_ir (cfg, "abc_removal");
3719 /* after SSA removal */
3720 if (parts == 3) {
3721 if (MONO_METHOD_COMPILE_END_ENABLED ())
3722 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
3723 return cfg;
3726 if (cfg->llvm_only && cfg->gsharedvt)
3727 mono_ssa_remove_gsharedvt (cfg);
3729 #ifdef MONO_ARCH_SOFT_FLOAT_FALLBACK
3730 if (COMPILE_SOFT_FLOAT (cfg))
3731 mono_decompose_soft_float (cfg);
3732 #endif
3733 MONO_TIME_TRACK (mono_jit_stats.jit_decompose_vtype_opts, mono_decompose_vtype_opts (cfg));
3734 if (cfg->flags & MONO_CFG_NEEDS_DECOMPOSE) {
3735 MONO_TIME_TRACK (mono_jit_stats.jit_decompose_array_access_opts, mono_decompose_array_access_opts (cfg));
3736 mono_cfg_dump_ir (cfg, "decompose_array_access_opts");
3739 if (cfg->got_var) {
3740 #ifndef MONO_ARCH_GOT_REG
3741 GList *regs;
3742 #endif
3743 int got_reg;
3745 g_assert (cfg->got_var_allocated);
3748 * Allways allocate the GOT var to a register, because keeping it
3749 * in memory will increase the number of live temporaries in some
3750 * code created by inssel.brg, leading to the well known spills+
3751 * branches problem. Testcase: mcs crash in
3752 * System.MonoCustomAttrs:GetCustomAttributes.
3754 #ifdef MONO_ARCH_GOT_REG
3755 got_reg = MONO_ARCH_GOT_REG;
3756 #else
3757 regs = mono_arch_get_global_int_regs (cfg);
3758 g_assert (regs);
3759 got_reg = GPOINTER_TO_INT (regs->data);
3760 g_list_free (regs);
3761 #endif
3762 cfg->got_var->opcode = OP_REGVAR;
3763 cfg->got_var->dreg = got_reg;
3764 cfg->used_int_regs |= 1LL << cfg->got_var->dreg;
3768 * Have to call this again to process variables added since the first call.
3770 MONO_TIME_TRACK(mono_jit_stats.jit_liveness_handle_exception_clauses2, mono_liveness_handle_exception_clauses (cfg));
3772 if (cfg->opt & MONO_OPT_LINEARS) {
3773 GList *vars, *regs, *l;
3775 /* fixme: maybe we can avoid to compute livenesss here if already computed ? */
3776 cfg->comp_done &= ~MONO_COMP_LIVENESS;
3777 if (!(cfg->comp_done & MONO_COMP_LIVENESS))
3778 MONO_TIME_TRACK (mono_jit_stats.jit_analyze_liveness, mono_analyze_liveness (cfg));
3780 if ((vars = mono_arch_get_allocatable_int_vars (cfg))) {
3781 regs = mono_arch_get_global_int_regs (cfg);
3782 /* Remove the reg reserved for holding the GOT address */
3783 if (cfg->got_var) {
3784 for (l = regs; l; l = l->next) {
3785 if (GPOINTER_TO_UINT (l->data) == cfg->got_var->dreg) {
3786 regs = g_list_delete_link (regs, l);
3787 break;
3791 MONO_TIME_TRACK (mono_jit_stats.jit_linear_scan, mono_linear_scan (cfg, vars, regs, &cfg->used_int_regs));
3792 mono_cfg_dump_ir (cfg, "linear_scan");
3796 //mono_print_code (cfg, "");
3798 //print_dfn (cfg);
3800 /* variables are allocated after decompose, since decompose could create temps */
3801 if (!COMPILE_LLVM (cfg)) {
3802 MONO_TIME_TRACK (mono_jit_stats.jit_arch_allocate_vars, mono_arch_allocate_vars (cfg));
3803 mono_cfg_dump_ir (cfg, "arch_allocate_vars");
3804 if (cfg->exception_type)
3805 return cfg;
3808 if (cfg->gsharedvt)
3809 mono_allocate_gsharedvt_vars (cfg);
3811 if (!COMPILE_LLVM (cfg)) {
3812 gboolean need_local_opts;
3813 MONO_TIME_TRACK (mono_jit_stats.jit_spill_global_vars, mono_spill_global_vars (cfg, &need_local_opts));
3814 mono_cfg_dump_ir (cfg, "spill_global_vars");
3816 if (need_local_opts || cfg->compile_aot) {
3817 /* To optimize code created by spill_global_vars */
3818 MONO_TIME_TRACK (mono_jit_stats.jit_local_cprop3, mono_local_cprop (cfg));
3819 if (cfg->opt & MONO_OPT_DEADCE)
3820 MONO_TIME_TRACK (mono_jit_stats.jit_local_deadce3, mono_local_deadce (cfg));
3821 mono_cfg_dump_ir (cfg, "needs_local_opts");
3825 mono_insert_branches_between_bblocks (cfg);
3827 if (COMPILE_LLVM (cfg)) {
3828 #ifdef ENABLE_LLVM
3829 char *nm;
3831 /* The IR has to be in SSA form for LLVM */
3832 if (!(cfg->comp_done & MONO_COMP_SSA)) {
3833 cfg->exception_message = g_strdup ("SSA disabled.");
3834 cfg->disable_llvm = TRUE;
3837 if (cfg->flags & MONO_CFG_NEEDS_DECOMPOSE)
3838 mono_decompose_array_access_opts (cfg);
3840 if (!cfg->disable_llvm)
3841 mono_llvm_emit_method (cfg);
3842 if (cfg->disable_llvm) {
3843 if (cfg->verbose_level >= (cfg->llvm_only ? 0 : 1)) {
3844 //nm = mono_method_full_name (cfg->method, TRUE);
3845 printf ("LLVM failed for '%s.%s': %s\n", m_class_get_name (method->klass), method->name, cfg->exception_message);
3846 //g_free (nm);
3848 if (cfg->llvm_only) {
3849 cfg->disable_aot = TRUE;
3850 return cfg;
3852 mono_destroy_compile (cfg);
3853 try_llvm = FALSE;
3854 goto restart_compile;
3857 if (cfg->verbose_level > 0 && !cfg->compile_aot) {
3858 nm = mono_method_get_full_name (cfg->method);
3859 g_print ("LLVM Method %s emitted at %p to %p (code length %d) [%s]\n",
3860 nm,
3861 cfg->native_code, cfg->native_code + cfg->code_len, cfg->code_len, cfg->domain->friendly_name);
3862 g_free (nm);
3864 #endif
3865 } else {
3866 MONO_TIME_TRACK (mono_jit_stats.jit_codegen, mono_codegen (cfg));
3867 mono_cfg_dump_ir (cfg, "codegen");
3868 if (cfg->exception_type)
3869 return cfg;
3872 if (COMPILE_LLVM (cfg))
3873 mono_atomic_inc_i32 (&mono_jit_stats.methods_with_llvm);
3874 else
3875 mono_atomic_inc_i32 (&mono_jit_stats.methods_without_llvm);
3877 MONO_TIME_TRACK (mono_jit_stats.jit_create_jit_info, cfg->jit_info = create_jit_info (cfg, method_to_compile));
3879 if (cfg->extend_live_ranges) {
3880 /* Extend live ranges to cover the whole method */
3881 for (i = 0; i < cfg->num_varinfo; ++i)
3882 MONO_VARINFO (cfg, i)->live_range_end = cfg->code_len;
3885 MONO_TIME_TRACK (mono_jit_stats.jit_gc_create_gc_map, mini_gc_create_gc_map (cfg));
3886 MONO_TIME_TRACK (mono_jit_stats.jit_save_seq_point_info, mono_save_seq_point_info (cfg, cfg->jit_info));
3888 if (!cfg->compile_aot) {
3889 mono_save_xdebug_info (cfg);
3890 mono_lldb_save_method_info (cfg);
3893 if (cfg->verbose_level >= 2) {
3894 char *id = mono_method_full_name (cfg->method, TRUE);
3895 g_print ("\n*** ASM for %s ***\n", id);
3896 mono_disassemble_code (cfg, cfg->native_code, cfg->code_len, id + 3);
3897 g_print ("***\n\n");
3898 g_free (id);
3901 if (!cfg->compile_aot && !(flags & JIT_FLAG_DISCARD_RESULTS)) {
3902 mono_domain_lock (cfg->domain);
3903 mono_jit_info_table_add (cfg->domain, cfg->jit_info);
3905 if (cfg->method->dynamic)
3906 mono_dynamic_code_hash_lookup (cfg->domain, cfg->method)->ji = cfg->jit_info;
3908 mono_postprocess_patches_after_ji_publish (cfg);
3910 mono_domain_unlock (cfg->domain);
3913 #if 0
3914 if (cfg->gsharedvt)
3915 printf ("GSHAREDVT: %s\n", mono_method_full_name (cfg->method, TRUE));
3916 #endif
3918 /* collect statistics */
3919 #ifndef DISABLE_PERFCOUNTERS
3920 mono_atomic_inc_i32 (&mono_perfcounters->jit_methods);
3921 mono_atomic_fetch_add_i32 (&mono_perfcounters->jit_bytes, header->code_size);
3922 #endif
3923 gint32 code_size_ratio = cfg->code_len;
3924 mono_atomic_fetch_add_i32 (&mono_jit_stats.allocated_code_size, code_size_ratio);
3925 mono_atomic_fetch_add_i32 (&mono_jit_stats.native_code_size, code_size_ratio);
3926 /* FIXME: use an explicit function to read booleans */
3927 if ((gboolean)mono_atomic_load_i32 ((gint32*)&mono_jit_stats.enabled)) {
3928 if (code_size_ratio > mono_atomic_load_i32 (&mono_jit_stats.biggest_method_size)) {
3929 mono_atomic_store_i32 (&mono_jit_stats.biggest_method_size, code_size_ratio);
3930 char *biggest_method = g_strdup_printf ("%s::%s)", m_class_get_name (method->klass), method->name);
3931 biggest_method = (char*)mono_atomic_xchg_ptr ((gpointer*)&mono_jit_stats.biggest_method, biggest_method);
3932 g_free (biggest_method);
3934 code_size_ratio = (code_size_ratio * 100) / header->code_size;
3935 if (code_size_ratio > mono_atomic_load_i32 (&mono_jit_stats.max_code_size_ratio)) {
3936 mono_atomic_store_i32 (&mono_jit_stats.max_code_size_ratio, code_size_ratio);
3937 char *max_ratio_method = g_strdup_printf ("%s::%s)", m_class_get_name (method->klass), method->name);
3938 max_ratio_method = (char*)mono_atomic_xchg_ptr ((gpointer*)&mono_jit_stats.max_ratio_method, max_ratio_method);
3939 g_free (max_ratio_method);
3943 if (MONO_METHOD_COMPILE_END_ENABLED ())
3944 MONO_PROBE_METHOD_COMPILE_END (method, TRUE);
3946 mono_cfg_dump_close_group (cfg);
3948 return cfg;
3951 gboolean
3952 mini_class_has_reference_variant_generic_argument (MonoCompile *cfg, MonoClass *klass, int context_used)
3954 int i;
3955 MonoGenericContainer *container;
3956 MonoGenericInst *ginst;
3958 if (mono_class_is_ginst (klass)) {
3959 container = mono_class_get_generic_container (mono_class_get_generic_class (klass)->container_class);
3960 ginst = mono_class_get_generic_class (klass)->context.class_inst;
3961 } else if (mono_class_is_gtd (klass) && context_used) {
3962 container = mono_class_get_generic_container (klass);
3963 ginst = container->context.class_inst;
3964 } else {
3965 return FALSE;
3968 for (i = 0; i < container->type_argc; ++i) {
3969 MonoType *type;
3970 if (!(mono_generic_container_get_param_info (container, i)->flags & (MONO_GEN_PARAM_VARIANT|MONO_GEN_PARAM_COVARIANT)))
3971 continue;
3972 type = ginst->type_argv [i];
3973 if (mini_type_is_reference (type))
3974 return TRUE;
3976 return FALSE;
3979 void
3980 mono_cfg_add_try_hole (MonoCompile *cfg, MonoExceptionClause *clause, guint8 *start, MonoBasicBlock *bb)
3982 TryBlockHole *hole = (TryBlockHole *)mono_mempool_alloc (cfg->mempool, sizeof (TryBlockHole));
3983 hole->clause = clause;
3984 hole->start_offset = start - cfg->native_code;
3985 hole->basic_block = bb;
3987 cfg->try_block_holes = g_slist_append_mempool (cfg->mempool, cfg->try_block_holes, hole);
3990 void
3991 mono_cfg_set_exception (MonoCompile *cfg, MonoExceptionType type)
3993 cfg->exception_type = type;
3996 /* Assumes ownership of the MSG argument */
3997 void
3998 mono_cfg_set_exception_invalid_program (MonoCompile *cfg, char *msg)
4000 mono_cfg_set_exception (cfg, MONO_EXCEPTION_MONO_ERROR);
4001 mono_error_set_generic_error (cfg->error, "System", "InvalidProgramException", "%s", msg);
4004 #endif /* DISABLE_JIT */
4006 gint64 mono_time_track_start ()
4008 return mono_100ns_ticks ();
4012 * mono_time_track_end:
4014 * Uses UnlockedAddDouble () to update \param time.
4016 void mono_time_track_end (gint64 *time, gint64 start)
4018 UnlockedAdd64 (time, mono_100ns_ticks () - start);
4022 * mono_update_jit_stats:
4024 * Only call this function in locked environments to avoid data races.
4026 MONO_NO_SANITIZE_THREAD
4027 void
4028 mono_update_jit_stats (MonoCompile *cfg)
4030 mono_jit_stats.allocate_var += cfg->stat_allocate_var;
4031 mono_jit_stats.locals_stack_size += cfg->stat_locals_stack_size;
4032 mono_jit_stats.basic_blocks += cfg->stat_basic_blocks;
4033 mono_jit_stats.max_basic_blocks = MAX (cfg->stat_basic_blocks, mono_jit_stats.max_basic_blocks);
4034 mono_jit_stats.cil_code_size += cfg->stat_cil_code_size;
4035 mono_jit_stats.regvars += cfg->stat_n_regvars;
4036 mono_jit_stats.inlineable_methods += cfg->stat_inlineable_methods;
4037 mono_jit_stats.inlined_methods += cfg->stat_inlined_methods;
4038 mono_jit_stats.code_reallocs += cfg->stat_code_reallocs;
4042 * mono_jit_compile_method_inner:
4044 * Main entry point for the JIT.
4046 gpointer
4047 mono_jit_compile_method_inner (MonoMethod *method, MonoDomain *target_domain, int opt, MonoError *error)
4049 MonoCompile *cfg;
4050 gpointer code = NULL;
4051 MonoJitInfo *jinfo, *info;
4052 MonoVTable *vtable;
4053 MonoException *ex = NULL;
4054 gint64 start;
4055 MonoMethod *prof_method, *shared;
4057 error_init (error);
4059 start = mono_time_track_start ();
4060 cfg = mini_method_compile (method, opt, target_domain, JIT_FLAG_RUN_CCTORS, 0, -1);
4061 gint64 jit_time = 0.0;
4062 mono_time_track_end (&jit_time, start);
4063 UnlockedAdd64 (&mono_jit_stats.jit_time, jit_time);
4065 prof_method = cfg->method;
4067 switch (cfg->exception_type) {
4068 case MONO_EXCEPTION_NONE:
4069 break;
4070 case MONO_EXCEPTION_TYPE_LOAD:
4071 case MONO_EXCEPTION_MISSING_FIELD:
4072 case MONO_EXCEPTION_MISSING_METHOD:
4073 case MONO_EXCEPTION_FILE_NOT_FOUND:
4074 case MONO_EXCEPTION_BAD_IMAGE:
4075 case MONO_EXCEPTION_INVALID_PROGRAM: {
4076 /* Throw a type load exception if needed */
4077 if (cfg->exception_ptr) {
4078 ex = mono_class_get_exception_for_failure ((MonoClass *)cfg->exception_ptr);
4079 } else {
4080 if (cfg->exception_type == MONO_EXCEPTION_MISSING_FIELD)
4081 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingFieldException", cfg->exception_message);
4082 else if (cfg->exception_type == MONO_EXCEPTION_MISSING_METHOD)
4083 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "MissingMethodException", cfg->exception_message);
4084 else if (cfg->exception_type == MONO_EXCEPTION_TYPE_LOAD)
4085 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "TypeLoadException", cfg->exception_message);
4086 else if (cfg->exception_type == MONO_EXCEPTION_FILE_NOT_FOUND)
4087 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System.IO", "FileNotFoundException", cfg->exception_message);
4088 else if (cfg->exception_type == MONO_EXCEPTION_BAD_IMAGE)
4089 ex = mono_get_exception_bad_image_format (cfg->exception_message);
4090 else if (cfg->exception_type == MONO_EXCEPTION_INVALID_PROGRAM)
4091 ex = mono_exception_from_name_msg (mono_defaults.corlib, "System", "InvalidProgramException", cfg->exception_message);
4092 else
4093 g_assert_not_reached ();
4095 break;
4097 case MONO_EXCEPTION_MONO_ERROR:
4098 // FIXME: MonoError has no copy ctor
4099 g_assert (!is_ok (cfg->error));
4100 ex = mono_error_convert_to_exception (cfg->error);
4101 break;
4102 default:
4103 g_assert_not_reached ();
4106 if (ex) {
4107 MONO_PROFILER_RAISE (jit_failed, (method));
4109 mono_destroy_compile (cfg);
4110 mono_error_set_exception_instance (error, ex);
4112 return NULL;
4115 if (mono_method_is_generic_sharable (method, FALSE)) {
4116 shared = mini_get_shared_method_full (method, SHARE_MODE_NONE, error);
4117 if (!is_ok (error)) {
4118 MONO_PROFILER_RAISE (jit_failed, (method));
4119 mono_destroy_compile (cfg);
4120 return NULL;
4122 } else {
4123 shared = NULL;
4126 mono_domain_lock (target_domain);
4128 /* Check if some other thread already did the job. In this case, we can
4129 discard the code this thread generated. */
4131 info = mini_lookup_method (target_domain, method, shared);
4132 if (info) {
4133 /* We can't use a domain specific method in another domain */
4134 if ((target_domain == mono_domain_get ()) || info->domain_neutral) {
4135 code = info->code_start;
4136 discarded_code ++;
4137 discarded_jit_time += jit_time;
4140 if (code == NULL) {
4141 /* The lookup + insert is atomic since this is done inside the domain lock */
4142 mono_domain_jit_code_hash_lock (target_domain);
4143 mono_internal_hash_table_insert (&target_domain->jit_code_hash, cfg->jit_info->d.method, cfg->jit_info);
4144 mono_domain_jit_code_hash_unlock (target_domain);
4146 code = cfg->native_code;
4148 if (cfg->gshared && mono_method_is_generic_sharable (method, FALSE))
4149 mono_atomic_inc_i32 (&mono_stats.generics_shared_methods);
4150 if (cfg->gsharedvt)
4151 mono_atomic_inc_i32 (&mono_stats.gsharedvt_methods);
4154 jinfo = cfg->jit_info;
4157 * Update global stats while holding a lock, instead of doing many
4158 * mono_atomic_inc_i32 operations during JITting.
4160 mono_update_jit_stats (cfg);
4162 mono_destroy_compile (cfg);
4164 mini_patch_llvm_jit_callees (target_domain, method, code);
4165 #ifndef DISABLE_JIT
4166 mono_emit_jit_map (jinfo);
4167 #endif
4168 mono_domain_unlock (target_domain);
4170 if (!is_ok (error))
4171 return NULL;
4173 vtable = mono_class_vtable_checked (target_domain, method->klass, error);
4174 return_val_if_nok (error, NULL);
4176 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
4177 if (mono_marshal_method_from_wrapper (method)) {
4178 /* Native func wrappers have no method */
4179 /* The profiler doesn't know about wrappers, so pass the original icall method */
4180 MONO_PROFILER_RAISE (jit_done, (mono_marshal_method_from_wrapper (method), jinfo));
4183 MONO_PROFILER_RAISE (jit_done, (method, jinfo));
4184 if (prof_method != method)
4185 MONO_PROFILER_RAISE (jit_done, (prof_method, jinfo));
4187 if (!(method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE ||
4188 method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK ||
4189 method->wrapper_type == MONO_WRAPPER_XDOMAIN_INVOKE)) {
4190 if (!mono_runtime_class_init_full (vtable, error))
4191 return NULL;
4193 return code;
4197 * mini_get_underlying_type:
4199 * Return the type the JIT will use during compilation.
4200 * Handles: byref, enums, native types, bool/char, ref types, generic sharing.
4201 * For gsharedvt types, it will return the original VAR/MVAR.
4203 MonoType*
4204 mini_get_underlying_type (MonoType *type)
4206 return mini_type_get_underlying_type (type);
4209 void
4210 mini_jit_init (void)
4212 mono_counters_register ("Discarded method code", MONO_COUNTER_JIT | MONO_COUNTER_INT, &discarded_code);
4213 mono_counters_register ("Time spent JITting discarded code", MONO_COUNTER_JIT | MONO_COUNTER_LONG | MONO_COUNTER_TIME, &discarded_jit_time);
4214 mono_counters_register ("Try holes memory size", MONO_COUNTER_JIT | MONO_COUNTER_INT, &jinfo_try_holes_size);
4216 mono_os_mutex_init_recursive (&jit_mutex);
4217 #ifndef DISABLE_JIT
4218 current_backend = g_new0 (MonoBackend, 1);
4219 init_backend (current_backend);
4220 #endif
4223 void
4224 mini_jit_cleanup (void)
4226 #ifndef DISABLE_JIT
4227 g_free (emul_opcode_map);
4228 g_free (emul_opcode_opcodes);
4229 #endif
4232 #ifndef ENABLE_LLVM
4233 void
4234 mono_llvm_emit_aot_file_info (MonoAotFileInfo *info, gboolean has_jitted_code)
4236 g_assert_not_reached ();
4239 void mono_llvm_emit_aot_data (const char *symbol, guint8 *data, int data_len)
4241 g_assert_not_reached ();
4244 #endif
4246 #if !defined(ENABLE_LLVM_RUNTIME) && !defined(ENABLE_LLVM)
4248 void
4249 mono_llvm_cpp_throw_exception (void)
4251 g_assert_not_reached ();
4254 void
4255 mono_llvm_cpp_catch_exception (MonoLLVMInvokeCallback cb, gpointer arg, gboolean *out_thrown)
4257 g_assert_not_reached ();
4260 #endif
4262 #ifdef DISABLE_JIT
4264 MonoCompile*
4265 mini_method_compile (MonoMethod *method, guint32 opts, MonoDomain *domain, JitFlags flags, int parts, int aot_method_index)
4267 g_assert_not_reached ();
4268 return NULL;
4271 void
4272 mono_destroy_compile (MonoCompile *cfg)
4274 g_assert_not_reached ();
4277 void
4278 mono_add_patch_info (MonoCompile *cfg, int ip, MonoJumpInfoType type, gconstpointer target)
4280 g_assert_not_reached ();
4283 #else // DISABLE_JIT
4285 guint8*
4286 mini_realloc_code_slow (MonoCompile *cfg, int size)
4288 const int EXTRA_CODE_SPACE = 16;
4290 if (cfg->code_len + size > (cfg->code_size - EXTRA_CODE_SPACE)) {
4291 while (cfg->code_len + size > (cfg->code_size - EXTRA_CODE_SPACE))
4292 cfg->code_size = cfg->code_size * 2 + EXTRA_CODE_SPACE;
4293 cfg->native_code = g_realloc (cfg->native_code, cfg->code_size);
4294 cfg->stat_code_reallocs++;
4296 return cfg->native_code + cfg->code_len;
4299 #endif /* DISABLE_JIT */
4301 gboolean
4302 mini_class_is_system_array (MonoClass *klass)
4304 return m_class_get_parent (klass) == mono_defaults.array_class;
4308 * mono_target_pagesize:
4310 * query pagesize used to determine if an implicit NRE can be used
4313 mono_target_pagesize (void)
4315 /* We could query the system's pagesize via mono_pagesize (), however there
4316 * are pitfalls: sysconf (3) is called on some posix like systems, and per
4317 * POSIX.1-2008 this function doesn't have to be async-safe. Since this
4318 * function can be called from a signal handler, we simplify things by
4319 * using 4k on all targets. Implicit null-checks with an offset larger than
4320 * 4k are _very_ uncommon, so we don't mind emitting an explicit null-check
4321 * for those cases.
4323 return 4 * 1024;
4326 MonoCPUFeatures
4327 mini_get_cpu_features (MonoCompile* cfg)
4329 MonoCPUFeatures features = (MonoCPUFeatures)0;
4330 #if !defined(MONO_CROSS_COMPILE)
4331 if (!cfg->compile_aot || cfg->use_current_cpu) {
4332 // detect current CPU features if we are in JIT mode or AOT with use_current_cpu flag.
4333 #if defined(ENABLE_LLVM) && !defined(MONO_LLVM_LOADED)
4334 features = mono_llvm_get_cpu_features (); // llvm has a nice built-in API to detect features
4335 #elif defined(TARGET_AMD64)
4336 features = mono_arch_get_cpu_features ();
4337 #endif
4339 #endif
4341 // apply parameters passed via -mattr
4342 return (features | mono_cpu_features_enabled) & ~mono_cpu_features_disabled;