2 * aot-compiler.c: mono Ahead of Time compiler
5 * Dietmar Maurer (dietmar@ximian.com)
6 * Zoltan Varga (vargaz@gmail.com)
8 * (C) 2002 Ximian, Inc.
11 /* Remaining AOT-only work:
12 * - reduce the length of the wrapper names.
13 * - aot IMT tables, so we don't have two kinds of aot code.
14 * - optimize the trampolines, generate more code in the arch files.
15 * - make things more consistent with how elf works, for example, use ELF
17 * Remaining generics sharing work:
18 * - optimize the size of the data which is encoded.
19 * - optimize the runtime loading of data:
20 * - the trampoline code calls mono_jit_info_table_find () to find the rgctx,
21 * which loads the debugging+exception handling info for the method. This is a
22 * huge waste of time and code, since the rgctx structure is currently empty.
23 * - every shared method has a MonoGenericJitInfo structure which is only really
24 * used for handling catch clauses with open types, not a very common use case.
28 #include <sys/types.h>
38 #ifndef PLATFORM_WIN32
48 #include <mono/metadata/tabledefs.h>
49 #include <mono/metadata/class.h>
50 #include <mono/metadata/object.h>
51 #include <mono/metadata/tokentype.h>
52 #include <mono/metadata/appdomain.h>
53 #include <mono/metadata/debug-helpers.h>
54 #include <mono/metadata/assembly.h>
55 #include <mono/metadata/metadata-internals.h>
56 #include <mono/metadata/marshal.h>
57 #include <mono/metadata/gc-internal.h>
58 #include <mono/metadata/monitor.h>
59 #include <mono/metadata/mempool-internals.h>
60 #include <mono/metadata/mono-endian.h>
61 #include <mono/metadata/threads-types.h>
62 #include <mono/utils/mono-logger.h>
63 #include <mono/utils/mono-compiler.h>
64 #include <mono/utils/mono-time.h>
65 #include <mono/utils/mono-mmap.h>
68 #include "image-writer.h"
69 #include "dwarfwriter.h"
71 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
73 #define TV_DECLARE(name) gint64 name
74 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
75 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
78 #define SHARED_EXT ".dll"
79 #elif defined(__ppc__) && defined(__MACH__)
80 #define SHARED_EXT ".dylib"
82 #define SHARED_EXT ".so"
85 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
86 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
87 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
89 typedef struct MonoAotOptions {
92 gboolean write_symbols;
93 gboolean metadata_only;
94 gboolean bind_to_runtime_version;
103 gboolean print_skipped_methods;
106 typedef struct MonoAotStats {
107 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
108 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size, got_info_offsets_size;
109 int methods_without_got_slots, direct_calls, all_calls;
111 int got_slot_types [MONO_PATCH_INFO_NONE];
112 int jit_time, gen_time, link_time;
115 typedef struct MonoAotCompile {
118 GHashTable *method_indexes;
121 GHashTable *patch_to_plt_offset;
122 GHashTable *plt_offset_to_patch;
123 GHashTable *patch_to_got_offset;
124 GPtrArray *got_patches;
125 GHashTable *image_hash;
126 GHashTable *method_to_cfg;
127 GHashTable *token_info_hash;
128 GPtrArray *extra_methods;
129 GPtrArray *image_table;
132 guint32 *plt_got_info_offsets;
133 guint32 got_offset, plt_offset, plt_got_offset_base;
134 /* Number of GOT entries reserved for trampolines */
135 guint32 num_trampoline_got_entries;
137 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
138 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
139 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
141 MonoAotOptions aot_opts;
144 MonoMemPool *mempool;
147 char *static_linking_symbol;
148 CRITICAL_SECTION mutex;
149 gboolean use_bin_writer;
151 MonoDwarfWriter *dwarf;
155 GHashTable *unwind_info_offsets;
156 GPtrArray *unwind_ops;
157 guint32 unwind_info_offset;
159 GHashTable *method_label_hash;
162 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
163 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
165 #ifdef HAVE_ARRAY_ELEM_INIT
166 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
167 #define MSGSTRFIELD1(line) str##line
168 static const struct msgstr_t {
169 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
170 #include "patch-info.h"
173 #define PATCH_INFO(a,b) b,
174 #include "patch-info.h"
177 static const gint16 opidx [] = {
178 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
179 #include "patch-info.h"
183 static G_GNUC_UNUSED const char*
184 get_patch_name (int info)
186 return (const char*)&opstr + opidx [info];
190 #define PATCH_INFO(a,b) b,
191 static const char* const
192 patch_types [MONO_PATCH_INFO_NUM + 1] = {
193 #include "patch-info.h"
198 get_patch_name (int info)
200 return patch_types [info];
205 /* Wrappers around the image writer functions */
208 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
210 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
214 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
216 img_writer_emit_push_section (acfg->w, section_name, subsection);
220 emit_pop_section (MonoAotCompile *acfg)
222 img_writer_emit_pop_section (acfg->w);
226 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
228 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
232 emit_label (MonoAotCompile *acfg, const char *name)
234 img_writer_emit_label (acfg->w, name);
238 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
240 img_writer_emit_bytes (acfg->w, buf, size);
244 emit_string (MonoAotCompile *acfg, const char *value)
246 img_writer_emit_string (acfg->w, value);
250 emit_line (MonoAotCompile *acfg)
252 img_writer_emit_line (acfg->w);
256 emit_alignment (MonoAotCompile *acfg, int size)
258 img_writer_emit_alignment (acfg->w, size);
262 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
264 img_writer_emit_pointer_unaligned (acfg->w, target);
268 emit_pointer (MonoAotCompile *acfg, const char *target)
270 img_writer_emit_pointer (acfg->w, target);
274 emit_int16 (MonoAotCompile *acfg, int value)
276 img_writer_emit_int16 (acfg->w, value);
280 emit_int32 (MonoAotCompile *acfg, int value)
282 img_writer_emit_int32 (acfg->w, value);
286 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
288 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
292 emit_zero_bytes (MonoAotCompile *acfg, int num)
294 img_writer_emit_zero_bytes (acfg->w, num);
298 emit_byte (MonoAotCompile *acfg, guint8 val)
300 img_writer_emit_byte (acfg->w, val);
303 static G_GNUC_UNUSED void
304 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
306 img_writer_emit_global (acfg->w, name, func);
310 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
312 if (acfg->aot_opts.no_dlsym) {
313 g_ptr_array_add (acfg->globals, g_strdup (name));
315 img_writer_emit_global (acfg->w, name, func);
320 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
322 img_writer_emit_section_change (acfg->w, ".text", 1);
323 emit_global (acfg, name, FALSE);
324 img_writer_emit_label (acfg->w, name);
325 img_writer_emit_string (acfg->w, value);
328 static G_GNUC_UNUSED void
329 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
332 guint8 b = value & 0x7f;
334 if (value != 0) /* more bytes to come */
340 static G_GNUC_UNUSED void
341 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
344 gboolean negative = (value < 0);
351 /* the following is unnecessary if the
352 * implementation of >>= uses an arithmetic rather
353 * than logical shift for a signed left operand
357 value |= - ((gint64)1 <<(size - 7));
358 /* sign bit of byte is second high order bit (0x40) */
359 if ((value == 0 && !(byte & 0x40)) ||
360 (value == -1 && (byte & 0x40)))
364 emit_byte (acfg, byte);
368 static G_GNUC_UNUSED void
369 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
374 guint8 b = value & 0x7f;
376 if (value != 0) /* more bytes to come */
384 static G_GNUC_UNUSED void
385 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
388 gboolean negative = (value < 0);
396 /* the following is unnecessary if the
397 * implementation of >>= uses an arithmetic rather
398 * than logical shift for a signed left operand
402 value |= - (1 <<(size - 7));
403 /* sign bit of byte is second high order bit (0x40) */
404 if ((value == 0 && !(byte & 0x40)) ||
405 (value == -1 && (byte & 0x40)))
415 /* ARCHITECTURE SPECIFIC CODE */
417 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM)
418 #define EMIT_DWARF_INFO 1
422 * arch_emit_direct_call:
424 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
428 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
430 #if defined(TARGET_X86) || defined(TARGET_AMD64)
431 /* Need to make sure this is exactly 5 bytes long */
432 emit_byte (acfg, '\xe8');
433 emit_symbol_diff (acfg, target, ".", -4);
435 #elif defined(TARGET_ARM)
436 if (acfg->use_bin_writer) {
443 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
444 emit_bytes (acfg, buf, 4);
446 img_writer_emit_unset_mode (acfg->w);
447 fprintf (acfg->fp, "bl %s\n", target);
451 g_assert_not_reached ();
455 #ifdef MONO_ARCH_AOT_SUPPORTED
457 * arch_emit_got_offset:
459 * The memory pointed to by CODE should hold native code for computing the GOT
460 * address. Emit this code while patching it with the offset between code and
461 * the GOT. CODE_SIZE is set to the number of bytes emitted.
464 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
466 guint32 offset = mono_arch_get_patch_offset (code);
467 emit_bytes (acfg, code, offset);
468 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
470 *code_size = offset + 4;
474 * arch_emit_got_access:
476 * The memory pointed to by CODE should hold native code for loading a GOT
477 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
478 * CODE_SIZE is set to the number of bytes emitted.
481 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
483 /* Emit beginning of instruction */
484 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
486 /* Emit the offset */
488 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
489 #elif defined(TARGET_X86)
490 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
491 #elif defined(TARGET_ARM)
492 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
494 g_assert_not_reached ();
497 *code_size = mono_arch_get_patch_offset (code) + 4;
503 * arch_emit_plt_entry:
505 * Emit code for the PLT entry with index INDEX.
508 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
510 #if defined(TARGET_X86)
512 /* It is filled up during loading by the AOT loader. */
513 emit_zero_bytes (acfg, 16);
515 /* Need to make sure this is 9 bytes long */
516 emit_byte (acfg, '\xe9');
517 emit_symbol_diff (acfg, "plt", ".", -4);
518 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
520 #elif defined(TARGET_AMD64)
522 * We can't emit jumps because they are 32 bits only so they can't be patched.
523 * So we make indirect calls through GOT entries which are patched by the AOT
524 * loader to point to .Lpd entries.
525 * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
527 /* jmpq *<offset>(%rip) */
528 emit_byte (acfg, '\xff');
529 emit_byte (acfg, '\x25');
530 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
531 /* Used by mono_aot_get_plt_info_offset */
532 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
533 #elif defined(TARGET_ARM)
538 * - optimize OP_AOTCONST implementation
539 * - optimize the PLT entries
540 * - optimize SWITCH AOT implementation
541 * - implement IMT support
544 if (acfg->use_bin_writer) {
545 /* We only emit 1 relocation since we implement it ourselves anyway */
546 img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, acfg->got_symbol, ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
547 /* FIXME: A 2 instruction encoding is sufficient in most cases */
548 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
549 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
550 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
551 emit_bytes (acfg, buf, code - buf);
552 /* FIXME: Get rid of this */
553 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
554 /* Used by mono_aot_get_plt_info_offset */
555 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
557 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
558 ARM_ADD_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
559 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
560 emit_bytes (acfg, buf, code - buf);
561 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
562 /* Used by mono_aot_get_plt_info_offset */
563 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
566 g_assert_not_reached ();
571 * arch_emit_specific_trampoline:
573 * Emit code for a specific trampoline. OFFSET is the offset of the first of
574 * two GOT slots which contain the generic trampoline address and the trampoline
575 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
578 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
581 * The trampolines created here are variations of the specific
582 * trampolines created in mono_arch_create_specific_trampoline (). The
584 * - the generic trampoline address is taken from a got slot.
585 * - the offset of the got slot where the trampoline argument is stored
586 * is embedded in the instruction stream, and the generic trampoline
587 * can load the argument by loading the offset, adding it to the
588 * address of the trampoline to get the address of the got slot, and
589 * loading the argument from there.
590 * - all the trampolines should be of the same length.
592 #if defined(TARGET_AMD64)
593 /* This should be exactly 16 bytes long */
595 /* call *<offset>(%rip) */
596 emit_byte (acfg, '\x41');
597 emit_byte (acfg, '\xff');
598 emit_byte (acfg, '\x15');
599 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
600 /* This should be relative to the start of the trampoline */
601 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 19);
602 emit_zero_bytes (acfg, 5);
603 #elif defined(TARGET_ARM)
607 /* This should be exactly 28 bytes long */
610 ARM_PUSH (code, 0x5fff);
611 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
612 /* Load the value from the GOT */
613 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
615 ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
616 ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
618 g_assert (code - buf == 20);
621 emit_bytes (acfg, buf, code - buf);
622 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
623 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
625 g_assert_not_reached ();
630 * arch_emit_unbox_trampoline:
632 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
633 * CALL_TARGET is the symbol pointing to the native code of METHOD.
636 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
638 #if defined(TARGET_AMD64)
643 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
645 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
647 emit_bytes (acfg, buf, code - buf);
649 emit_byte (acfg, '\xe9');
650 emit_symbol_diff (acfg, call_target, ".", -4);
651 #elif defined(TARGET_ARM)
658 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
661 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
663 emit_bytes (acfg, buf, code - buf);
665 if (acfg->use_bin_writer) {
672 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
673 emit_bytes (acfg, buf, 4);
675 fprintf (acfg->fp, "\n\tb %s\n", call_target);
678 g_assert_not_reached ();
683 * arch_emit_static_rgctx_trampoline:
685 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
686 * two GOT slots which contain the rgctx argument, and the method to jump to.
687 * TRAMP_SIZE is set to the size of the emitted trampoline.
688 * These kinds of trampolines cannot be enumerated statically, since there could
689 * be one trampoline per method instantiation, so we emit the same code for all
690 * trampolines, and parameterize them using two GOT slots.
693 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
695 #if defined(TARGET_AMD64)
696 /* This should be exactly 13 bytes long */
699 /* mov <OFFSET>(%rip), %r10 */
700 emit_byte (acfg, '\x4d');
701 emit_byte (acfg, '\x8b');
702 emit_byte (acfg, '\x15');
703 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
705 /* jmp *<offset>(%rip) */
706 emit_byte (acfg, '\xff');
707 emit_byte (acfg, '\x25');
708 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
709 #elif defined(TARGET_ARM)
713 /* This should be exactly 24 bytes long */
716 /* Load rgctx value */
717 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
718 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_R1);
719 /* Load branch addr + branch */
720 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
721 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_R1);
723 g_assert (code - buf == 16);
726 emit_bytes (acfg, buf, code - buf);
727 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
728 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
730 g_assert_not_reached ();
735 * arch_emit_imt_thunk:
737 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
738 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
739 * key is the IMT key, and ptr holds the address of a memory location holding
740 * the address to branch to if the IMT arg matches the key. The array is
741 * terminated by a pair whose key is NULL, and whose ptr is the address of the
743 * TRAMP_SIZE is set to the size of the emitted trampoline.
746 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
748 #if defined(TARGET_AMD64)
752 code = buf = g_malloc (256);
754 /* FIXME: Optimize this, i.e. use binary search etc. */
755 /* Maybe move the body into a separate function (slower, but much smaller) */
757 /* R10 is a free register */
760 amd64_alu_membase_imm (code, X86_CMP, AMD64_R10, 0, 0);
762 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
765 amd64_alu_membase_reg (code, X86_CMP, AMD64_R10, 0, MONO_ARCH_IMT_REG);
767 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
770 amd64_alu_reg_imm (code, X86_ADD, AMD64_R10, 2 * sizeof (gpointer));
771 amd64_jump_code (code, labels [0]);
774 mono_amd64_patch (labels [2], code);
775 amd64_mov_reg_membase (code, AMD64_R10, AMD64_R10, sizeof (gpointer), 8);
776 amd64_jump_membase (code, AMD64_R10, 0);
780 mono_amd64_patch (labels [1], code);
781 x86_breakpoint (code);
783 /* mov <OFFSET>(%rip), %r10 */
784 emit_byte (acfg, '\x4d');
785 emit_byte (acfg, '\x8b');
786 emit_byte (acfg, '\x15');
787 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
789 emit_bytes (acfg, buf, code - buf);
791 *tramp_size = code - buf + 7;
792 #elif defined(TARGET_ARM)
794 guint8 *code, *code2, *labels [16];
798 /* The IMT method is in v5 */
800 /* Only IP is available, but we need at least two free registers */
801 ARM_PUSH1 (code, ARMREG_R1);
803 /* Load the parameter from the GOT */
804 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
805 ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
808 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_IP, 0);
809 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
811 ARM_B_COND (code, ARMCOND_EQ, 0);
813 /* End-of-loop check */
814 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
816 ARM_B_COND (code, ARMCOND_EQ, 0);
819 ARM_ADD_REG_IMM8 (code, ARMREG_IP, ARMREG_IP, sizeof (gpointer) * 2);
822 arm_patch (labels [4], labels [1]);
825 arm_patch (labels [2], code);
826 ARM_POP1 (code, ARMREG_R1);
827 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_IP, 4);
828 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
831 arm_patch (labels [3], code);
836 ARM_LDR_IMM (code2, ARMREG_IP, ARMREG_PC, (code - (labels [0] + 8)));
838 emit_bytes (acfg, buf, code - buf);
839 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
841 *tramp_size = code - buf + 4;
843 g_assert_not_reached ();
848 * arch_get_cie_program:
850 * Get the unwind bytecode for the DWARF CIE.
853 arch_get_cie_program (void)
858 mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
859 mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
867 /* END OF ARCH SPECIFIC CODE */
870 mono_get_field_token (MonoClassField *field)
872 MonoClass *klass = field->parent;
875 for (i = 0; i < klass->field.count; ++i) {
876 if (field == &klass->fields [i])
877 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
880 g_assert_not_reached ();
885 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
889 //printf ("ENCODE: %d 0x%x.\n", value, value);
892 * Same encoding as the one used in the metadata, extended to handle values
893 * greater than 0x1fffffff.
895 if ((value >= 0) && (value <= 127))
897 else if ((value >= 0) && (value <= 16383)) {
898 p [0] = 0x80 | (value >> 8);
899 p [1] = value & 0xff;
901 } else if ((value >= 0) && (value <= 0x1fffffff)) {
902 p [0] = (value >> 24) | 0xc0;
903 p [1] = (value >> 16) & 0xff;
904 p [2] = (value >> 8) & 0xff;
905 p [3] = value & 0xff;
910 p [1] = (value >> 24) & 0xff;
911 p [2] = (value >> 16) & 0xff;
912 p [3] = (value >> 8) & 0xff;
913 p [4] = value & 0xff;
921 get_image_index (MonoAotCompile *cfg, MonoImage *image)
925 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
929 index = g_hash_table_size (cfg->image_hash);
930 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
931 g_ptr_array_add (cfg->image_table, image);
937 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
942 /* FIXME: Search referenced images as well */
943 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
944 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
949 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
950 return MONO_TOKEN_TYPE_SPEC | (i + 1);
956 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
961 * Encode a reference to KLASS. We use our home-grown encoding instead of the
962 * standard metadata encoding.
965 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
969 if (klass->generic_class) {
971 g_assert (klass->type_token);
973 /* Find a typespec for a class if possible */
974 token = find_typespec_for_class (acfg, klass);
976 encode_value (token, p, &p);
977 encode_value (get_image_index (acfg, acfg->image), p, &p);
979 MonoClass *gclass = klass->generic_class->container_class;
980 MonoGenericInst *inst = klass->generic_class->context.class_inst;
983 /* Encode it ourselves */
985 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
986 encode_value (MONO_TYPE_GENERICINST, p, &p);
987 encode_klass_ref (acfg, gclass, p, &p);
988 encode_value (inst->type_argc, p, &p);
989 for (i = 0; i < inst->type_argc; ++i)
990 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
992 } else if (klass->type_token) {
993 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
994 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
995 encode_value (get_image_index (acfg, klass->image), p, &p);
996 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
997 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
998 g_assert (container);
1001 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1002 encode_value (klass->byval_arg.type, p, &p);
1004 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1006 encode_value (container->is_method, p, &p);
1007 if (container->is_method)
1008 encode_method_ref (acfg, container->owner.method, p, &p);
1010 encode_klass_ref (acfg, container->owner.klass, p, &p);
1013 g_assert (klass->rank > 0);
1014 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1015 encode_value (get_image_index (acfg, klass->image), p, &p);
1016 encode_value (klass->rank, p, &p);
1017 encode_klass_ref (acfg, klass->element_class, p, &p);
1023 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1025 guint32 token = mono_get_field_token (field);
1028 encode_klass_ref (cfg, field->parent, p, &p);
1029 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1030 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1035 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1039 MonoGenericInst *inst;
1041 /* Encode the context */
1042 inst = context->class_inst;
1043 encode_value (inst ? 1 : 0, p, &p);
1045 encode_value (inst->type_argc, p, &p);
1046 for (i = 0; i < inst->type_argc; ++i)
1047 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1049 inst = context->method_inst;
1050 encode_value (inst ? 1 : 0, p, &p);
1052 encode_value (inst->type_argc, p, &p);
1053 for (i = 0; i < inst->type_argc; ++i)
1054 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1060 #define MAX_IMAGE_INDEX 250
1063 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1065 guint32 image_index = get_image_index (acfg, method->klass->image);
1066 guint32 token = method->token;
1067 MonoJumpInfoToken *ji;
1072 * The encoding for most methods is as follows:
1073 * - image index encoded as a leb128
1074 * - token index encoded as a leb128
1075 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1076 * types of method encodings.
1079 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1081 /* Mark methods which can't use aot trampolines because they need the further
1082 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1084 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1085 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1086 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1089 * Some wrapper methods are shared using their signature, encode their
1090 * stringified signature instead.
1091 * FIXME: Optimize disk usage
1094 if (method->wrapper_type) {
1095 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1096 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1097 if (mono_marshal_method_from_wrapper (method) != method) {
1098 /* Direct wrapper, encode it normally */
1100 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1103 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1104 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1105 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1107 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1108 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1109 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1111 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1112 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1113 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1119 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1120 strcpy ((char*)p, name);
1121 p += strlen (name) + 1;
1123 } else if (method->wrapper_type) {
1124 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1126 encode_value (method->wrapper_type, p, &p);
1128 switch (method->wrapper_type) {
1129 case MONO_WRAPPER_REMOTING_INVOKE:
1130 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1131 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1134 m = mono_marshal_method_from_wrapper (method);
1136 encode_method_ref (acfg, m, p, &p);
1139 case MONO_WRAPPER_PROXY_ISINST:
1140 case MONO_WRAPPER_LDFLD:
1141 case MONO_WRAPPER_LDFLDA:
1142 case MONO_WRAPPER_STFLD:
1143 case MONO_WRAPPER_ISINST: {
1144 MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
1145 encode_klass_ref (acfg, proxy_class, p, &p);
1148 case MONO_WRAPPER_LDFLD_REMOTE:
1149 case MONO_WRAPPER_STFLD_REMOTE:
1151 case MONO_WRAPPER_ALLOC: {
1152 int alloc_type = mono_gc_get_managed_allocator_type (method);
1153 g_assert (alloc_type != -1);
1154 encode_value (alloc_type, p, &p);
1157 case MONO_WRAPPER_STELEMREF:
1159 case MONO_WRAPPER_UNKNOWN:
1160 if (strcmp (method->name, "FastMonitorEnter") == 0)
1161 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1162 else if (strcmp (method->name, "FastMonitorExit") == 0)
1163 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1165 g_assert_not_reached ();
1167 case MONO_WRAPPER_SYNCHRONIZED:
1168 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1169 case MONO_WRAPPER_RUNTIME_INVOKE: {
1172 m = mono_marshal_method_from_wrapper (method);
1174 g_assert (m != method);
1175 encode_method_ref (acfg, m, p, &p);
1179 g_assert_not_reached ();
1181 } else if (mono_method_signature (method)->is_inflated) {
1183 * This is a generic method, find the original token which referenced it and
1185 * Obtain the token from information recorded by the JIT.
1187 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1189 image_index = get_image_index (acfg, ji->image);
1190 g_assert (image_index < MAX_IMAGE_INDEX);
1193 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1194 encode_value (image_index, p, &p);
1195 encode_value (token, p, &p);
1197 MonoMethod *declaring;
1198 MonoGenericContext *context = mono_method_get_context (method);
1200 g_assert (method->is_inflated);
1201 declaring = ((MonoMethodInflated*)method)->declaring;
1204 * This might be a non-generic method of a generic instance, which
1205 * doesn't have a token since the reference is generated by the JIT
1206 * like Nullable:Box/Unbox, or by generic sharing.
1209 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1210 /* Encode the klass */
1211 encode_klass_ref (acfg, method->klass, p, &p);
1212 /* Encode the method */
1213 image_index = get_image_index (acfg, method->klass->image);
1214 g_assert (image_index < MAX_IMAGE_INDEX);
1215 g_assert (declaring->token);
1216 token = declaring->token;
1217 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1218 encode_value (image_index, p, &p);
1219 encode_value (token, p, &p);
1220 encode_generic_context (acfg, context, p, &p);
1222 } else if (token == 0) {
1223 /* This might be a method of a constructed type like int[,].Set */
1224 /* Obtain the token from information recorded by the JIT */
1225 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1227 image_index = get_image_index (acfg, ji->image);
1228 g_assert (image_index < MAX_IMAGE_INDEX);
1231 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1232 encode_value (image_index, p, &p);
1233 encode_value (token, p, &p);
1236 g_assert (method->klass->rank);
1238 /* Encode directly */
1239 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1240 encode_klass_ref (acfg, method->klass, p, &p);
1241 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1242 encode_value (0, p, &p);
1243 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1244 encode_value (1, p, &p);
1245 else if (!strcmp (method->name, "Get"))
1246 encode_value (2, p, &p);
1247 else if (!strcmp (method->name, "Address"))
1248 encode_value (3, p, &p);
1249 else if (!strcmp (method->name, "Set"))
1250 encode_value (4, p, &p);
1252 g_assert_not_reached ();
1255 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1256 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1262 compare_patches (gconstpointer a, gconstpointer b)
1266 i = (*(MonoJumpInfo**)a)->ip.i;
1267 j = (*(MonoJumpInfo**)b)->ip.i;
1281 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
1284 static inline gboolean
1285 is_plt_patch (MonoJumpInfo *patch_info)
1287 switch (patch_info->type) {
1288 case MONO_PATCH_INFO_METHOD:
1289 case MONO_PATCH_INFO_INTERNAL_METHOD:
1290 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1291 case MONO_PATCH_INFO_ICALL_ADDR:
1292 case MONO_PATCH_INFO_CLASS_INIT:
1293 case MONO_PATCH_INFO_RGCTX_FETCH:
1294 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1295 case MONO_PATCH_INFO_MONITOR_ENTER:
1296 case MONO_PATCH_INFO_MONITOR_EXIT:
1304 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1308 if (is_plt_patch (patch_info)) {
1309 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1311 if (patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1313 * Allocate a separate PLT slot for each such patch, since some plt
1314 * entries will refer to the method itself, and some will refer to
1323 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1325 res = acfg->plt_offset;
1326 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1327 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1328 acfg->plt_offset ++;
1338 * Returns the offset of the GOT slot where the runtime object resulting from resolving
1339 * JI could be found if it exists, otherwise allocates a new one.
1342 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1346 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset, ji));
1348 return got_offset - 1;
1350 got_offset = acfg->got_offset;
1351 acfg->got_offset ++;
1353 acfg->stats.got_slots ++;
1354 acfg->stats.got_slot_types [ji->type] ++;
1356 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
1357 g_ptr_array_add (acfg->got_patches, ji);
1362 /* Add a method to the list of methods which need to be emitted */
1364 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
1367 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1368 g_ptr_array_add (acfg->methods, method);
1369 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1370 acfg->nmethods = acfg->methods->len + 1;
1373 if (method->wrapper_type || extra)
1374 g_ptr_array_add (acfg->extra_methods, method);
1378 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1380 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1388 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra)
1392 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1396 index = acfg->method_index;
1397 add_method_with_index (acfg, method, index, extra);
1399 /* FIXME: Fix quadratic behavior */
1400 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1402 acfg->method_index ++;
1408 add_method (MonoAotCompile *acfg, MonoMethod *method)
1410 return add_method_full (acfg, method, FALSE);
1414 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
1416 add_method_full (acfg, method, TRUE);
1420 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1422 MonoAotCompile *acfg = user_data;
1423 MonoJitICallInfo *callinfo = value;
1424 MonoMethod *wrapper;
1430 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1431 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1434 add_method (acfg, wrapper);
1438 get_runtime_invoke_sig (MonoMethodSignature *sig)
1440 MonoMethodBuilder *mb;
1443 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1444 m = mono_mb_create_method (mb, sig, 16);
1445 return mono_marshal_get_runtime_invoke (m, FALSE);
1449 add_wrappers (MonoAotCompile *acfg)
1451 MonoMethod *method, *m;
1452 int i, j, nallocators;
1453 MonoMethodSignature *sig, *csig;
1457 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1458 * so there is only one wrapper of a given type, or inlining their contents into their
1463 * FIXME: This depends on the fact that different wrappers have different
1467 /* FIXME: Collect these automatically */
1469 /* Runtime invoke wrappers */
1471 /* void runtime-invoke () [.cctor] */
1472 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1473 csig->ret = &mono_defaults.void_class->byval_arg;
1474 add_method (acfg, get_runtime_invoke_sig (csig));
1476 /* void runtime-invoke () [Finalize] */
1477 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1479 csig->ret = &mono_defaults.void_class->byval_arg;
1480 add_method (acfg, get_runtime_invoke_sig (csig));
1482 /* void runtime-invoke (string) [exception ctor] */
1483 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
1485 csig->ret = &mono_defaults.void_class->byval_arg;
1486 csig->params [0] = &mono_defaults.string_class->byval_arg;
1487 add_method (acfg, get_runtime_invoke_sig (csig));
1489 /* void runtime-invoke (string, string) [exception ctor] */
1490 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1492 csig->ret = &mono_defaults.void_class->byval_arg;
1493 csig->params [0] = &mono_defaults.string_class->byval_arg;
1494 csig->params [1] = &mono_defaults.string_class->byval_arg;
1495 add_method (acfg, get_runtime_invoke_sig (csig));
1497 /* string runtime-invoke () [Exception.ToString ()] */
1498 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1500 csig->ret = &mono_defaults.string_class->byval_arg;
1501 add_method (acfg, get_runtime_invoke_sig (csig));
1503 /* void runtime-invoke (string, Exception) [exception ctor] */
1504 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1506 csig->ret = &mono_defaults.void_class->byval_arg;
1507 csig->params [0] = &mono_defaults.string_class->byval_arg;
1508 csig->params [1] = &mono_defaults.exception_class->byval_arg;
1509 add_method (acfg, get_runtime_invoke_sig (csig));
1511 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
1512 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1514 csig->ret = &(mono_class_from_name (
1515 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
1516 csig->params [0] = &mono_defaults.string_class->byval_arg;
1517 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
1518 add_method (acfg, get_runtime_invoke_sig (csig));
1520 /* runtime-invoke used by finalizers */
1521 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
1523 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1525 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1526 gboolean skip = FALSE;
1528 method = mono_get_method (acfg->image, token, NULL);
1530 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1531 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1532 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1535 if (method->is_generic || method->klass->generic_container)
1538 /* Skip methods which can not be handled by get_runtime_invoke () */
1539 sig = mono_method_signature (method);
1540 if ((sig->ret->type == MONO_TYPE_PTR) ||
1541 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
1544 for (j = 0; j < sig->param_count; j++) {
1545 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
1550 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
1553 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
1554 MonoMethodDesc *desc;
1555 MonoMethod *orig_method;
1557 /* JIT icall wrappers */
1558 /* FIXME: locking */
1559 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
1561 /* Managed Allocators */
1562 nallocators = mono_gc_get_managed_allocator_types ();
1563 for (i = 0; i < nallocators; ++i) {
1564 m = mono_gc_get_managed_allocator_by_type (i);
1566 add_method (acfg, m);
1570 add_method (acfg, mono_marshal_get_stelemref ());
1572 /* Monitor Enter/Exit */
1573 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
1574 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1575 g_assert (orig_method);
1576 mono_method_desc_free (desc);
1577 method = mono_monitor_get_fast_path (orig_method);
1579 add_method (acfg, method);
1581 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
1582 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1583 g_assert (orig_method);
1584 mono_method_desc_free (desc);
1585 method = mono_monitor_get_fast_path (orig_method);
1587 add_method (acfg, method);
1590 /* remoting-invoke wrappers */
1591 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1592 MonoMethodSignature *sig;
1594 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1595 method = mono_get_method (acfg->image, token, NULL);
1597 sig = mono_method_signature (method);
1599 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
1600 m = mono_marshal_get_remoting_invoke_with_check (method);
1602 add_method (acfg, m);
1606 /* delegate-invoke wrappers */
1607 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1610 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1611 klass = mono_class_get (acfg->image, token);
1613 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
1614 method = mono_get_delegate_invoke (klass);
1616 m = mono_marshal_get_delegate_invoke (method, NULL);
1618 add_method (acfg, m);
1620 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
1621 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
1623 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
1624 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
1628 /* Synchronized wrappers */
1629 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1630 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1631 method = mono_get_method (acfg->image, token, NULL);
1633 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
1634 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
1637 /* pinvoke wrappers */
1638 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1640 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1642 method = mono_get_method (acfg->image, token, NULL);
1644 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1645 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1646 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
1650 /* StructureToPtr/PtrToStructure wrappers */
1651 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1654 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1655 klass = mono_class_get (acfg->image, token);
1657 if (klass->valuetype && !klass->generic_container && ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) != TYPE_ATTRIBUTE_AUTO_LAYOUT)) {
1658 MonoMarshalType *info;
1659 gboolean can_marshal = TRUE;
1662 info = mono_marshal_load_type_info (klass);
1664 /* Only allow a few field types to avoid asserts in the marshalling code */
1665 for (j = 0; j < info->num_fields; j++) {
1666 switch (info->fields [j].field->type->type) {
1671 case MONO_TYPE_BOOLEAN:
1674 case MONO_TYPE_CHAR:
1682 can_marshal = FALSE;
1688 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
1689 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
1696 has_type_vars (MonoClass *klass)
1698 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
1701 return has_type_vars (klass->element_class);
1702 if (klass->generic_class) {
1703 MonoGenericContext *context = &klass->generic_class->context;
1704 if (context->class_inst) {
1707 for (i = 0; i < context->class_inst->type_argc; ++i)
1708 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
1716 method_has_type_vars (MonoMethod *method)
1718 if (has_type_vars (method->klass))
1721 if (method->is_inflated) {
1722 MonoGenericContext *context = mono_method_get_context (method);
1723 if (context->method_inst) {
1726 for (i = 0; i < context->method_inst->type_argc; ++i)
1727 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
1735 * add_generic_class:
1737 * Add all methods of a generic class.
1740 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
1745 mono_class_init (klass);
1747 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
1750 if (has_type_vars (klass))
1753 if (!klass->generic_class && !klass->rank)
1757 while ((method = mono_class_get_methods (klass, &iter))) {
1758 if (mono_method_is_generic_sharable_impl (method, FALSE))
1762 if (method->is_generic)
1767 * FIXME: Instances which are referenced by these methods are not added,
1768 * for example Array.Resize<int> for List<int>.Add ().
1770 add_extra_method (acfg, method);
1774 * For ICollection<T>, where T is a vtype, add instances of the helper methods
1775 * in Array, since a T[] could be cast to ICollection<T>.
1777 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
1778 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1")) &&
1779 MONO_TYPE_ISSTRUCT (klass->generic_class->context.class_inst->type_argv [0])) {
1780 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
1781 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
1785 if (!strcmp (klass->name, "IEnumerator`1"))
1786 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
1788 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
1790 /* Add the T[]/InternalEnumerator class */
1791 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
1795 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
1796 if (!strcmp (nclass->name, "InternalEnumerator`1"))
1800 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
1801 add_generic_class (acfg, nclass);
1805 while ((method = mono_class_get_methods (array_class, &iter))) {
1806 if (strstr (method->name, name_prefix))
1807 add_extra_method (acfg, method);
1810 g_free (name_prefix);
1815 * add_generic_instances:
1817 * Add instances referenced by the METHODSPEC/TYPESPEC table.
1820 add_generic_instances (MonoAotCompile *acfg)
1825 MonoMethodHeader *header;
1826 MonoMethodSignature *sig;
1827 MonoGenericContext *context;
1829 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
1830 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
1831 method = mono_get_method (acfg->image, token, NULL);
1833 context = mono_method_get_context (method);
1834 if (context && ((context->class_inst && context->class_inst->is_open) ||
1835 (context->method_inst && context->method_inst->is_open)))
1838 if (method->klass->image != acfg->image)
1841 if (mono_method_is_generic_sharable_impl (method, FALSE))
1845 add_extra_method (acfg, method);
1848 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1851 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
1853 klass = mono_class_get (acfg->image, token);
1854 if (!klass || klass->rank)
1857 add_generic_class (acfg, klass);
1860 /* Add types of args/locals */
1861 for (i = 0; i < acfg->methods->len; ++i) {
1864 method = g_ptr_array_index (acfg->methods, i);
1866 sig = mono_method_signature (method);
1869 for (j = 0; j < sig->param_count; ++j)
1870 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
1871 add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
1874 header = mono_method_get_header (method);
1877 for (j = 0; j < header->num_locals; ++j)
1878 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
1879 add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
1885 * emit_and_reloc_code:
1887 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
1888 * is true, calls are made through the GOT too. This is used for emitting trampolines
1889 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
1890 * since trampolines are needed to make PTL work.
1893 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
1895 int i, pindex, start_index, method_index;
1897 MonoJumpInfo *patch_info;
1898 MonoMethodHeader *header;
1899 gboolean skip, direct_call;
1901 char direct_call_target [128];
1904 header = mono_method_get_header (method);
1906 method_index = get_method_index (acfg, method);
1909 /* Collect and sort relocations */
1910 patches = g_ptr_array_new ();
1911 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
1912 g_ptr_array_add (patches, patch_info);
1913 g_ptr_array_sort (patches, compare_patches);
1916 for (i = 0; i < code_len; i++) {
1918 for (pindex = start_index; pindex < patches->len; ++pindex) {
1919 patch_info = g_ptr_array_index (patches, pindex);
1920 if (patch_info->ip.i >= i)
1924 #ifdef MONO_ARCH_AOT_SUPPORTED
1926 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
1927 start_index = pindex;
1929 switch (patch_info->type) {
1930 case MONO_PATCH_INFO_NONE:
1932 case MONO_PATCH_INFO_GOT_OFFSET: {
1935 arch_emit_got_offset (acfg, code + i, &code_size);
1942 * If this patch is a call, try emitting a direct call instead of
1943 * through a PLT entry. This is possible if the called method is in
1944 * the same assembly and requires no initialization.
1946 direct_call = FALSE;
1947 if (!got_only && (patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == method->klass->image)) {
1948 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
1950 gboolean direct_callable = TRUE;
1952 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
1953 direct_callable = FALSE;
1954 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
1955 // FIXME: Maybe call the wrapper directly ?
1956 direct_callable = FALSE;
1957 if (direct_callable) {
1958 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
1960 sprintf (direct_call_target, ".Lm_%x", get_method_index (acfg, callee_cfg->orig_method));
1961 patch_info->type = MONO_PATCH_INFO_NONE;
1962 acfg->stats.direct_calls ++;
1966 acfg->stats.all_calls ++;
1969 if (!got_only && !direct_call) {
1970 int plt_offset = get_plt_offset (acfg, patch_info);
1971 if (plt_offset != -1) {
1972 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
1974 sprintf (direct_call_target, ".Lp_%d", plt_offset);
1976 /* Nullify the patch */
1977 patch_info->type = MONO_PATCH_INFO_NONE;
1984 arch_emit_direct_call (acfg, direct_call_target, &call_size);
1989 got_slot = get_got_offset (acfg, patch_info);
1991 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
1998 #endif /* MONO_ARCH_AOT_SUPPORTED */
2001 /* Find next patch */
2003 for (pindex = start_index; pindex < patches->len; ++pindex) {
2004 patch_info = g_ptr_array_index (patches, pindex);
2005 if (patch_info->ip.i >= i)
2009 /* Try to emit multiple bytes at once */
2010 if (pindex < patches->len && patch_info->ip.i > i) {
2011 emit_bytes (acfg, code + i, patch_info->ip.i - i);
2012 i = patch_info->ip.i - 1;
2014 emit_bytes (acfg, code + i, 1);
2021 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2027 int func_alignment = 16;
2028 MonoMethodHeader *header;
2030 method = cfg->orig_method;
2031 code = cfg->native_code;
2032 header = mono_method_get_header (method);
2034 method_index = get_method_index (acfg, method);
2036 /* Make the labels local */
2037 sprintf (symbol, ".Lm_%x", method_index);
2039 emit_alignment (acfg, func_alignment);
2040 emit_label (acfg, symbol);
2042 if (acfg->aot_opts.write_symbols) {
2043 char *name1, *name2, *cached;
2044 int i, j, len, count;
2047 * Write a C style symbol for every method, this has two uses:
2048 * - it works on platforms where the dwarf debugging info is not
2050 * - it allows the setting of breakpoints of aot-ed methods.
2052 name1 = mono_method_full_name (method, TRUE);
2053 len = strlen (name1);
2054 name2 = malloc (len + 1);
2056 for (i = 0; i < len; ++i) {
2057 if (isalnum (name1 [i])) {
2058 name2 [j ++] = name1 [i];
2059 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
2061 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
2064 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
2071 while (g_hash_table_lookup (acfg->method_label_hash, name2)) {
2072 sprintf (name2 + j, "_%d", count);
2076 cached = g_strdup (name2);
2077 g_hash_table_insert (acfg->method_label_hash, cached, cached);
2079 sprintf (symbol, ".Lme_%x", method_index);
2080 emit_local_symbol (acfg, name2, symbol, TRUE);
2081 emit_label (acfg, name2);
2086 if (cfg->verbose_level > 0)
2087 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2089 acfg->stats.code_size += cfg->code_len;
2091 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
2093 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2097 sprintf (symbol, ".Lme_%x", method_index);
2098 emit_label (acfg, symbol);
2104 * Encode PATCH_INFO into its disk representation.
2107 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2111 switch (patch_info->type) {
2112 case MONO_PATCH_INFO_NONE:
2114 case MONO_PATCH_INFO_IMAGE:
2115 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2117 case MONO_PATCH_INFO_METHOD_REL:
2118 encode_value ((gint)patch_info->data.offset, p, &p);
2120 case MONO_PATCH_INFO_SWITCH: {
2121 gpointer *table = (gpointer *)patch_info->data.table->table;
2124 encode_value (patch_info->data.table->table_size, p, &p);
2125 for (k = 0; k < patch_info->data.table->table_size; k++)
2126 encode_value ((int)(gssize)table [k], p, &p);
2129 case MONO_PATCH_INFO_METHODCONST:
2130 case MONO_PATCH_INFO_METHOD:
2131 case MONO_PATCH_INFO_METHOD_JUMP:
2132 case MONO_PATCH_INFO_ICALL_ADDR:
2133 case MONO_PATCH_INFO_METHOD_RGCTX:
2134 encode_method_ref (acfg, patch_info->data.method, p, &p);
2136 case MONO_PATCH_INFO_INTERNAL_METHOD:
2137 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2138 guint32 len = strlen (patch_info->data.name);
2140 encode_value (len, p, &p);
2142 memcpy (p, patch_info->data.name, len);
2147 case MONO_PATCH_INFO_LDSTR: {
2148 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2149 guint32 token = patch_info->data.token->token;
2150 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2151 encode_value (image_index, p, &p);
2152 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2155 case MONO_PATCH_INFO_RVA:
2156 case MONO_PATCH_INFO_DECLSEC:
2157 case MONO_PATCH_INFO_LDTOKEN:
2158 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2159 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2160 encode_value (patch_info->data.token->token, p, &p);
2161 encode_value (patch_info->data.token->has_context, p, &p);
2162 if (patch_info->data.token->has_context)
2163 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
2165 case MONO_PATCH_INFO_EXC_NAME: {
2166 MonoClass *ex_class;
2169 mono_class_from_name (mono_defaults.exception_class->image,
2170 "System", patch_info->data.target);
2171 g_assert (ex_class);
2172 encode_klass_ref (acfg, ex_class, p, &p);
2175 case MONO_PATCH_INFO_R4:
2176 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2178 case MONO_PATCH_INFO_R8:
2179 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2180 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
2182 case MONO_PATCH_INFO_VTABLE:
2183 case MONO_PATCH_INFO_CLASS:
2184 case MONO_PATCH_INFO_IID:
2185 case MONO_PATCH_INFO_ADJUSTED_IID:
2186 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2188 case MONO_PATCH_INFO_CLASS_INIT:
2189 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2190 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2192 case MONO_PATCH_INFO_FIELD:
2193 case MONO_PATCH_INFO_SFLDA:
2194 encode_field_info (acfg, patch_info->data.field, p, &p);
2196 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2198 case MONO_PATCH_INFO_RGCTX_FETCH: {
2199 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2201 encode_method_ref (acfg, entry->method, p, &p);
2202 encode_value (entry->in_mrgctx, p, &p);
2203 encode_value (entry->info_type, p, &p);
2204 encode_value (entry->data->type, p, &p);
2205 encode_patch (acfg, entry->data, p, &p);
2208 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2209 case MONO_PATCH_INFO_MONITOR_ENTER:
2210 case MONO_PATCH_INFO_MONITOR_EXIT:
2213 g_warning ("unable to handle jump info %d", patch_info->type);
2214 g_assert_not_reached ();
2221 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2224 guint32 pindex, offset;
2225 MonoJumpInfo *patch_info;
2227 encode_value (n_patches, p, &p);
2230 encode_value (first_got_offset, p, &p);
2232 for (pindex = 0; pindex < patches->len; ++pindex) {
2233 patch_info = g_ptr_array_index (patches, pindex);
2235 if (patch_info->type == MONO_PATCH_INFO_NONE)
2239 offset = get_got_offset (acfg, patch_info);
2240 encode_value (offset, p, &p);
2247 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2251 int pindex, buf_size, n_patches;
2255 MonoJumpInfo *patch_info;
2256 MonoMethodHeader *header;
2257 guint32 method_index;
2259 guint32 first_got_offset;
2261 method = cfg->orig_method;
2262 code = cfg->native_code;
2263 header = mono_method_get_header (method);
2265 method_index = get_method_index (acfg, method);
2267 /* Make the labels local */
2268 sprintf (symbol, ".Lm_%x_p", method_index);
2270 /* Sort relocations */
2271 patches = g_ptr_array_new ();
2272 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2273 g_ptr_array_add (patches, patch_info);
2274 g_ptr_array_sort (patches, compare_patches);
2276 first_got_offset = acfg->cfgs [method_index]->got_offset;
2278 /**********************/
2279 /* Encode method info */
2280 /**********************/
2282 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2283 p = buf = g_malloc (buf_size);
2285 if (mono_class_get_cctor (method->klass))
2286 encode_klass_ref (acfg, method->klass, p, &p);
2288 /* Not needed when loading the method */
2289 encode_value (0, p, &p);
2292 if (cfg->opt & MONO_OPT_SHARED) {
2293 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2294 for (l = cfg->ldstr_list; l; l = l->next) {
2295 encode_value ((long)l->data, p, &p);
2299 /* Used only in shared mode */
2300 g_assert (!cfg->ldstr_list);
2303 for (pindex = 0; pindex < patches->len; ++pindex) {
2304 patch_info = g_ptr_array_index (patches, pindex);
2306 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2307 (patch_info->type == MONO_PATCH_INFO_NONE)) {
2308 patch_info->type = MONO_PATCH_INFO_NONE;
2313 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2314 /* Stored in a GOT slot initialized at module load time */
2315 patch_info->type = MONO_PATCH_INFO_NONE;
2319 if (is_plt_patch (patch_info)) {
2320 /* Calls are made through the PLT */
2321 patch_info->type = MONO_PATCH_INFO_NONE;
2329 g_assert (cfg->has_got_slots);
2331 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2333 acfg->stats.info_size += p - buf;
2335 /* Emit method info */
2337 emit_label (acfg, symbol);
2339 g_assert (p - buf < buf_size);
2340 emit_bytes (acfg, buf, p - buf);
2345 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
2347 guint32 cache_index;
2350 /* Reuse the unwind module to canonize and store unwind info entries */
2351 cache_index = mono_cache_unwind_info (encoded, encoded_len);
2353 /* Use +/- 1 to distinguish 0s from missing entries */
2354 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
2362 * It would be easier to use assembler symbols, but the caller needs an
2365 offset = acfg->unwind_info_offset;
2366 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
2367 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
2370 encode_value (encoded_len, p, &p);
2372 acfg->unwind_info_offset += encoded_len + (p - buf);
2378 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2381 int k, buf_size, method_index;
2382 guint32 debug_info_size;
2385 MonoMethodHeader *header;
2386 guint8 *p, *buf, *debug_info;
2387 MonoJitInfo *jinfo = cfg->jit_info;
2389 gboolean use_unwind_ops = FALSE;
2391 method = cfg->orig_method;
2392 code = cfg->native_code;
2393 header = mono_method_get_header (method);
2395 method_index = get_method_index (acfg, method);
2397 /* Make the labels local */
2398 sprintf (symbol, ".Le_%x_p", method_index);
2400 if (!acfg->aot_opts.nodebug) {
2401 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2404 debug_info_size = 0;
2407 buf_size = header->num_clauses * 256 + debug_info_size + 1024;
2408 p = buf = g_malloc (buf_size);
2410 #ifdef MONO_ARCH_HAVE_XP_UNWIND
2411 use_unwind_ops = cfg->unwind_ops != NULL;
2414 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0);
2416 encode_value (jinfo->code_size, p, &p);
2417 encode_value (flags, p, &p);
2419 if (use_unwind_ops) {
2420 guint32 encoded_len;
2424 * This is a duplicate of the data in the .debug_frame section, but that
2425 * section cannot be accessed using the dl interface.
2427 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
2428 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
2431 encode_value (jinfo->used_regs, p, &p);
2434 /* Exception table */
2435 if (header->num_clauses) {
2436 for (k = 0; k < header->num_clauses; ++k) {
2437 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2439 encode_value (ei->exvar_offset, p, &p);
2441 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2442 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2444 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2445 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2446 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
2450 if (jinfo->has_generic_jit_info) {
2451 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
2453 encode_value (gi->has_this ? 1 : 0, p, &p);
2454 encode_value (gi->this_reg, p, &p);
2455 encode_value (gi->this_offset, p, &p);
2458 * Need to encode jinfo->method too, since it is not equal to 'method'
2459 * when using generic sharing.
2461 encode_method_ref (acfg, jinfo->method, p, &p);
2464 g_assert (debug_info_size < buf_size);
2466 encode_value (debug_info_size, p, &p);
2467 if (debug_info_size) {
2468 memcpy (p, debug_info, debug_info_size);
2469 p += debug_info_size;
2470 g_free (debug_info);
2473 acfg->stats.ex_info_size += p - buf;
2477 emit_label (acfg, symbol);
2479 g_assert (p - buf < buf_size);
2480 emit_bytes (acfg, buf, p - buf);
2485 emit_klass_info (MonoAotCompile *acfg, guint32 token)
2487 MonoClass *klass = mono_class_get (acfg->image, token);
2491 gboolean no_special_static, cant_encode;
2492 gpointer iter = NULL;
2494 buf_size = 10240 + (klass->vtable_size * 16);
2495 p = buf = g_malloc (buf_size);
2499 mono_class_init (klass);
2501 mono_class_get_nested_types (klass, &iter);
2502 g_assert (klass->nested_classes_inited);
2504 mono_class_setup_vtable (klass);
2507 * Emit all the information which is required for creating vtables so
2508 * the runtime does not need to create the MonoMethod structures which
2509 * take up a lot of space.
2512 no_special_static = !mono_class_has_special_static_fields (klass);
2514 /* Check whenever we have enough info to encode the vtable */
2515 cant_encode = FALSE;
2516 for (i = 0; i < klass->vtable_size; ++i) {
2517 MonoMethod *cm = klass->vtable [i];
2519 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
2523 if (klass->generic_container || cant_encode) {
2524 encode_value (-1, p, &p);
2526 encode_value (klass->vtable_size, p, &p);
2527 encode_value ((no_special_static << 7) | (klass->has_static_refs << 6) | (klass->has_references << 5) | ((klass->blittable << 4) | ((klass->ext && klass->ext->nested_classes) ? 1 : 0) << 3) | (klass->has_cctor << 2) | (klass->has_finalize << 1) | klass->ghcimpl, p, &p);
2528 if (klass->has_cctor)
2529 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
2530 if (klass->has_finalize)
2531 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
2533 encode_value (klass->instance_size, p, &p);
2534 encode_value (mono_class_data_size (klass), p, &p);
2535 encode_value (klass->packing_size, p, &p);
2536 encode_value (klass->min_align, p, &p);
2538 for (i = 0; i < klass->vtable_size; ++i) {
2539 MonoMethod *cm = klass->vtable [i];
2542 encode_method_ref (acfg, cm, p, &p);
2544 encode_value (0, p, &p);
2548 acfg->stats.class_info_size += p - buf;
2551 sprintf (symbol, ".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
2552 emit_label (acfg, symbol);
2554 g_assert (p - buf < buf_size);
2555 emit_bytes (acfg, buf, p - buf);
2560 * Calls made from AOTed code are routed through a table of jumps similar to the
2561 * ELF PLT (Program Linkage Table). The differences are the following:
2562 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
2563 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
2564 * jumps. This means the jumps need to be patched when the address of the callee is
2565 * known. Initially the PLT entries jump to code which transfers control to the
2566 * AOT runtime through the first PLT entry.
2569 emit_plt (MonoAotCompile *acfg)
2575 sprintf (symbol, "plt");
2577 emit_section_change (acfg, ".text", 0);
2578 emit_global (acfg, symbol, TRUE);
2580 /* This section will be made read-write by the AOT loader */
2581 emit_alignment (acfg, mono_pagesize ());
2583 emit_alignment (acfg, 16);
2585 emit_label (acfg, symbol);
2587 for (i = 0; i < acfg->plt_offset; ++i) {
2590 sprintf (label, ".Lp_%d", i);
2591 emit_label (acfg, label);
2594 * The first plt entry is used to transfer code to the AOT loader.
2596 arch_emit_plt_entry (acfg, i);
2599 sprintf (symbol, "plt_end");
2600 emit_global (acfg, symbol, TRUE);
2601 emit_label (acfg, symbol);
2604 static G_GNUC_UNUSED void
2605 emit_trampoline (MonoAotCompile *acfg, const char *name, guint8 *code,
2606 guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
2610 MonoJumpInfo *patch_info;
2616 sprintf (symbol, "%s", name);
2618 emit_section_change (acfg, ".text", 0);
2619 emit_global (acfg, symbol, TRUE);
2620 emit_alignment (acfg, 16);
2621 emit_label (acfg, symbol);
2623 sprintf (symbol, ".Lnamed_%s", name);
2624 emit_label (acfg, symbol);
2627 * The code should access everything through the GOT, so we pass
2630 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
2634 /* Sort relocations */
2635 patches = g_ptr_array_new ();
2636 for (patch_info = ji; patch_info; patch_info = patch_info->next)
2637 g_ptr_array_add (patches, patch_info);
2638 g_ptr_array_sort (patches, compare_patches);
2640 buf_size = patches->len * 128 + 128;
2641 buf = g_malloc (buf_size);
2644 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
2645 g_assert (p - buf < buf_size);
2647 sprintf (symbol, "%s_p", name);
2649 emit_section_change (acfg, ".text", 0);
2650 emit_global (acfg, symbol, FALSE);
2651 emit_label (acfg, symbol);
2653 emit_bytes (acfg, buf, p - buf);
2655 /* Emit debug info */
2659 sprintf (symbol, "%s", name);
2660 sprintf (symbol2, ".Lnamed_%s", name);
2663 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
2668 emit_trampolines (MonoAotCompile *acfg)
2671 int i, tramp_got_offset;
2672 MonoAotTrampoline ntype;
2673 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2681 if (!acfg->aot_opts.full_aot)
2684 g_assert (acfg->image->assembly);
2686 /* Currently, we only emit most trampolines into the mscorlib AOT image. */
2687 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2688 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2690 * Emit the generic trampolines.
2692 * We could save some code by treating the generic trampolines as a wrapper
2693 * method, but that approach has its own complexities, so we choose the simpler
2696 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
2697 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
2699 /* Emit trampoline code */
2701 sprintf (symbol, "generic_trampoline_%d", tramp_type);
2703 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
2706 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
2707 emit_trampoline (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
2708 #if defined(TARGET_AMD64) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
2709 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
2710 emit_trampoline (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2711 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
2712 emit_trampoline (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2715 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
2716 emit_trampoline (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2718 /* Emit the exception related code pieces */
2719 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
2720 emit_trampoline (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
2721 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
2722 emit_trampoline (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
2723 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
2724 emit_trampoline (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
2725 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
2726 emit_trampoline (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
2727 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
2728 emit_trampoline (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
2729 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
2730 emit_trampoline (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
2732 #if defined(TARGET_AMD64)
2733 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
2734 emit_trampoline (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
2737 #if defined(TARGET_AMD64) || defined(TARGET_ARM)
2738 for (i = 0; i < 128; ++i) {
2741 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
2742 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
2743 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
2744 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
2746 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
2747 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
2748 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
2749 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
2753 #if defined(TARGET_AMD64) || defined(TARGET_ARM)
2757 /* delegate_invoke_impl trampolines */
2758 l = mono_arch_get_delegate_invoke_impls ();
2760 MonoAotTrampInfo *info = l->data;
2762 emit_trampoline (acfg, info->name, info->code, info->code_size, acfg->got_offset, NULL, NULL);
2768 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
2770 /* Emit trampolines which are numerous */
2773 * These include the following:
2774 * - specific trampolines
2775 * - static rgctx invoke trampolines
2777 * These trampolines have the same code, they are parameterized by GOT
2779 * They are defined in this file, in the arch_... routines instead of
2780 * in tramp-<ARCH>.c, since it is easier to do it this way.
2784 * When running in aot-only mode, we can't create specific trampolines at
2785 * runtime, so we create a few, and save them in the AOT file.
2786 * Normal trampolines embed their argument as a literal inside the
2787 * trampoline code, we can't do that here, so instead we embed an offset
2788 * which needs to be added to the trampoline address to get the address of
2789 * the GOT slot which contains the argument value.
2790 * The generated trampolines jump to the generic trampolines using another
2791 * GOT slot, which will be setup by the AOT loader to point to the
2792 * generic trampoline code of the given type.
2796 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
2800 emit_section_change (acfg, ".text", 0);
2802 tramp_got_offset = acfg->got_offset;
2804 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
2806 case MONO_AOT_TRAMP_SPECIFIC:
2807 sprintf (symbol, "specific_trampolines");
2809 case MONO_AOT_TRAMP_STATIC_RGCTX:
2810 sprintf (symbol, "static_rgctx_trampolines");
2812 case MONO_AOT_TRAMP_IMT_THUNK:
2813 sprintf (symbol, "imt_thunks");
2816 g_assert_not_reached ();
2819 emit_global (acfg, symbol, TRUE);
2820 emit_alignment (acfg, 16);
2821 emit_label (acfg, symbol);
2823 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
2825 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
2829 case MONO_AOT_TRAMP_SPECIFIC:
2830 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
2831 tramp_got_offset += 2;
2833 case MONO_AOT_TRAMP_STATIC_RGCTX:
2834 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
2835 tramp_got_offset += 2;
2837 case MONO_AOT_TRAMP_IMT_THUNK:
2838 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
2839 tramp_got_offset += 1;
2842 g_assert_not_reached ();
2845 if (!acfg->trampoline_size [ntype]) {
2846 g_assert (tramp_size);
2847 acfg->trampoline_size [ntype] = tramp_size;
2852 /* Reserve some entries at the end of the GOT for our use */
2853 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
2856 /* Unbox trampolines */
2857 for (i = 0; i < acfg->methods->len; ++i) {
2858 MonoMethod *method = g_ptr_array_index (acfg->methods, i);
2860 char call_target [256];
2862 cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
2863 if (!cfg || !cfg->orig_method->klass->valuetype || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
2866 if (!method->wrapper_type && !method->is_inflated) {
2867 g_assert (method->token);
2868 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
2870 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
2873 emit_section_change (acfg, ".text", 0);
2874 emit_global (acfg, symbol, TRUE);
2875 emit_label (acfg, symbol);
2877 sprintf (call_target, ".Lm_%x", get_method_index (acfg, cfg->orig_method));
2879 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
2882 acfg->got_offset += acfg->num_trampoline_got_entries;
2886 str_begins_with (const char *str1, const char *str2)
2888 int len = strlen (str2);
2889 return strncmp (str1, str2, len) == 0;
2893 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
2895 gchar **args, **ptr;
2897 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
2898 for (ptr = args; ptr && *ptr; ptr ++) {
2899 const char *arg = *ptr;
2901 if (str_begins_with (arg, "outfile=")) {
2902 opts->outfile = g_strdup (arg + strlen ("outfile="));
2903 } else if (str_begins_with (arg, "save-temps")) {
2904 opts->save_temps = TRUE;
2905 } else if (str_begins_with (arg, "keep-temps")) {
2906 opts->save_temps = TRUE;
2907 } else if (str_begins_with (arg, "write-symbols")) {
2908 opts->write_symbols = TRUE;
2909 } else if (str_begins_with (arg, "metadata-only")) {
2910 opts->metadata_only = TRUE;
2911 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
2912 opts->bind_to_runtime_version = TRUE;
2913 } else if (str_begins_with (arg, "full")) {
2914 opts->full_aot = TRUE;
2915 } else if (str_begins_with (arg, "threads=")) {
2916 opts->nthreads = atoi (arg + strlen ("threads="));
2917 } else if (str_begins_with (arg, "static")) {
2918 opts->static_link = TRUE;
2919 opts->no_dlsym = TRUE;
2920 } else if (str_begins_with (arg, "asmonly")) {
2921 opts->asm_only = TRUE;
2922 } else if (str_begins_with (arg, "asmwriter")) {
2923 opts->asm_writer = TRUE;
2924 } else if (str_begins_with (arg, "nodebug")) {
2925 opts->nodebug = TRUE;
2926 } else if (str_begins_with (arg, "ntrampolines=")) {
2927 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
2929 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
2938 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
2940 MonoMethod *method = (MonoMethod*)key;
2941 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
2942 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
2943 MonoAotCompile *acfg = user_data;
2945 new_ji->image = ji->image;
2946 new_ji->token = ji->token;
2947 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
2951 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
2953 if (klass->type_token)
2955 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2958 return can_encode_class (acfg, klass->element_class);
2963 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2965 switch (patch_info->type) {
2966 case MONO_PATCH_INFO_METHOD:
2967 case MONO_PATCH_INFO_METHODCONST: {
2968 MonoMethod *method = patch_info->data.method;
2970 if (method->wrapper_type) {
2971 switch (method->wrapper_type) {
2972 case MONO_WRAPPER_NONE:
2973 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2974 case MONO_WRAPPER_XDOMAIN_INVOKE:
2975 case MONO_WRAPPER_STFLD:
2976 case MONO_WRAPPER_LDFLD:
2977 case MONO_WRAPPER_LDFLDA:
2978 case MONO_WRAPPER_LDFLD_REMOTE:
2979 case MONO_WRAPPER_STFLD_REMOTE:
2980 case MONO_WRAPPER_STELEMREF:
2981 case MONO_WRAPPER_ISINST:
2982 case MONO_WRAPPER_PROXY_ISINST:
2983 case MONO_WRAPPER_ALLOC:
2984 case MONO_WRAPPER_REMOTING_INVOKE:
2985 case MONO_WRAPPER_UNKNOWN:
2988 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
2992 if (!method->token) {
2993 /* The method is part of a constructed type like Int[,].Set (). */
2994 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
2995 if (method->klass->rank)
3003 case MONO_PATCH_INFO_VTABLE:
3004 case MONO_PATCH_INFO_CLASS_INIT:
3005 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3006 case MONO_PATCH_INFO_CLASS:
3007 case MONO_PATCH_INFO_IID:
3008 case MONO_PATCH_INFO_ADJUSTED_IID:
3009 if (!can_encode_class (acfg, patch_info->data.klass)) {
3010 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
3014 case MONO_PATCH_INFO_RGCTX_FETCH: {
3015 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3017 if (!can_encode_patch (acfg, entry->data))
3029 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
3034 * AOT compile a given method.
3035 * This function might be called by multiple threads, so it must be thread-safe.
3038 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3041 MonoJumpInfo *patch_info;
3044 MonoMethod *wrapped;
3046 if (acfg->aot_opts.metadata_only)
3049 mono_acfg_lock (acfg);
3050 index = get_method_index (acfg, method);
3051 mono_acfg_unlock (acfg);
3053 /* fixme: maybe we can also precompile wrapper methods */
3054 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3055 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3056 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3057 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3061 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3064 wrapped = mono_marshal_method_from_wrapper (method);
3065 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
3066 // FIXME: The wrapper should be generic too, but it is not
3069 InterlockedIncrement (&acfg->stats.mcount);
3072 if (method->is_generic || method->klass->generic_container) {
3073 InterlockedIncrement (&acfg->stats.genericcount);
3078 //acfg->aot_opts.print_skipped_methods = TRUE;
3081 * Since these methods are the only ones which are compiled with
3082 * AOT support, and they are not used by runtime startup/shutdown code,
3083 * the runtime will not see AOT methods during AOT compilation,so it
3084 * does not need to support them by creating a fake GOT etc.
3086 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3087 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3088 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3089 InterlockedIncrement (&acfg->stats.genericcount);
3092 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3093 /* Let the exception happen at runtime */
3097 if (cfg->disable_aot) {
3098 if (acfg->aot_opts.print_skipped_methods)
3099 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
3100 InterlockedIncrement (&acfg->stats.ocount);
3101 mono_destroy_compile (cfg);
3105 /* Nullify patches which need no aot processing */
3106 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3107 switch (patch_info->type) {
3108 case MONO_PATCH_INFO_LABEL:
3109 case MONO_PATCH_INFO_BB:
3110 patch_info->type = MONO_PATCH_INFO_NONE;
3117 /* Collect method->token associations from the cfg */
3118 mono_acfg_lock (acfg);
3119 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3120 mono_acfg_unlock (acfg);
3123 * Check for absolute addresses.
3126 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3127 switch (patch_info->type) {
3128 case MONO_PATCH_INFO_ABS:
3129 /* unable to handle this */
3138 if (acfg->aot_opts.print_skipped_methods)
3139 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
3140 InterlockedIncrement (&acfg->stats.abscount);
3141 mono_destroy_compile (cfg);
3145 /* Lock for the rest of the code */
3146 mono_acfg_lock (acfg);
3149 * Check for methods/klasses we can't encode.
3152 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3153 if (!can_encode_patch (acfg, patch_info))
3158 if (acfg->aot_opts.print_skipped_methods)
3159 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
3160 acfg->stats.ocount++;
3161 mono_destroy_compile (cfg);
3162 mono_acfg_unlock (acfg);
3166 /* Adds generic instances referenced by this method */
3167 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3168 switch (patch_info->type) {
3169 case MONO_PATCH_INFO_METHOD: {
3170 MonoMethod *m = patch_info->data.method;
3171 if (m->is_inflated) {
3172 if (!(mono_class_generic_sharing_enabled (m->klass) &&
3173 mono_method_is_generic_sharable_impl (m, FALSE)) &&
3174 !method_has_type_vars (m)) {
3175 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
3176 if (acfg->aot_opts.full_aot)
3177 add_extra_method (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE));
3179 add_extra_method (acfg, m);
3182 add_generic_class (acfg, m->klass);
3191 /* Determine whenever the method has GOT slots */
3192 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3193 switch (patch_info->type) {
3194 case MONO_PATCH_INFO_GOT_OFFSET:
3195 case MONO_PATCH_INFO_NONE:
3197 case MONO_PATCH_INFO_IMAGE:
3198 /* The assembly is stored in GOT slot 0 */
3199 if (patch_info->data.image != acfg->image)
3200 cfg->has_got_slots = TRUE;
3203 if (!is_plt_patch (patch_info))
3204 cfg->has_got_slots = TRUE;
3209 if (!cfg->has_got_slots)
3210 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
3212 /* Make a copy of the patch info which is in the mempool */
3214 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3216 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3217 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3220 patches = new_patch_info;
3222 patches_end->next = new_patch_info;
3223 patches_end = new_patch_info;
3225 cfg->patch_info = patches;
3227 /* Make a copy of the unwind info */
3229 GSList *l, *unwind_ops;
3233 for (l = cfg->unwind_ops; l; l = l->next) {
3234 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
3235 memcpy (op, l->data, sizeof (MonoUnwindOp));
3236 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
3238 cfg->unwind_ops = g_slist_reverse (unwind_ops);
3240 /* Make a copy of the argument/local info */
3242 MonoInst **args, **locals;
3243 MonoMethodSignature *sig;
3244 MonoMethodHeader *header;
3247 sig = mono_method_signature (method);
3248 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
3249 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
3250 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3251 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
3255 header = mono_method_get_header (method);
3256 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
3257 for (i = 0; i < header->num_locals; ++i) {
3258 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3259 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
3261 cfg->locals = locals;
3264 /* Free some fields used by cfg to conserve memory */
3265 mono_mempool_destroy (cfg->mempool);
3266 cfg->mempool = NULL;
3267 g_free (cfg->varinfo);
3268 cfg->varinfo = NULL;
3272 mono_regstate_free (cfg->rs);
3276 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
3278 while (index >= acfg->cfgs_size) {
3279 MonoCompile **new_cfgs;
3282 new_size = acfg->cfgs_size * 2;
3283 new_cfgs = g_new0 (MonoCompile*, new_size);
3284 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
3285 g_free (acfg->cfgs);
3286 acfg->cfgs = new_cfgs;
3287 acfg->cfgs_size = new_size;
3289 acfg->cfgs [index] = cfg;
3291 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
3294 if (cfg->orig_method->wrapper_type)
3295 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
3298 mono_acfg_unlock (acfg);
3300 InterlockedIncrement (&acfg->stats.ccount);
3304 compile_thread_main (gpointer *user_data)
3306 MonoDomain *domain = user_data [0];
3307 MonoAotCompile *acfg = user_data [1];
3308 GPtrArray *methods = user_data [2];
3311 mono_thread_attach (domain);
3313 for (i = 0; i < methods->len; ++i)
3314 compile_method (acfg, g_ptr_array_index (methods, i));
3318 load_profile_files (MonoAotCompile *acfg)
3322 int file_index, res, method_index, i;
3329 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%s-%d", g_get_home_dir (), acfg->image->assembly_name, acfg->image->guid, file_index);
3331 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
3336 infile = fopen (tmp, "r");
3339 printf ("Using profile data file '%s'\n", tmp);
3344 res = fscanf (infile, "%32s\n", ver);
3345 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3346 printf ("Profile file has wrong version or invalid.\n");
3352 res = fscanf (infile, "%d\n", &token);
3356 method_index = mono_metadata_token_index (token) - 1;
3358 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3359 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3364 /* Add missing methods */
3366 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3367 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3368 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
3370 unordered = g_list_reverse (unordered);
3371 if (acfg->method_order)
3372 g_list_last (acfg->method_order)->next = unordered;
3374 acfg->method_order = unordered;
3378 emit_code (MonoAotCompile *acfg)
3384 sprintf (symbol, "methods");
3385 emit_section_change (acfg, ".text", 0);
3386 emit_global (acfg, symbol, TRUE);
3387 emit_alignment (acfg, 8);
3388 emit_label (acfg, symbol);
3391 * Emit some padding so the local symbol for the first method doesn't have the
3392 * same address as 'methods'.
3394 emit_zero_bytes (acfg, 16);
3396 for (l = acfg->method_order; l != NULL; l = l->next) {
3397 i = GPOINTER_TO_UINT (l->data);
3400 emit_method_code (acfg, acfg->cfgs [i]);
3403 sprintf (symbol, "methods_end");
3404 emit_section_change (acfg, ".text", 0);
3405 emit_global (acfg, symbol, FALSE);
3406 emit_alignment (acfg, 8);
3407 emit_label (acfg, symbol);
3409 sprintf (symbol, "method_offsets");
3410 emit_section_change (acfg, ".text", 1);
3411 emit_global (acfg, symbol, FALSE);
3412 emit_alignment (acfg, 8);
3413 emit_label (acfg, symbol);
3415 for (i = 0; i < acfg->nmethods; ++i) {
3416 if (acfg->cfgs [i]) {
3417 sprintf (symbol, ".Lm_%x", i);
3418 emit_symbol_diff (acfg, symbol, "methods", 0);
3420 emit_int32 (acfg, 0xffffffff);
3427 emit_info (MonoAotCompile *acfg)
3433 /* Emit method info */
3434 sprintf (symbol, "method_info");
3435 emit_section_change (acfg, ".text", 1);
3436 emit_global (acfg, symbol, FALSE);
3437 emit_alignment (acfg, 8);
3438 emit_label (acfg, symbol);
3440 /* To reduce size of generated assembly code */
3441 sprintf (symbol, "mi");
3442 emit_label (acfg, symbol);
3444 for (l = acfg->method_order; l != NULL; l = l->next) {
3445 i = GPOINTER_TO_UINT (l->data);
3448 emit_method_info (acfg, acfg->cfgs [i]);
3451 sprintf (symbol, "method_info_offsets");
3452 emit_section_change (acfg, ".text", 1);
3453 emit_global (acfg, symbol, FALSE);
3454 emit_alignment (acfg, 8);
3455 emit_label (acfg, symbol);
3457 for (i = 0; i < acfg->nmethods; ++i) {
3458 if (acfg->cfgs [i]) {
3459 sprintf (symbol, ".Lm_%x_p", i);
3460 emit_symbol_diff (acfg, symbol, "mi", 0);
3462 emit_int32 (acfg, 0);
3468 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
3471 * mono_aot_str_hash:
3473 * Hash function for strings which we use to hash strings for things which are
3474 * saved in the AOT image, since g_str_hash () can change.
3477 mono_aot_str_hash (gconstpointer v1)
3479 /* Same as g_str_hash () in glib */
3480 char *p = (char *) v1;
3485 hash = (hash << 5) - hash + *p;
3491 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
3492 #define mix(a,b,c) { \
3493 a -= c; a ^= rot(c, 4); c += b; \
3494 b -= a; b ^= rot(a, 6); a += c; \
3495 c -= b; c ^= rot(b, 8); b += a; \
3496 a -= c; a ^= rot(c,16); c += b; \
3497 b -= a; b ^= rot(a,19); a += c; \
3498 c -= b; c ^= rot(b, 4); b += a; \
3500 #define final(a,b,c) { \
3501 c ^= b; c -= rot(b,14); \
3502 a ^= c; a -= rot(c,11); \
3503 b ^= a; b -= rot(a,25); \
3504 c ^= b; c -= rot(b,16); \
3505 a ^= c; a -= rot(c,4); \
3506 b ^= a; b -= rot(a,14); \
3507 c ^= b; c -= rot(b,24); \
3511 mono_aot_type_hash (MonoType *t1)
3513 guint hash = t1->type;
3515 hash |= t1->byref << 6; /* do not collide with t1->type values */
3517 case MONO_TYPE_VALUETYPE:
3518 case MONO_TYPE_CLASS:
3519 case MONO_TYPE_SZARRAY:
3520 /* check if the distribution is good enough */
3521 return ((hash << 5) - hash) ^ mono_aot_str_hash (t1->data.klass->name);
3523 return ((hash << 5) - hash) ^ mono_aot_type_hash (t1->data.type);
3524 case MONO_TYPE_ARRAY:
3525 return ((hash << 5) - hash) ^ mono_aot_type_hash (&t1->data.array->eklass->byval_arg);
3526 case MONO_TYPE_GENERICINST:
3527 return ((hash << 5) - hash) ^ 0;
3533 * mono_aot_method_hash:
3535 * Return a hash code for methods which only depends on metadata.
3538 mono_aot_method_hash (MonoMethod *method)
3540 MonoMethodSignature *sig;
3544 guint32 *hashes_start, *hashes;
3547 /* Similar to the hash in mono_method_get_imt_slot () */
3549 sig = mono_method_signature (method);
3551 hashes_count = sig->param_count + 5;
3552 hashes_start = malloc (hashes_count * sizeof (guint32));
3553 hashes = hashes_start;
3555 /* Some wrappers are assigned to random classes */
3556 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
3557 klass = method->klass;
3559 klass = mono_defaults.object_class;
3561 if (!method->wrapper_type) {
3562 char *full_name = mono_type_full_name (&klass->byval_arg);
3564 hashes [0] = mono_aot_str_hash (full_name);
3568 hashes [0] = mono_aot_str_hash (klass->name);
3569 hashes [1] = mono_aot_str_hash (klass->name_space);
3571 hashes [2] = mono_aot_str_hash (method->name);
3572 hashes [3] = method->wrapper_type;
3573 hashes [4] = mono_aot_type_hash (sig->ret);
3574 for (i = 0; i < sig->param_count; i++) {
3575 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
3578 /* Setup internal state */
3579 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
3581 /* Handle most of the hashes */
3582 while (hashes_count > 3) {
3591 /* Handle the last 3 hashes (all the case statements fall through) */
3592 switch (hashes_count) {
3593 case 3 : c += hashes [2];
3594 case 2 : b += hashes [1];
3595 case 1 : a += hashes [0];
3597 case 0: /* nothing left to add */
3601 free (hashes_start);
3610 * mono_aot_wrapper_name:
3612 * Return a string which uniqely identifies the given wrapper method.
3615 mono_aot_wrapper_name (MonoMethod *method)
3617 char *name, *tmpsig, *klass_desc;
3619 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3621 switch (method->wrapper_type) {
3622 case MONO_WRAPPER_RUNTIME_INVOKE:
3623 case MONO_WRAPPER_DELEGATE_INVOKE:
3624 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3625 case MONO_WRAPPER_DELEGATE_END_INVOKE:
3626 /* This is a hack to work around the fact that runtime invoke wrappers get assigned to some random class */
3627 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
3630 klass_desc = mono_type_full_name (&method->klass->byval_arg);
3632 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
3642 * mono_aot_tramp_info_create:
3644 * Create a MonoAotTrampInfo structure from the arguments.
3647 mono_aot_tramp_info_create (const char *name, guint8 *code, guint32 code_size)
3649 MonoAotTrampInfo *info = g_new0 (MonoAotTrampInfo, 1);
3651 info->name = (char*)name;
3653 info->code_size = code_size;
3658 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
3660 typedef struct HashEntry {
3661 guint32 key, value, index;
3662 struct HashEntry *next;
3666 * emit_extra_methods:
3668 * Emit methods which are not in the METHOD table, like wrappers.
3671 emit_extra_methods (MonoAotCompile *acfg)
3673 int i, table_size, buf_size;
3676 guint32 *info_offsets;
3679 HashEntry *entry, *new_entry;
3680 int nmethods, max_chain_length;
3683 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
3685 buf_size = acfg->extra_methods->len * 256 + 256;
3686 p = buf = g_malloc (buf_size);
3688 /* Encode method info */
3690 /* So offsets are > 0 */
3693 for (i = 0; i < acfg->extra_methods->len; ++i) {
3694 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3695 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3702 info_offsets [i] = p - buf;
3705 if (method->wrapper_type) {
3707 * We encode some wrappers using their name, since encoding them
3708 * directly would be difficult. This also avoids creating the wrapper
3709 * methods at runtime, since they are not needed anyway.
3711 switch (method->wrapper_type) {
3712 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3713 case MONO_WRAPPER_SYNCHRONIZED:
3714 /* encode_method_ref () can handle these */
3716 case MONO_WRAPPER_RUNTIME_INVOKE:
3717 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
3718 /* Direct wrapper, encode normally */
3722 name = mono_aot_wrapper_name (method);
3728 encode_value (1, p, &p);
3729 encode_value (method->wrapper_type, p, &p);
3730 strcpy ((char*)p, name);
3731 p += strlen (name ) + 1;
3734 encode_value (0, p, &p);
3735 encode_method_ref (acfg, method, p, &p);
3738 g_assert ((p - buf) < buf_size);
3741 g_assert ((p - buf) < buf_size);
3743 /* Emit method info */
3744 sprintf (symbol, "extra_method_info");
3745 emit_section_change (acfg, ".text", 1);
3746 emit_global (acfg, symbol, FALSE);
3747 emit_alignment (acfg, 8);
3748 emit_label (acfg, symbol);
3750 emit_bytes (acfg, buf, p - buf);
3755 * Construct a chained hash table for mapping indexes in extra_method_info to
3758 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
3759 table = g_ptr_array_sized_new (table_size);
3760 for (i = 0; i < table_size; ++i)
3761 g_ptr_array_add (table, NULL);
3762 chain_lengths = g_new0 (int, table_size);
3763 max_chain_length = 0;
3764 for (i = 0; i < acfg->extra_methods->len; ++i) {
3765 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3766 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3772 key = info_offsets [i];
3773 value = get_method_index (acfg, method);
3775 hash = mono_aot_method_hash (method) % table_size;
3777 chain_lengths [hash] ++;
3778 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
3780 /* FIXME: Allocate from the mempool */
3781 new_entry = g_new0 (HashEntry, 1);
3782 new_entry->key = key;
3783 new_entry->value = value;
3785 entry = g_ptr_array_index (table, hash);
3786 if (entry == NULL) {
3787 new_entry->index = hash;
3788 g_ptr_array_index (table, hash) = new_entry;
3791 entry = entry->next;
3793 entry->next = new_entry;
3794 new_entry->index = table->len;
3795 g_ptr_array_add (table, new_entry);
3799 //printf ("MAX: %d\n", max_chain_length);
3801 /* Emit the table */
3802 sprintf (symbol, "extra_method_table");
3803 emit_section_change (acfg, ".text", 0);
3804 emit_global (acfg, symbol, FALSE);
3805 emit_alignment (acfg, 8);
3806 emit_label (acfg, symbol);
3808 g_assert (table_size < 65000);
3809 emit_int32 (acfg, table_size);
3810 g_assert (table->len < 65000);
3811 for (i = 0; i < table->len; ++i) {
3812 HashEntry *entry = g_ptr_array_index (table, i);
3814 if (entry == NULL) {
3815 emit_int32 (acfg, 0);
3816 emit_int32 (acfg, 0);
3817 emit_int32 (acfg, 0);
3819 g_assert (entry->key > 0);
3820 emit_int32 (acfg, entry->key);
3821 emit_int32 (acfg, entry->value);
3823 emit_int32 (acfg, entry->next->index);
3825 emit_int32 (acfg, 0);
3830 * Emit a table reverse mapping method indexes to their index in extra_method_info.
3831 * This is used by mono_aot_find_jit_info ().
3833 sprintf (symbol, "extra_method_info_offsets");
3834 emit_section_change (acfg, ".text", 0);
3835 emit_global (acfg, symbol, FALSE);
3836 emit_alignment (acfg, 8);
3837 emit_label (acfg, symbol);
3839 emit_int32 (acfg, acfg->extra_methods->len);
3840 for (i = 0; i < acfg->extra_methods->len; ++i) {
3841 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3843 emit_int32 (acfg, get_method_index (acfg, method));
3844 emit_int32 (acfg, info_offsets [i]);
3849 emit_method_order (MonoAotCompile *acfg)
3855 sprintf (symbol, "method_order");
3856 emit_section_change (acfg, ".text", 1);
3857 emit_global (acfg, symbol, FALSE);
3858 emit_alignment (acfg, 8);
3859 emit_label (acfg, symbol);
3861 /* First emit an index table */
3864 for (l = acfg->method_order; l != NULL; l = l->next) {
3865 i = GPOINTER_TO_UINT (l->data);
3867 if (acfg->cfgs [i]) {
3868 if ((index % 1024) == 0) {
3869 emit_int32 (acfg, i);
3877 emit_int32 (acfg, 0xffffff);
3879 /* Then emit the whole method order */
3880 for (l = acfg->method_order; l != NULL; l = l->next) {
3881 i = GPOINTER_TO_UINT (l->data);
3883 if (acfg->cfgs [i]) {
3884 emit_int32 (acfg, i);
3889 sprintf (symbol, "method_order_end");
3890 emit_section_change (acfg, ".text", 1);
3891 emit_global (acfg, symbol, FALSE);
3892 emit_label (acfg, symbol);
3896 emit_exception_info (MonoAotCompile *acfg)
3901 sprintf (symbol, "ex_info");
3902 emit_section_change (acfg, ".text", 1);
3903 emit_global (acfg, symbol, FALSE);
3904 emit_alignment (acfg, 8);
3905 emit_label (acfg, symbol);
3907 /* To reduce size of generated assembly */
3908 sprintf (symbol, "ex");
3909 emit_label (acfg, symbol);
3911 for (i = 0; i < acfg->nmethods; ++i) {
3913 emit_exception_debug_info (acfg, acfg->cfgs [i]);
3916 sprintf (symbol, "ex_info_offsets");
3917 emit_section_change (acfg, ".text", 1);
3918 emit_global (acfg, symbol, FALSE);
3919 emit_alignment (acfg, 8);
3920 emit_label (acfg, symbol);
3922 for (i = 0; i < acfg->nmethods; ++i) {
3923 if (acfg->cfgs [i]) {
3924 sprintf (symbol, ".Le_%x_p", i);
3925 emit_symbol_diff (acfg, symbol, "ex", 0);
3927 emit_int32 (acfg, 0);
3934 emit_unwind_info (MonoAotCompile *acfg)
3940 * The unwind info contains a lot of duplicates so we emit each unique
3941 * entry once, and only store the offset from the start of the table in the
3945 sprintf (symbol, "unwind_info");
3946 emit_section_change (acfg, ".text", 1);
3947 emit_alignment (acfg, 8);
3948 emit_label (acfg, symbol);
3949 emit_global (acfg, symbol, FALSE);
3951 for (i = 0; i < acfg->unwind_ops->len; ++i) {
3952 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
3953 guint8 *unwind_info;
3954 guint32 unwind_info_len;
3958 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
3961 encode_value (unwind_info_len, p, &p);
3962 emit_bytes (acfg, buf, p - buf);
3963 emit_bytes (acfg, unwind_info, unwind_info_len);
3965 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
3970 emit_class_info (MonoAotCompile *acfg)
3975 sprintf (symbol, "class_info");
3976 emit_section_change (acfg, ".text", 1);
3977 emit_global (acfg, symbol, FALSE);
3978 emit_alignment (acfg, 8);
3979 emit_label (acfg, symbol);
3981 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
3982 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
3984 sprintf (symbol, "class_info_offsets");
3985 emit_section_change (acfg, ".text", 1);
3986 emit_global (acfg, symbol, FALSE);
3987 emit_alignment (acfg, 8);
3988 emit_label (acfg, symbol);
3990 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3991 sprintf (symbol, ".LK_I_%x", i);
3992 emit_symbol_diff (acfg, symbol, "class_info", 0);
3997 typedef struct ClassNameTableEntry {
3998 guint32 token, index;
3999 struct ClassNameTableEntry *next;
4000 } ClassNameTableEntry;
4003 emit_class_name_table (MonoAotCompile *acfg)
4006 guint32 token, hash;
4011 ClassNameTableEntry *entry, *new_entry;
4014 * Construct a chained hash table for mapping class names to typedef tokens.
4016 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4017 table = g_ptr_array_sized_new (table_size);
4018 for (i = 0; i < table_size; ++i)
4019 g_ptr_array_add (table, NULL);
4020 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4021 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4022 klass = mono_class_get (acfg->image, token);
4023 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4024 hash = mono_aot_str_hash (full_name) % table_size;
4027 /* FIXME: Allocate from the mempool */
4028 new_entry = g_new0 (ClassNameTableEntry, 1);
4029 new_entry->token = token;
4031 entry = g_ptr_array_index (table, hash);
4032 if (entry == NULL) {
4033 new_entry->index = hash;
4034 g_ptr_array_index (table, hash) = new_entry;
4037 entry = entry->next;
4039 entry->next = new_entry;
4040 new_entry->index = table->len;
4041 g_ptr_array_add (table, new_entry);
4045 /* Emit the table */
4046 sprintf (symbol, "class_name_table");
4047 emit_section_change (acfg, ".text", 0);
4048 emit_global (acfg, symbol, FALSE);
4049 emit_alignment (acfg, 8);
4050 emit_label (acfg, symbol);
4052 /* FIXME: Optimize memory usage */
4053 g_assert (table_size < 65000);
4054 emit_int16 (acfg, table_size);
4055 g_assert (table->len < 65000);
4056 for (i = 0; i < table->len; ++i) {
4057 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4059 if (entry == NULL) {
4060 emit_int16 (acfg, 0);
4061 emit_int16 (acfg, 0);
4063 emit_int16 (acfg, mono_metadata_token_index (entry->token));
4065 emit_int16 (acfg, entry->next->index);
4067 emit_int16 (acfg, 0);
4073 emit_image_table (MonoAotCompile *acfg)
4079 * The image table is small but referenced in a lot of places.
4080 * So we emit it at once, and reference its elements by an index.
4083 sprintf (symbol, "mono_image_table");
4084 emit_section_change (acfg, ".text", 1);
4085 emit_global (acfg, symbol, FALSE);
4086 emit_alignment (acfg, 8);
4087 emit_label (acfg, symbol);
4089 emit_int32 (acfg, acfg->image_table->len);
4090 for (i = 0; i < acfg->image_table->len; i++) {
4091 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4092 MonoAssemblyName *aname = &image->assembly->aname;
4094 /* FIXME: Support multi-module assemblies */
4095 g_assert (image->assembly->image == image);
4097 emit_string (acfg, image->assembly_name);
4098 emit_string (acfg, image->guid);
4099 emit_string (acfg, aname->culture ? aname->culture : "");
4100 emit_string (acfg, (const char*)aname->public_key_token);
4102 emit_alignment (acfg, 8);
4103 emit_int32 (acfg, aname->flags);
4104 emit_int32 (acfg, aname->major);
4105 emit_int32 (acfg, aname->minor);
4106 emit_int32 (acfg, aname->build);
4107 emit_int32 (acfg, aname->revision);
4112 emit_got_info (MonoAotCompile *acfg)
4115 int i, first_plt_got_patch, buf_size;
4117 guint32 *got_info_offsets;
4119 /* Add the patches needed by the PLT to the GOT */
4120 acfg->plt_got_offset_base = acfg->got_offset;
4121 first_plt_got_patch = acfg->got_patches->len;
4122 for (i = 1; i < acfg->plt_offset; ++i) {
4123 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
4125 g_ptr_array_add (acfg->got_patches, patch_info);
4128 acfg->got_offset += acfg->plt_offset;
4132 * - optimize offsets table.
4133 * - reduce number of exported symbols.
4134 * - emit info for a klass only once.
4135 * - determine when a method uses a GOT slot which is guaranteed to be already
4137 * - clean up and document the code.
4138 * - use String.Empty in class libs.
4141 /* Encode info required to decode shared GOT entries */
4142 buf_size = acfg->got_patches->len * 64;
4143 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
4144 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
4145 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
4146 for (i = 0; i < acfg->got_patches->len; ++i) {
4147 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
4149 got_info_offsets [i] = p - buf;
4150 if (i >= first_plt_got_patch)
4151 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
4152 encode_value (ji->type, p, &p);
4153 encode_patch (acfg, ji, p, &p);
4156 g_assert (p - buf <= buf_size);
4158 acfg->stats.got_info_size = p - buf;
4160 /* Emit got_info table */
4161 sprintf (symbol, "got_info");
4162 emit_section_change (acfg, ".text", 1);
4163 emit_global (acfg, symbol, FALSE);
4164 emit_alignment (acfg, 8);
4165 emit_label (acfg, symbol);
4167 emit_bytes (acfg, buf, p - buf);
4169 /* Emit got_info_offsets table */
4170 sprintf (symbol, "got_info_offsets");
4171 emit_section_change (acfg, ".text", 1);
4172 emit_global (acfg, symbol, FALSE);
4173 emit_alignment (acfg, 8);
4174 emit_label (acfg, symbol);
4176 for (i = 0; i < acfg->got_patches->len; ++i)
4177 emit_int32 (acfg, got_info_offsets [i]);
4179 acfg->stats.got_info_offsets_size = acfg->got_patches->len * 4;
4183 emit_got (MonoAotCompile *acfg)
4187 /* Don't make GOT global so accesses to it don't need relocations */
4188 sprintf (symbol, acfg->got_symbol);
4189 emit_section_change (acfg, ".bss", 0);
4190 emit_alignment (acfg, 8);
4191 emit_local_symbol (acfg, symbol, "got_end", FALSE);
4192 emit_label (acfg, symbol);
4193 if (acfg->got_offset > 0)
4194 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4196 sprintf (symbol, "got_end");
4197 emit_label (acfg, symbol);
4199 sprintf (symbol, "mono_aot_got_addr");
4200 emit_section_change (acfg, ".data", 0);
4201 emit_global (acfg, symbol, FALSE);
4202 emit_alignment (acfg, 8);
4203 emit_label (acfg, symbol);
4204 emit_pointer (acfg, acfg->got_symbol);
4208 emit_globals (MonoAotCompile *acfg)
4213 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
4215 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
4217 opts_str = g_strdup_printf ("%d", acfg->opts);
4218 emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
4221 emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
4223 if (acfg->aot_opts.bind_to_runtime_version) {
4224 build_info = mono_get_runtime_build_info ();
4225 emit_string_symbol (acfg, "mono_runtime_version", build_info);
4226 g_free (build_info);
4228 emit_string_symbol (acfg, "mono_runtime_version", "");
4232 * When static linking, we emit a global which will point to the symbol table.
4234 if (acfg->aot_opts.static_link) {
4239 /* Emit a string holding the assembly name */
4240 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
4242 /* Emit the names */
4243 for (i = 0; i < acfg->globals->len; ++i) {
4244 char *name = g_ptr_array_index (acfg->globals, i);
4246 sprintf (symbol, "name_%d", i);
4247 emit_section_change (acfg, ".text", 1);
4248 emit_label (acfg, symbol);
4249 emit_string (acfg, name);
4252 /* Emit the globals table */
4253 sprintf (symbol, "globals");
4254 emit_section_change (acfg, ".data", 0);
4255 /* This is not a global, since it is accessed by the init function */
4256 emit_alignment (acfg, 8);
4257 emit_label (acfg, symbol);
4259 for (i = 0; i < acfg->globals->len; ++i) {
4260 char *name = g_ptr_array_index (acfg->globals, i);
4262 sprintf (symbol, "name_%d", i);
4263 emit_pointer (acfg, symbol);
4265 sprintf (symbol, "%s", name);
4266 emit_pointer (acfg, symbol);
4268 /* Null terminate the table */
4269 emit_int32 (acfg, 0);
4270 emit_int32 (acfg, 0);
4273 * Emit a global symbol which can be passed by an embedding app to
4274 * mono_aot_register_module ().
4276 #if defined(__MACH__)
4277 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4279 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4282 /* Get rid of characters which cannot occur in symbols */
4284 for (p = symbol; *p; ++p) {
4285 if (!(isalnum (*p) || *p == '_'))
4288 acfg->static_linking_symbol = g_strdup (symbol);
4289 emit_global_inner (acfg, symbol, FALSE);
4290 emit_alignment (acfg, 8);
4291 emit_label (acfg, symbol);
4292 emit_pointer (acfg, "globals");
4297 emit_mem_end (MonoAotCompile *acfg)
4301 sprintf (symbol, "mem_end");
4302 emit_section_change (acfg, ".text", 1);
4303 emit_global (acfg, symbol, FALSE);
4304 emit_alignment (acfg, 8);
4305 emit_label (acfg, symbol);
4309 * Emit a structure containing all the information not stored elsewhere.
4312 emit_file_info (MonoAotCompile *acfg)
4317 sprintf (symbol, "mono_aot_file_info");
4318 emit_section_change (acfg, ".data", 0);
4319 emit_alignment (acfg, 8);
4320 emit_label (acfg, symbol);
4321 emit_global (acfg, symbol, FALSE);
4323 /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
4324 emit_int32 (acfg, acfg->plt_got_offset_base);
4325 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4326 emit_int32 (acfg, acfg->plt_offset);
4328 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4329 emit_int32 (acfg, acfg->num_trampolines [i]);
4330 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4331 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
4332 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4333 emit_int32 (acfg, acfg->trampoline_size [i]);
4337 emit_dwarf_info (MonoAotCompile *acfg)
4339 #ifdef EMIT_DWARF_INFO
4341 char symbol [128], symbol2 [128];
4343 /* DIEs for methods */
4344 for (i = 0; i < acfg->nmethods; ++i) {
4345 MonoCompile *cfg = acfg->cfgs [i];
4350 sprintf (symbol, ".Lm_%x", i);
4351 sprintf (symbol2, ".Lme_%x", i);
4353 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, symbol, symbol2, NULL, 0, cfg->args, cfg->locals, cfg->unwind_ops, NULL);
4359 collect_methods (MonoAotCompile *acfg)
4362 MonoImage *image = acfg->image;
4364 /* Collect methods */
4365 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
4367 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4369 method = mono_get_method (acfg->image, token, NULL);
4372 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
4376 /* Load all methods eagerly to skip the slower lazy loading code */
4377 mono_class_setup_methods (method->klass);
4379 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4380 /* Compile the wrapper instead */
4381 /* We do this here instead of add_wrappers () because it is easy to do it here */
4382 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
4386 /* Since we add the normal methods first, their index will be equal to their zero based token index */
4387 add_method_with_index (acfg, method, i, FALSE);
4388 acfg->method_index ++;
4391 add_generic_instances (acfg);
4393 if (acfg->aot_opts.full_aot)
4394 add_wrappers (acfg);
4398 compile_methods (MonoAotCompile *acfg)
4402 if (acfg->aot_opts.nthreads > 0) {
4407 gpointer *user_data;
4408 MonoMethod **methods;
4410 methods_len = acfg->methods->len;
4412 len = acfg->methods->len / acfg->aot_opts.nthreads;
4415 * Partition the list of methods into fragments, and hand it to threads to
4418 threads = g_ptr_array_new ();
4419 /* Make a copy since acfg->methods is modified by compile_method () */
4420 methods = g_new0 (MonoMethod*, methods_len);
4421 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
4422 for (i = 0; i < methods_len; ++i)
4423 methods [i] = g_ptr_array_index (acfg->methods, i);
4425 while (i < methods_len) {
4426 frag = g_ptr_array_new ();
4427 for (j = 0; j < len; ++j) {
4428 if (i < methods_len) {
4429 g_ptr_array_add (frag, methods [i]);
4434 user_data = g_new0 (gpointer, 3);
4435 user_data [0] = mono_domain_get ();
4436 user_data [1] = acfg;
4437 user_data [2] = frag;
4439 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
4440 g_ptr_array_add (threads, handle);
4444 for (i = 0; i < threads->len; ++i) {
4445 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
4451 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
4452 for (i = methods_len; i < acfg->methods->len; ++i) {
4453 /* This can new methods to acfg->methods */
4454 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
4459 compile_asm (MonoAotCompile *acfg)
4461 char *command, *objfile;
4462 char *outfile_name, *tmp_outfile_name;
4464 #if defined(TARGET_AMD64)
4465 #define AS_OPTIONS "--64"
4466 #elif defined(sparc) && SIZEOF_VOID_P == 8
4467 #define AS_OPTIONS "-xarch=v9"
4469 #define AS_OPTIONS ""
4472 if (acfg->aot_opts.asm_only) {
4473 printf ("Output file: '%s'.\n", acfg->tmpfname);
4474 if (acfg->aot_opts.static_link)
4475 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
4479 if (acfg->aot_opts.static_link) {
4480 if (acfg->aot_opts.outfile)
4481 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4483 objfile = g_strdup_printf ("%s.o", acfg->image->name);
4485 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
4487 command = g_strdup_printf ("as %s %s -o %s", AS_OPTIONS, acfg->tmpfname, objfile);
4488 printf ("Executing the native assembler: %s\n", command);
4489 if (system (command) != 0) {
4497 if (acfg->aot_opts.static_link) {
4498 printf ("Output file: '%s'.\n", objfile);
4499 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
4504 if (acfg->aot_opts.outfile)
4505 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4507 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
4509 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
4512 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4513 #elif defined(__ppc__) && defined(__MACH__)
4514 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4515 #elif defined(PLATFORM_WIN32)
4516 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4518 command = g_strdup_printf ("ld -shared -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4520 printf ("Executing the native linker: %s\n", command);
4521 if (system (command) != 0) {
4522 g_free (tmp_outfile_name);
4523 g_free (outfile_name);
4531 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
4532 printf ("Stripping the binary: %s\n", com);
4536 #if defined(TARGET_ARM) && !defined(__MACH__)
4538 * gas generates 'mapping symbols' each time code and data is mixed, which
4539 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
4541 command = g_strdup_printf ("strip --strip-symbol=\\$a --strip-symbol=\\$d %s", tmp_outfile_name);
4542 printf ("Stripping the binary: %s\n", command);
4543 if (system (command) != 0) {
4544 g_free (tmp_outfile_name);
4545 g_free (outfile_name);
4552 rename (tmp_outfile_name, outfile_name);
4554 g_free (tmp_outfile_name);
4555 g_free (outfile_name);
4558 if (acfg->aot_opts.save_temps)
4559 printf ("Retained input file.\n");
4561 unlink (acfg->tmpfname);
4566 static MonoAotCompile*
4567 acfg_create (MonoAssembly *ass, guint32 opts)
4569 MonoImage *image = ass->image;
4570 MonoAotCompile *acfg;
4572 acfg = g_new0 (MonoAotCompile, 1);
4573 acfg->methods = g_ptr_array_new ();
4574 acfg->method_indexes = g_hash_table_new (NULL, NULL);
4575 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
4576 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4577 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4578 acfg->got_patches = g_ptr_array_new ();
4579 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
4580 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
4581 acfg->image_hash = g_hash_table_new (NULL, NULL);
4582 acfg->image_table = g_ptr_array_new ();
4583 acfg->globals = g_ptr_array_new ();
4584 acfg->image = image;
4586 acfg->mempool = mono_mempool_new ();
4587 acfg->extra_methods = g_ptr_array_new ();
4588 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
4589 acfg->unwind_ops = g_ptr_array_new ();
4590 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
4591 InitializeCriticalSection (&acfg->mutex);
4597 acfg_free (MonoAotCompile *acfg)
4601 img_writer_destroy (acfg->w);
4602 for (i = 0; i < acfg->nmethods; ++i)
4604 g_free (acfg->cfgs [i]);
4605 g_free (acfg->cfgs);
4606 g_free (acfg->static_linking_symbol);
4607 g_ptr_array_free (acfg->methods, TRUE);
4608 g_ptr_array_free (acfg->got_patches, TRUE);
4609 g_ptr_array_free (acfg->image_table, TRUE);
4610 g_ptr_array_free (acfg->globals, TRUE);
4611 g_ptr_array_free (acfg->unwind_ops, TRUE);
4612 g_hash_table_destroy (acfg->method_indexes);
4613 g_hash_table_destroy (acfg->plt_offset_to_patch);
4614 g_hash_table_destroy (acfg->patch_to_plt_offset);
4615 g_hash_table_destroy (acfg->patch_to_got_offset);
4616 g_hash_table_destroy (acfg->method_to_cfg);
4617 g_hash_table_destroy (acfg->token_info_hash);
4618 g_hash_table_destroy (acfg->image_hash);
4619 g_hash_table_destroy (acfg->unwind_info_offsets);
4620 g_hash_table_destroy (acfg->method_label_hash);
4621 mono_mempool_destroy (acfg->mempool);
4626 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4628 MonoImage *image = ass->image;
4630 MonoAotCompile *acfg;
4631 char *outfile_name, *tmp_outfile_name, *p;
4635 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
4637 acfg = acfg_create (ass, opts);
4639 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
4640 acfg->aot_opts.write_symbols = TRUE;
4641 acfg->aot_opts.ntrampolines = 10240;
4643 mono_aot_parse_options (aot_options, &acfg->aot_opts);
4645 //acfg->aot_opts.print_skipped_methods = TRUE;
4647 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4648 if (acfg->aot_opts.full_aot) {
4649 printf ("--aot=full is not supported on this platform.\n");
4654 if (acfg->aot_opts.static_link)
4655 acfg->aot_opts.asm_writer = TRUE;
4657 load_profile_files (acfg);
4659 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
4660 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
4661 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? 1024 : 0;
4663 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? 128 : 0;
4665 acfg->got_symbol = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
4667 /* Get rid of characters which cannot occur in symbols */
4668 p = acfg->got_symbol;
4669 for (p = acfg->got_symbol; *p; ++p) {
4670 if (!(isalnum (*p) || *p == '_'))
4674 acfg->method_index = 1;
4676 collect_methods (acfg);
4678 acfg->cfgs_size = acfg->methods->len + 32;
4679 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
4681 /* PLT offset 0 is reserved for the PLT trampoline */
4682 acfg->plt_offset = 1;
4684 /* GOT offset 0 is reserved for the address of the current assembly */
4688 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
4689 ji->type = MONO_PATCH_INFO_IMAGE;
4690 ji->data.image = acfg->image;
4692 get_got_offset (acfg, ji);
4697 compile_methods (acfg);
4701 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
4705 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
4706 if (acfg->aot_opts.outfile)
4707 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4709 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
4712 * Can't use g_file_open_tmp () as it will be deleted at exit, and
4713 * it might be in another file system so the rename () won't work.
4715 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
4717 acfg->fp = fopen (tmp_outfile_name, "w");
4719 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
4723 acfg->w = img_writer_create (acfg->fp, TRUE);
4724 acfg->use_bin_writer = TRUE;
4726 if (acfg->aot_opts.asm_only) {
4727 if (acfg->aot_opts.outfile)
4728 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4730 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
4731 acfg->fp = fopen (acfg->tmpfname, "w+");
4733 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
4734 acfg->fp = fdopen (i, "w+");
4736 g_assert (acfg->fp);
4738 acfg->w = img_writer_create (acfg->fp, FALSE);
4740 tmp_outfile_name = NULL;
4741 outfile_name = NULL;
4744 if (!acfg->aot_opts.nodebug)
4745 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL);
4747 img_writer_emit_start (acfg->w);
4750 mono_dwarf_writer_emit_base_info (acfg->dwarf, arch_get_cie_program ());
4756 emit_extra_methods (acfg);
4758 emit_method_order (acfg);
4760 emit_trampolines (acfg);
4762 emit_class_name_table (acfg);
4764 emit_got_info (acfg);
4766 emit_exception_info (acfg);
4768 emit_unwind_info (acfg);
4770 emit_class_info (acfg);
4774 emit_image_table (acfg);
4778 emit_file_info (acfg);
4780 emit_globals (acfg);
4783 emit_dwarf_info (acfg);
4785 emit_mem_end (acfg);
4789 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
4791 printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT Info Offsets: %d GOT: %d\n", acfg->stats.code_size, acfg->stats.info_size, acfg->stats.ex_info_size, acfg->stats.unwind_info_size, acfg->stats.class_info_size, acfg->plt_offset, acfg->stats.got_info_size, acfg->stats.got_info_offsets_size, (int)(acfg->got_offset * sizeof (gpointer)));
4794 res = img_writer_emit_writeout (acfg->w);
4799 if (acfg->use_bin_writer) {
4800 int err = rename (tmp_outfile_name, outfile_name);
4803 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
4807 res = compile_asm (acfg);
4814 acfg->stats.link_time = TV_ELAPSED (atv, btv);
4816 printf ("Compiled %d out of %d methods (%d%%)\n", acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100);
4817 if (acfg->stats.genericcount)
4818 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
4819 if (acfg->stats.abscount)
4820 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
4821 if (acfg->stats.lmfcount)
4822 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
4823 if (acfg->stats.ocount)
4824 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
4825 printf ("Methods without GOT slots: %d (%d%%)\n", acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100);
4826 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
4829 printf ("GOT slot distribution:\n");
4830 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
4831 if (acfg->stats.got_slot_types [i])
4832 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
4835 printf ("JIT time: %d ms, Generation time: %d ms, Assembly+Link time: %d ms.\n", acfg->stats.jit_time / 1000, acfg->stats.gen_time / 1000, acfg->stats.link_time / 1000);
4843 * Support for emitting debug info for JITted code.
4845 * This works as follows:
4846 * - the runtime writes out an xdb.s file containing DWARF debug info.
4847 * - the user calls a gdb macro
4848 * - the macro compiles and loads this shared library using add-symbol-file.
4850 * This is based on the xdebug functionality in the Kaffe Java VM.
4852 * We emit assembly code instead of using the ELF writer, so we can emit debug info
4853 * incrementally as each method is JITted, and the debugger doesn't have to call
4854 * into the runtime to emit the shared library, which would cause all kinds of
4855 * complications, like threading issues, and the fact that the ELF writer's
4856 * emit_writeout () function cannot be called more than once.
4859 /* The recommended gdb macro is: */
4862 shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
4863 add-symbol-file xdb.so 0
4867 static MonoDwarfWriter *xdebug_writer;
4868 static FILE *xdebug_fp;
4871 mono_xdebug_init (void)
4877 xdebug_fp = fopen ("xdb.s", "w");
4879 w = img_writer_create (xdebug_fp, FALSE);
4881 img_writer_emit_start (w);
4883 /* This file will contain the IL code for methods which don't have debug info */
4884 il_file = fopen ("xdb.il", "w");
4886 xdebug_writer = mono_dwarf_writer_create (w, il_file);
4888 /* Emit something so the file has a text segment */
4889 img_writer_emit_section_change (w, ".text", 0);
4890 img_writer_emit_string (w, "");
4892 mono_dwarf_writer_emit_base_info (xdebug_writer, arch_get_cie_program ());
4896 * mono_save_xdebug_info:
4898 * Emit debugging info for METHOD into an assembly file which can be assembled
4899 * and loaded into gdb to provide debugging info for JITted code.
4900 * LOCKING: Acquires the loader lock.
4903 mono_save_xdebug_info (MonoCompile *cfg)
4908 mono_loader_lock ();
4909 mono_dwarf_writer_emit_method (xdebug_writer, cfg, cfg->jit_info->method, NULL, NULL, cfg->jit_info->code_start, cfg->jit_info->code_size, cfg->args, cfg->locals, cfg->unwind_ops, mono_debug_find_method (cfg->jit_info->method, mono_domain_get ()));
4911 mono_loader_unlock ();
4915 * mono_save_trampoline_xdebug_info:
4917 * Same as mono_save_xdebug_info, but for trampolines.
4918 * LOCKING: Acquires the loader lock.
4921 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
4926 mono_loader_lock ();
4927 mono_dwarf_writer_emit_trampoline (xdebug_writer, tramp_name, NULL, NULL, code, code_size, unwind_info);
4929 mono_loader_unlock ();
4937 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4943 mono_xdebug_init (void)
4948 mono_save_xdebug_info (MonoCompile *cfg)
4953 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)