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_shared_got_offset;
124 GPtrArray *shared_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;
161 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
162 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
164 #ifdef HAVE_ARRAY_ELEM_INIT
165 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
166 #define MSGSTRFIELD1(line) str##line
167 static const struct msgstr_t {
168 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
169 #include "patch-info.h"
172 #define PATCH_INFO(a,b) b,
173 #include "patch-info.h"
176 static const gint16 opidx [] = {
177 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
178 #include "patch-info.h"
182 static G_GNUC_UNUSED const char*
183 get_patch_name (int info)
185 return (const char*)&opstr + opidx [info];
189 #define PATCH_INFO(a,b) b,
190 static const char* const
191 patch_types [MONO_PATCH_INFO_NUM + 1] = {
192 #include "patch-info.h"
197 get_patch_name (int info)
199 return patch_types [info];
204 /* Wrappers around the image writer functions */
207 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
209 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
213 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
215 img_writer_emit_push_section (acfg->w, section_name, subsection);
219 emit_pop_section (MonoAotCompile *acfg)
221 img_writer_emit_pop_section (acfg->w);
225 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
227 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
231 emit_label (MonoAotCompile *acfg, const char *name)
233 img_writer_emit_label (acfg->w, name);
237 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
239 img_writer_emit_bytes (acfg->w, buf, size);
243 emit_string (MonoAotCompile *acfg, const char *value)
245 img_writer_emit_string (acfg->w, value);
249 emit_line (MonoAotCompile *acfg)
251 img_writer_emit_line (acfg->w);
255 emit_alignment (MonoAotCompile *acfg, int size)
257 img_writer_emit_alignment (acfg->w, size);
261 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
263 img_writer_emit_pointer_unaligned (acfg->w, target);
267 emit_pointer (MonoAotCompile *acfg, const char *target)
269 img_writer_emit_pointer (acfg->w, target);
273 emit_int16 (MonoAotCompile *acfg, int value)
275 img_writer_emit_int16 (acfg->w, value);
279 emit_int32 (MonoAotCompile *acfg, int value)
281 img_writer_emit_int32 (acfg->w, value);
285 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
287 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
291 emit_zero_bytes (MonoAotCompile *acfg, int num)
293 img_writer_emit_zero_bytes (acfg->w, num);
297 emit_byte (MonoAotCompile *acfg, guint8 val)
299 img_writer_emit_byte (acfg->w, val);
302 static G_GNUC_UNUSED void
303 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
305 img_writer_emit_global (acfg->w, name, func);
309 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
311 if (acfg->aot_opts.no_dlsym) {
312 g_ptr_array_add (acfg->globals, g_strdup (name));
314 img_writer_emit_global (acfg->w, name, func);
319 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
321 img_writer_emit_section_change (acfg->w, ".text", 1);
322 emit_global (acfg, name, FALSE);
323 img_writer_emit_label (acfg->w, name);
324 img_writer_emit_string (acfg->w, value);
327 static G_GNUC_UNUSED void
328 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
331 guint8 b = value & 0x7f;
333 if (value != 0) /* more bytes to come */
339 static G_GNUC_UNUSED void
340 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
343 gboolean negative = (value < 0);
350 /* the following is unnecessary if the
351 * implementation of >>= uses an arithmetic rather
352 * than logical shift for a signed left operand
356 value |= - ((gint64)1 <<(size - 7));
357 /* sign bit of byte is second high order bit (0x40) */
358 if ((value == 0 && !(byte & 0x40)) ||
359 (value == -1 && (byte & 0x40)))
363 emit_byte (acfg, byte);
367 static G_GNUC_UNUSED void
368 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
373 guint8 b = value & 0x7f;
375 if (value != 0) /* more bytes to come */
383 static G_GNUC_UNUSED void
384 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
387 gboolean negative = (value < 0);
395 /* the following is unnecessary if the
396 * implementation of >>= uses an arithmetic rather
397 * than logical shift for a signed left operand
401 value |= - (1 <<(size - 7));
402 /* sign bit of byte is second high order bit (0x40) */
403 if ((value == 0 && !(byte & 0x40)) ||
404 (value == -1 && (byte & 0x40)))
414 /* ARCHITECTURE SPECIFIC CODE */
416 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM)
417 #define EMIT_DWARF_INFO 1
421 * arch_emit_direct_call:
423 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
427 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
429 #if defined(TARGET_X86) || defined(TARGET_AMD64)
430 /* Need to make sure this is exactly 5 bytes long */
431 emit_byte (acfg, '\xe8');
432 emit_symbol_diff (acfg, target, ".", -4);
434 #elif defined(TARGET_ARM)
435 if (acfg->use_bin_writer) {
442 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
443 emit_bytes (acfg, buf, 4);
445 img_writer_emit_unset_mode (acfg->w);
446 fprintf (acfg->fp, "bl %s\n", target);
450 g_assert_not_reached ();
454 #ifdef MONO_ARCH_AOT_SUPPORTED
456 * arch_emit_got_offset:
458 * The memory pointed to by CODE should hold native code for computing the GOT
459 * address. Emit this code while patching it with the offset between code and
460 * the GOT. CODE_SIZE is set to the number of bytes emitted.
463 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
465 guint32 offset = mono_arch_get_patch_offset (code);
466 emit_bytes (acfg, code, offset);
467 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
469 *code_size = offset + 4;
473 * arch_emit_got_access:
475 * The memory pointed to by CODE should hold native code for loading a GOT
476 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
477 * CODE_SIZE is set to the number of bytes emitted.
480 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
482 /* Emit beginning of instruction */
483 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
485 /* Emit the offset */
487 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
488 #elif defined(TARGET_X86)
489 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
490 #elif defined(TARGET_ARM)
491 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
493 g_assert_not_reached ();
496 *code_size = mono_arch_get_patch_offset (code) + 4;
502 * arch_emit_plt_entry:
504 * Emit code for the PLT entry with index INDEX.
507 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
509 #if defined(TARGET_X86)
511 /* It is filled up during loading by the AOT loader. */
512 emit_zero_bytes (acfg, 16);
514 /* Need to make sure this is 9 bytes long */
515 emit_byte (acfg, '\xe9');
516 emit_symbol_diff (acfg, "plt", ".", -4);
517 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
519 #elif defined(TARGET_AMD64)
521 * We can't emit jumps because they are 32 bits only so they can't be patched.
522 * So we make indirect calls through GOT entries which are patched by the AOT
523 * loader to point to .Lpd entries.
524 * An x86_64 plt entry is 10 bytes long, init_plt () depends on this.
526 /* jmpq *<offset>(%rip) */
527 emit_byte (acfg, '\xff');
528 emit_byte (acfg, '\x25');
529 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
530 /* Used by mono_aot_get_plt_info_offset */
531 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
532 #elif defined(TARGET_ARM)
537 * - optimize OP_AOTCONST implementation
538 * - optimize the PLT entries
539 * - optimize SWITCH AOT implementation
540 * - implement IMT support
543 if (acfg->use_bin_writer) {
544 /* We only emit 1 relocation since we implement it ourselves anyway */
545 img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, acfg->got_symbol, ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
546 /* FIXME: A 2 instruction encoding is sufficient in most cases */
547 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
548 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
549 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
550 emit_bytes (acfg, buf, code - buf);
551 /* FIXME: Get rid of this */
552 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
553 /* Used by mono_aot_get_plt_info_offset */
554 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
556 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
557 ARM_ADD_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
558 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
559 emit_bytes (acfg, buf, code - buf);
560 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)));
561 /* Used by mono_aot_get_plt_info_offset */
562 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
565 g_assert_not_reached ();
570 * arch_emit_specific_trampoline:
572 * Emit code for a specific trampoline. OFFSET is the offset of the first of
573 * two GOT slots which contain the generic trampoline address and the trampoline
574 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
577 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
580 * The trampolines created here are variations of the specific
581 * trampolines created in mono_arch_create_specific_trampoline (). The
583 * - the generic trampoline address is taken from a got slot.
584 * - the offset of the got slot where the trampoline argument is stored
585 * is embedded in the instruction stream, and the generic trampoline
586 * can load the argument by loading the offset, adding it to the
587 * address of the trampoline to get the address of the got slot, and
588 * loading the argument from there.
589 * - all the trampolines should be of the same length.
591 #if defined(TARGET_AMD64)
592 /* This should be exactly 16 bytes long */
594 /* call *<offset>(%rip) */
595 emit_byte (acfg, '\x41');
596 emit_byte (acfg, '\xff');
597 emit_byte (acfg, '\x15');
598 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
599 /* This should be relative to the start of the trampoline */
600 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 19);
601 emit_zero_bytes (acfg, 5);
602 #elif defined(TARGET_ARM)
606 /* This should be exactly 28 bytes long */
609 ARM_PUSH (code, 0x5fff);
610 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
611 /* Load the value from the GOT */
612 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
614 ARM_MOV_REG_REG (code, ARMREG_LR, ARMREG_PC);
615 ARM_MOV_REG_REG (code, ARMREG_PC, ARMREG_R1);
617 g_assert (code - buf == 20);
620 emit_bytes (acfg, buf, code - buf);
621 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
622 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
624 g_assert_not_reached ();
629 * arch_emit_unbox_trampoline:
631 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
632 * CALL_TARGET is the symbol pointing to the native code of METHOD.
635 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
637 #if defined(TARGET_AMD64)
642 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
644 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
646 emit_bytes (acfg, buf, code - buf);
648 emit_byte (acfg, '\xe9');
649 emit_symbol_diff (acfg, call_target, ".", -4);
650 #elif defined(TARGET_ARM)
657 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
660 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
662 emit_bytes (acfg, buf, code - buf);
664 if (acfg->use_bin_writer) {
671 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
672 emit_bytes (acfg, buf, 4);
674 fprintf (acfg->fp, "\n\tb %s\n", call_target);
677 g_assert_not_reached ();
682 * arch_emit_static_rgctx_trampoline:
684 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
685 * two GOT slots which contain the rgctx argument, and the method to jump to.
686 * TRAMP_SIZE is set to the size of the emitted trampoline.
687 * These kinds of trampolines cannot be enumerated statically, since there could
688 * be one trampoline per method instantiation, so we emit the same code for all
689 * trampolines, and parameterize them using two GOT slots.
692 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
694 #if defined(TARGET_AMD64)
695 /* This should be exactly 13 bytes long */
698 /* mov <OFFSET>(%rip), %r10 */
699 emit_byte (acfg, '\x4d');
700 emit_byte (acfg, '\x8b');
701 emit_byte (acfg, '\x15');
702 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
704 /* jmp *<offset>(%rip) */
705 emit_byte (acfg, '\xff');
706 emit_byte (acfg, '\x25');
707 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
708 #elif defined(TARGET_ARM)
712 /* This should be exactly 24 bytes long */
715 /* Load rgctx value */
716 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
717 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_R1);
718 /* Load branch addr + branch */
719 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
720 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_R1);
722 g_assert (code - buf == 16);
725 emit_bytes (acfg, buf, code - buf);
726 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
727 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
729 g_assert_not_reached ();
734 * arch_emit_imt_thunk:
736 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
737 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
738 * key is the IMT key, and ptr holds the address of a memory location holding
739 * the address to branch to if the IMT arg matches the key. The array is
740 * terminated by a pair whose key is NULL, and whose ptr is the address of the
742 * TRAMP_SIZE is set to the size of the emitted trampoline.
745 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
747 #if defined(TARGET_AMD64)
751 code = buf = g_malloc (256);
753 /* FIXME: Optimize this, i.e. use binary search etc. */
754 /* Maybe move the body into a separate function (slower, but much smaller) */
756 /* R10 is a free register */
759 amd64_alu_membase_imm (code, X86_CMP, AMD64_R10, 0, 0);
761 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
764 amd64_alu_membase_reg (code, X86_CMP, AMD64_R10, 0, MONO_ARCH_IMT_REG);
766 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
769 amd64_alu_reg_imm (code, X86_ADD, AMD64_R10, 2 * sizeof (gpointer));
770 amd64_jump_code (code, labels [0]);
773 mono_amd64_patch (labels [2], code);
774 amd64_mov_reg_membase (code, AMD64_R10, AMD64_R10, sizeof (gpointer), 8);
775 amd64_jump_membase (code, AMD64_R10, 0);
779 mono_amd64_patch (labels [1], code);
780 x86_breakpoint (code);
782 /* mov <OFFSET>(%rip), %r10 */
783 emit_byte (acfg, '\x4d');
784 emit_byte (acfg, '\x8b');
785 emit_byte (acfg, '\x15');
786 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
788 emit_bytes (acfg, buf, code - buf);
790 *tramp_size = code - buf + 7;
791 #elif defined(TARGET_ARM)
793 guint8 *code, *code2, *labels [16];
797 /* The IMT method is in v5 */
799 /* Only IP is available, but we need at least two free registers */
800 ARM_PUSH1 (code, ARMREG_R1);
802 /* Load the parameter from the GOT */
803 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
804 ARM_LDR_REG_REG (code, ARMREG_IP, ARMREG_PC, ARMREG_IP);
807 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_IP, 0);
808 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
810 ARM_B_COND (code, ARMCOND_EQ, 0);
812 /* End-of-loop check */
813 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
815 ARM_B_COND (code, ARMCOND_EQ, 0);
818 ARM_ADD_REG_IMM8 (code, ARMREG_IP, ARMREG_IP, sizeof (gpointer) * 2);
821 arm_patch (labels [4], labels [1]);
824 arm_patch (labels [2], code);
825 ARM_POP1 (code, ARMREG_R1);
826 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_IP, 4);
827 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
830 arm_patch (labels [3], code);
835 ARM_LDR_IMM (code2, ARMREG_IP, ARMREG_PC, (code - (labels [0] + 8)));
837 emit_bytes (acfg, buf, code - buf);
838 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
840 *tramp_size = code - buf + 4;
842 g_assert_not_reached ();
847 * arch_get_cie_program:
849 * Get the unwind bytecode for the DWARF CIE.
852 arch_get_cie_program (void)
857 mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
858 mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
866 /* END OF ARCH SPECIFIC CODE */
869 mono_get_field_token (MonoClassField *field)
871 MonoClass *klass = field->parent;
874 for (i = 0; i < klass->field.count; ++i) {
875 if (field == &klass->fields [i])
876 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
879 g_assert_not_reached ();
884 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
888 //printf ("ENCODE: %d 0x%x.\n", value, value);
891 * Same encoding as the one used in the metadata, extended to handle values
892 * greater than 0x1fffffff.
894 if ((value >= 0) && (value <= 127))
896 else if ((value >= 0) && (value <= 16383)) {
897 p [0] = 0x80 | (value >> 8);
898 p [1] = value & 0xff;
900 } else if ((value >= 0) && (value <= 0x1fffffff)) {
901 p [0] = (value >> 24) | 0xc0;
902 p [1] = (value >> 16) & 0xff;
903 p [2] = (value >> 8) & 0xff;
904 p [3] = value & 0xff;
909 p [1] = (value >> 24) & 0xff;
910 p [2] = (value >> 16) & 0xff;
911 p [3] = (value >> 8) & 0xff;
912 p [4] = value & 0xff;
920 get_image_index (MonoAotCompile *cfg, MonoImage *image)
924 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
928 index = g_hash_table_size (cfg->image_hash);
929 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
930 g_ptr_array_add (cfg->image_table, image);
936 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
941 /* FIXME: Search referenced images as well */
942 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
943 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
948 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
949 return MONO_TOKEN_TYPE_SPEC | (i + 1);
955 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
960 * Encode a reference to KLASS. We use our home-grown encoding instead of the
961 * standard metadata encoding.
964 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
968 if (klass->generic_class) {
970 g_assert (klass->type_token);
972 /* Find a typespec for a class if possible */
973 token = find_typespec_for_class (acfg, klass);
975 encode_value (token, p, &p);
976 encode_value (get_image_index (acfg, acfg->image), p, &p);
978 MonoClass *gclass = klass->generic_class->container_class;
979 MonoGenericInst *inst = klass->generic_class->context.class_inst;
982 /* Encode it ourselves */
984 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
985 encode_value (MONO_TYPE_GENERICINST, p, &p);
986 encode_klass_ref (acfg, gclass, p, &p);
987 encode_value (inst->type_argc, p, &p);
988 for (i = 0; i < inst->type_argc; ++i)
989 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
991 } else if (klass->type_token) {
992 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
993 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
994 encode_value (get_image_index (acfg, klass->image), p, &p);
995 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
996 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
997 g_assert (container);
1000 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1001 encode_value (klass->byval_arg.type, p, &p);
1003 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1005 encode_value (container->is_method, p, &p);
1006 if (container->is_method)
1007 encode_method_ref (acfg, container->owner.method, p, &p);
1009 encode_klass_ref (acfg, container->owner.klass, p, &p);
1012 g_assert (klass->rank > 0);
1013 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1014 encode_value (get_image_index (acfg, klass->image), p, &p);
1015 encode_value (klass->rank, p, &p);
1016 encode_klass_ref (acfg, klass->element_class, p, &p);
1022 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1024 guint32 token = mono_get_field_token (field);
1027 encode_klass_ref (cfg, field->parent, p, &p);
1028 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1029 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1034 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1038 MonoGenericInst *inst;
1040 /* Encode the context */
1041 inst = context->class_inst;
1042 encode_value (inst ? 1 : 0, p, &p);
1044 encode_value (inst->type_argc, p, &p);
1045 for (i = 0; i < inst->type_argc; ++i)
1046 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1048 inst = context->method_inst;
1049 encode_value (inst ? 1 : 0, p, &p);
1051 encode_value (inst->type_argc, p, &p);
1052 for (i = 0; i < inst->type_argc; ++i)
1053 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1059 #define MAX_IMAGE_INDEX 250
1062 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1064 guint32 image_index = get_image_index (acfg, method->klass->image);
1065 guint32 token = method->token;
1066 MonoJumpInfoToken *ji;
1071 * The encoding for most methods is as follows:
1072 * - image index encoded as a leb128
1073 * - token index encoded as a leb128
1074 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1075 * types of method encodings.
1078 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1080 /* Mark methods which can't use aot trampolines because they need the further
1081 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1083 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1084 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1085 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1088 * Some wrapper methods are shared using their signature, encode their
1089 * stringified signature instead.
1090 * FIXME: Optimize disk usage
1093 if (method->wrapper_type) {
1094 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1095 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1096 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1098 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1099 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1100 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1102 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1103 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1104 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1106 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1107 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1108 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1114 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1115 strcpy ((char*)p, name);
1116 p += strlen (name) + 1;
1118 } else if (method->wrapper_type) {
1119 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1121 encode_value (method->wrapper_type, p, &p);
1123 switch (method->wrapper_type) {
1124 case MONO_WRAPPER_REMOTING_INVOKE:
1125 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1126 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1129 m = mono_marshal_method_from_wrapper (method);
1131 encode_method_ref (acfg, m, p, &p);
1134 case MONO_WRAPPER_PROXY_ISINST:
1135 case MONO_WRAPPER_LDFLD:
1136 case MONO_WRAPPER_LDFLDA:
1137 case MONO_WRAPPER_STFLD:
1138 case MONO_WRAPPER_ISINST: {
1139 MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
1140 encode_klass_ref (acfg, proxy_class, p, &p);
1143 case MONO_WRAPPER_LDFLD_REMOTE:
1144 case MONO_WRAPPER_STFLD_REMOTE:
1146 case MONO_WRAPPER_ALLOC: {
1147 int alloc_type = mono_gc_get_managed_allocator_type (method);
1148 g_assert (alloc_type != -1);
1149 encode_value (alloc_type, p, &p);
1152 case MONO_WRAPPER_STELEMREF:
1154 case MONO_WRAPPER_UNKNOWN:
1155 if (strcmp (method->name, "FastMonitorEnter") == 0)
1156 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1157 else if (strcmp (method->name, "FastMonitorExit") == 0)
1158 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1160 g_assert_not_reached ();
1162 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
1163 case MONO_WRAPPER_SYNCHRONIZED:
1164 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
1167 m = mono_marshal_method_from_wrapper (method);
1169 g_assert (m != method);
1170 encode_method_ref (acfg, m, p, &p);
1174 g_assert_not_reached ();
1176 } else if (mono_method_signature (method)->is_inflated) {
1178 * This is a generic method, find the original token which referenced it and
1180 * Obtain the token from information recorded by the JIT.
1182 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1184 image_index = get_image_index (acfg, ji->image);
1185 g_assert (image_index < MAX_IMAGE_INDEX);
1188 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1189 encode_value (image_index, p, &p);
1190 encode_value (token, p, &p);
1192 MonoMethod *declaring;
1193 MonoGenericContext *context = mono_method_get_context (method);
1195 g_assert (method->is_inflated);
1196 declaring = ((MonoMethodInflated*)method)->declaring;
1199 * This might be a non-generic method of a generic instance, which
1200 * doesn't have a token since the reference is generated by the JIT
1201 * like Nullable:Box/Unbox, or by generic sharing.
1204 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1205 /* Encode the klass */
1206 encode_klass_ref (acfg, method->klass, p, &p);
1207 /* Encode the method */
1208 image_index = get_image_index (acfg, method->klass->image);
1209 g_assert (image_index < MAX_IMAGE_INDEX);
1210 g_assert (declaring->token);
1211 token = declaring->token;
1212 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1213 encode_value (image_index, p, &p);
1214 encode_value (token, p, &p);
1215 encode_generic_context (acfg, context, p, &p);
1217 } else if (token == 0) {
1218 /* This might be a method of a constructed type like int[,].Set */
1219 /* Obtain the token from information recorded by the JIT */
1220 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1222 image_index = get_image_index (acfg, ji->image);
1223 g_assert (image_index < MAX_IMAGE_INDEX);
1226 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1227 encode_value (image_index, p, &p);
1228 encode_value (token, p, &p);
1231 g_assert (method->klass->rank);
1233 /* Encode directly */
1234 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1235 encode_klass_ref (acfg, method->klass, p, &p);
1236 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1237 encode_value (0, p, &p);
1238 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1239 encode_value (1, p, &p);
1240 else if (!strcmp (method->name, "Get"))
1241 encode_value (2, p, &p);
1242 else if (!strcmp (method->name, "Address"))
1243 encode_value (3, p, &p);
1244 else if (!strcmp (method->name, "Set"))
1245 encode_value (4, p, &p);
1247 g_assert_not_reached ();
1250 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1251 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1257 compare_patches (gconstpointer a, gconstpointer b)
1261 i = (*(MonoJumpInfo**)a)->ip.i;
1262 j = (*(MonoJumpInfo**)b)->ip.i;
1276 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
1279 static inline gboolean
1280 is_plt_patch (MonoJumpInfo *patch_info)
1282 switch (patch_info->type) {
1283 case MONO_PATCH_INFO_METHOD:
1284 case MONO_PATCH_INFO_INTERNAL_METHOD:
1285 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1286 case MONO_PATCH_INFO_ICALL_ADDR:
1287 case MONO_PATCH_INFO_CLASS_INIT:
1288 case MONO_PATCH_INFO_RGCTX_FETCH:
1289 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1290 case MONO_PATCH_INFO_MONITOR_ENTER:
1291 case MONO_PATCH_INFO_MONITOR_EXIT:
1299 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1303 if (is_plt_patch (patch_info)) {
1304 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1306 if (patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1308 * Allocate a separate PLT slot for each such patch, since some plt
1309 * entries will refer to the method itself, and some will refer to
1318 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1320 res = acfg->plt_offset;
1321 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1322 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1323 acfg->plt_offset ++;
1333 * Returns the offset of the GOT slot where the runtime object resulting from resolving
1334 * JI could be found if it exists, otherwise allocates a new one.
1337 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1341 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji));
1343 return got_offset - 1;
1345 got_offset = acfg->got_offset;
1346 acfg->got_offset ++;
1348 acfg->stats.got_slots ++;
1349 acfg->stats.got_slot_types [ji->type] ++;
1355 get_shared_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1360 if (!g_hash_table_lookup (acfg->patch_to_shared_got_offset, ji)) {
1361 got_offset = get_got_offset (acfg, ji);
1362 copy = mono_patch_info_dup_mp (acfg->mempool, ji);
1363 g_hash_table_insert (acfg->patch_to_shared_got_offset, copy, GUINT_TO_POINTER (got_offset + 1));
1364 g_ptr_array_add (acfg->shared_patches, copy);
1367 return get_got_offset (acfg, ji);
1370 /* Add a method to the list of methods which need to be emitted */
1372 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index)
1375 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1376 g_ptr_array_add (acfg->methods, method);
1377 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1378 acfg->nmethods = acfg->methods->len + 1;
1383 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1385 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1393 add_method (MonoAotCompile *acfg, MonoMethod *method)
1397 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1401 index = acfg->method_index;
1402 add_method_with_index (acfg, method, index);
1404 /* FIXME: Fix quadratic behavior */
1405 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1407 acfg->method_index ++;
1413 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
1417 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1420 add_method (acfg, method);
1421 g_ptr_array_add (acfg->extra_methods, method);
1425 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1427 MonoAotCompile *acfg = user_data;
1428 MonoJitICallInfo *callinfo = value;
1429 MonoMethod *wrapper;
1435 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1436 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1439 add_method (acfg, wrapper);
1443 get_runtime_invoke_sig (MonoMethodSignature *sig)
1445 MonoMethodBuilder *mb;
1448 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1449 m = mono_mb_create_method (mb, sig, 16);
1450 return mono_marshal_get_runtime_invoke (m, FALSE);
1454 add_wrappers (MonoAotCompile *acfg)
1456 MonoMethod *method, *m;
1457 int i, j, nallocators;
1458 MonoMethodSignature *sig, *csig;
1462 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1463 * so there is only one wrapper of a given type, or inlining their contents into their
1468 * FIXME: This depends on the fact that different wrappers have different
1472 /* FIXME: Collect these automatically */
1474 /* Runtime invoke wrappers */
1476 /* void runtime-invoke () [.cctor] */
1477 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1478 csig->ret = &mono_defaults.void_class->byval_arg;
1479 add_method (acfg, get_runtime_invoke_sig (csig));
1481 /* void runtime-invoke () [Finalize] */
1482 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1484 csig->ret = &mono_defaults.void_class->byval_arg;
1485 add_method (acfg, get_runtime_invoke_sig (csig));
1487 /* void runtime-invoke (string) [exception ctor] */
1488 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
1490 csig->ret = &mono_defaults.void_class->byval_arg;
1491 csig->params [0] = &mono_defaults.string_class->byval_arg;
1492 add_method (acfg, get_runtime_invoke_sig (csig));
1494 /* void runtime-invoke (string, string) [exception ctor] */
1495 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1497 csig->ret = &mono_defaults.void_class->byval_arg;
1498 csig->params [0] = &mono_defaults.string_class->byval_arg;
1499 csig->params [1] = &mono_defaults.string_class->byval_arg;
1500 add_method (acfg, get_runtime_invoke_sig (csig));
1502 /* string runtime-invoke () [Exception.ToString ()] */
1503 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1505 csig->ret = &mono_defaults.string_class->byval_arg;
1506 add_method (acfg, get_runtime_invoke_sig (csig));
1508 /* void runtime-invoke (string, Exception) [exception ctor] */
1509 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1511 csig->ret = &mono_defaults.void_class->byval_arg;
1512 csig->params [0] = &mono_defaults.string_class->byval_arg;
1513 csig->params [1] = &mono_defaults.exception_class->byval_arg;
1514 add_method (acfg, get_runtime_invoke_sig (csig));
1516 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
1517 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1519 csig->ret = &(mono_class_from_name (
1520 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
1521 csig->params [0] = &mono_defaults.string_class->byval_arg;
1522 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
1523 add_method (acfg, get_runtime_invoke_sig (csig));
1525 /* runtime-invoke used by finalizers */
1526 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
1528 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1530 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1531 gboolean skip = FALSE;
1533 method = mono_get_method (acfg->image, token, NULL);
1535 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1536 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1537 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1540 if (method->is_generic || method->klass->generic_container)
1543 /* Skip methods which can not be handled by get_runtime_invoke () */
1544 sig = mono_method_signature (method);
1545 if ((sig->ret->type == MONO_TYPE_PTR) ||
1546 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
1549 for (j = 0; j < sig->param_count; j++) {
1550 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
1555 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
1558 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
1559 MonoMethodDesc *desc;
1560 MonoMethod *orig_method;
1562 /* JIT icall wrappers */
1563 /* FIXME: locking */
1564 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
1566 /* Managed Allocators */
1567 nallocators = mono_gc_get_managed_allocator_types ();
1568 for (i = 0; i < nallocators; ++i) {
1569 m = mono_gc_get_managed_allocator_by_type (i);
1571 add_method (acfg, m);
1575 add_method (acfg, mono_marshal_get_stelemref ());
1577 /* Monitor Enter/Exit */
1578 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
1579 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1580 g_assert (orig_method);
1581 mono_method_desc_free (desc);
1582 method = mono_monitor_get_fast_path (orig_method);
1584 add_method (acfg, method);
1586 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
1587 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
1588 g_assert (orig_method);
1589 mono_method_desc_free (desc);
1590 method = mono_monitor_get_fast_path (orig_method);
1592 add_method (acfg, method);
1595 /* remoting-invoke wrappers */
1596 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1597 MonoMethodSignature *sig;
1599 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1600 method = mono_get_method (acfg->image, token, NULL);
1602 sig = mono_method_signature (method);
1604 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
1605 m = mono_marshal_get_remoting_invoke_with_check (method);
1607 add_method (acfg, m);
1611 /* delegate-invoke wrappers */
1612 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
1615 token = MONO_TOKEN_TYPE_DEF | (i + 1);
1616 klass = mono_class_get (acfg->image, token);
1618 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
1619 method = mono_get_delegate_invoke (klass);
1621 m = mono_marshal_get_delegate_invoke (method, NULL);
1623 add_method (acfg, m);
1625 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
1626 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
1628 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
1629 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
1633 /* Synchronized wrappers */
1634 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1635 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1636 method = mono_get_method (acfg->image, token, NULL);
1638 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
1639 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
1642 /* pinvoke wrappers */
1643 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1645 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1647 method = mono_get_method (acfg->image, token, NULL);
1649 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1650 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
1651 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
1657 has_type_vars (MonoClass *klass)
1659 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
1662 return has_type_vars (klass->element_class);
1663 if (klass->generic_class) {
1664 MonoGenericContext *context = &klass->generic_class->context;
1665 if (context->class_inst) {
1668 for (i = 0; i < context->class_inst->type_argc; ++i)
1669 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
1677 method_has_type_vars (MonoMethod *method)
1679 if (has_type_vars (method->klass))
1682 if (method->is_inflated) {
1683 MonoGenericContext *context = mono_method_get_context (method);
1684 if (context->method_inst) {
1687 for (i = 0; i < context->method_inst->type_argc; ++i)
1688 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
1696 * add_generic_class:
1698 * Add all methods of a generic class.
1701 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
1706 mono_class_init (klass);
1708 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
1711 if (has_type_vars (klass))
1714 if (!klass->generic_class && !klass->rank)
1718 * Add rgctx wrappers for cctors since those are called by the runtime, so
1719 * there is no methodspec for them. This is needed even for shared classes,
1720 * since rgctx wrappers belong to inflated methods.
1722 method = mono_class_get_cctor (klass);
1723 if (method && mono_method_needs_static_rgctx_invoke (method, FALSE))
1724 add_extra_method (acfg, mono_marshal_get_static_rgctx_invoke (method));
1727 while ((method = mono_class_get_methods (klass, &iter))) {
1728 if (mono_method_is_generic_sharable_impl (method, FALSE))
1732 if (method->is_generic)
1737 * FIXME: Instances which are referenced by these methods are not added,
1738 * for example Array.Resize<int> for List<int>.Add ().
1740 add_extra_method (acfg, method);
1744 * For ICollection<T>, where T is a vtype, add instances of the helper methods
1745 * in Array, since a T[] could be cast to ICollection<T>.
1747 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
1748 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1")) &&
1749 MONO_TYPE_ISSTRUCT (klass->generic_class->context.class_inst->type_argv [0])) {
1750 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
1751 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
1755 if (!strcmp (klass->name, "IEnumerator`1"))
1756 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
1758 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
1760 /* Add the T[]/InternalEnumerator class */
1761 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
1765 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
1766 if (!strcmp (nclass->name, "InternalEnumerator`1"))
1770 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
1771 add_generic_class (acfg, nclass);
1775 while ((method = mono_class_get_methods (array_class, &iter))) {
1776 if (strstr (method->name, name_prefix))
1777 add_extra_method (acfg, method);
1780 g_free (name_prefix);
1785 * add_generic_instances:
1787 * Add instances referenced by the METHODSPEC/TYPESPEC table.
1790 add_generic_instances (MonoAotCompile *acfg)
1795 MonoMethodHeader *header;
1796 MonoMethodSignature *sig;
1797 MonoGenericContext *context;
1799 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
1800 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
1801 method = mono_get_method (acfg->image, token, NULL);
1803 context = mono_method_get_context (method);
1804 if (context && ((context->class_inst && context->class_inst->is_open) ||
1805 (context->method_inst && context->method_inst->is_open)))
1808 if (method->klass->image != acfg->image)
1811 if (mono_method_is_generic_sharable_impl (method, FALSE))
1815 add_extra_method (acfg, method);
1818 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1821 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
1823 klass = mono_class_get (acfg->image, token);
1827 add_generic_class (acfg, klass);
1830 /* Add types of args/locals */
1831 for (i = 0; i < acfg->methods->len; ++i) {
1834 method = g_ptr_array_index (acfg->methods, i);
1836 sig = mono_method_signature (method);
1839 for (j = 0; j < sig->param_count; ++j)
1840 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
1841 add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
1844 header = mono_method_get_header (method);
1847 for (j = 0; j < header->num_locals; ++j)
1848 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
1849 add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
1855 * emit_and_reloc_code:
1857 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
1858 * is true, calls are made through the GOT too. This is used for emitting trampolines
1859 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
1860 * since trampolines are needed to make PTL work.
1863 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
1865 int i, pindex, start_index, method_index;
1867 MonoJumpInfo *patch_info;
1868 MonoMethodHeader *header;
1869 gboolean skip, direct_call;
1871 char direct_call_target [128];
1874 header = mono_method_get_header (method);
1876 method_index = get_method_index (acfg, method);
1879 /* Collect and sort relocations */
1880 patches = g_ptr_array_new ();
1881 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
1882 g_ptr_array_add (patches, patch_info);
1883 g_ptr_array_sort (patches, compare_patches);
1886 for (i = 0; i < code_len; i++) {
1888 for (pindex = start_index; pindex < patches->len; ++pindex) {
1889 patch_info = g_ptr_array_index (patches, pindex);
1890 if (patch_info->ip.i >= i)
1894 #ifdef MONO_ARCH_AOT_SUPPORTED
1896 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
1897 start_index = pindex;
1899 switch (patch_info->type) {
1900 case MONO_PATCH_INFO_NONE:
1902 case MONO_PATCH_INFO_GOT_OFFSET: {
1905 arch_emit_got_offset (acfg, code + i, &code_size);
1912 * If this patch is a call, try emitting a direct call instead of
1913 * through a PLT entry. This is possible if the called method is in
1914 * the same assembly and requires no initialization.
1916 direct_call = FALSE;
1917 if (!got_only && (patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == method->klass->image)) {
1918 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
1920 gboolean direct_callable = TRUE;
1922 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
1923 direct_callable = FALSE;
1924 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED)
1925 // FIXME: Maybe call the wrapper directly ?
1926 direct_callable = FALSE;
1927 if (direct_callable) {
1928 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
1930 sprintf (direct_call_target, ".Lm_%x", get_method_index (acfg, callee_cfg->orig_method));
1931 patch_info->type = MONO_PATCH_INFO_NONE;
1932 acfg->stats.direct_calls ++;
1936 acfg->stats.all_calls ++;
1939 if (!got_only && !direct_call) {
1940 int plt_offset = get_plt_offset (acfg, patch_info);
1941 if (plt_offset != -1) {
1942 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
1944 sprintf (direct_call_target, ".Lp_%d", plt_offset);
1946 /* Nullify the patch */
1947 patch_info->type = MONO_PATCH_INFO_NONE;
1954 arch_emit_direct_call (acfg, direct_call_target, &call_size);
1959 got_slot = get_got_offset (acfg, patch_info);
1961 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
1968 #endif /* MONO_ARCH_AOT_SUPPORTED */
1971 /* Find next patch */
1973 for (pindex = start_index; pindex < patches->len; ++pindex) {
1974 patch_info = g_ptr_array_index (patches, pindex);
1975 if (patch_info->ip.i >= i)
1979 /* Try to emit multiple bytes at once */
1980 if (pindex < patches->len && patch_info->ip.i > i) {
1981 emit_bytes (acfg, code + i, patch_info->ip.i - i);
1982 i = patch_info->ip.i - 1;
1984 emit_bytes (acfg, code + i, 1);
1991 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
1997 int func_alignment = 16;
1998 MonoMethodHeader *header;
2000 method = cfg->orig_method;
2001 code = cfg->native_code;
2002 header = mono_method_get_header (method);
2004 method_index = get_method_index (acfg, method);
2006 /* Make the labels local */
2007 sprintf (symbol, ".Lm_%x", method_index);
2009 emit_alignment (acfg, func_alignment);
2010 emit_label (acfg, symbol);
2012 if (acfg->aot_opts.write_symbols && !acfg->aot_opts.nodebug) {
2013 char *name1, *name2;
2016 name1 = mono_method_full_name (method, TRUE);
2017 len = strlen (name1);
2018 name2 = malloc (len + 1);
2020 for (i = 0; i < len; ++i) {
2021 if (isalnum (name1 [i])) {
2022 name2 [j ++] = name1 [i];
2023 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
2025 } else if (name1 [i] == '(' || name1 [i] == ')') {
2030 sprintf (symbol, ".Lme_%x", method_index);
2031 emit_local_symbol (acfg, name2, symbol, TRUE);
2032 emit_label (acfg, name2);
2037 if (cfg->verbose_level > 0)
2038 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2040 acfg->stats.code_size += cfg->code_len;
2042 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
2044 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2048 sprintf (symbol, ".Lme_%x", method_index);
2049 emit_label (acfg, symbol);
2055 * Encode PATCH_INFO into its disk representation.
2058 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2062 switch (patch_info->type) {
2063 case MONO_PATCH_INFO_NONE:
2065 case MONO_PATCH_INFO_IMAGE:
2066 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2068 case MONO_PATCH_INFO_METHOD_REL:
2069 encode_value ((gint)patch_info->data.offset, p, &p);
2071 case MONO_PATCH_INFO_SWITCH: {
2072 gpointer *table = (gpointer *)patch_info->data.table->table;
2075 encode_value (patch_info->data.table->table_size, p, &p);
2076 for (k = 0; k < patch_info->data.table->table_size; k++)
2077 encode_value ((int)(gssize)table [k], p, &p);
2080 case MONO_PATCH_INFO_METHODCONST:
2081 case MONO_PATCH_INFO_METHOD:
2082 case MONO_PATCH_INFO_METHOD_JUMP:
2083 case MONO_PATCH_INFO_ICALL_ADDR:
2084 case MONO_PATCH_INFO_METHOD_RGCTX:
2085 encode_method_ref (acfg, patch_info->data.method, p, &p);
2087 case MONO_PATCH_INFO_INTERNAL_METHOD:
2088 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2089 guint32 len = strlen (patch_info->data.name);
2091 encode_value (len, p, &p);
2093 memcpy (p, patch_info->data.name, len);
2098 case MONO_PATCH_INFO_LDSTR: {
2099 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2100 guint32 token = patch_info->data.token->token;
2101 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2102 encode_value (image_index, p, &p);
2103 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2106 case MONO_PATCH_INFO_RVA:
2107 case MONO_PATCH_INFO_DECLSEC:
2108 case MONO_PATCH_INFO_LDTOKEN:
2109 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2110 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2111 encode_value (patch_info->data.token->token, p, &p);
2112 encode_value (patch_info->data.token->has_context, p, &p);
2113 if (patch_info->data.token->has_context)
2114 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
2116 case MONO_PATCH_INFO_EXC_NAME: {
2117 MonoClass *ex_class;
2120 mono_class_from_name (mono_defaults.exception_class->image,
2121 "System", patch_info->data.target);
2122 g_assert (ex_class);
2123 encode_klass_ref (acfg, ex_class, p, &p);
2126 case MONO_PATCH_INFO_R4:
2127 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2129 case MONO_PATCH_INFO_R8:
2130 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2131 encode_value (*(((guint32 *)patch_info->data.target) + 1), p, &p);
2133 case MONO_PATCH_INFO_VTABLE:
2134 case MONO_PATCH_INFO_CLASS:
2135 case MONO_PATCH_INFO_IID:
2136 case MONO_PATCH_INFO_ADJUSTED_IID:
2137 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2139 case MONO_PATCH_INFO_CLASS_INIT:
2140 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2141 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2143 case MONO_PATCH_INFO_FIELD:
2144 case MONO_PATCH_INFO_SFLDA:
2145 encode_field_info (acfg, patch_info->data.field, p, &p);
2147 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2149 case MONO_PATCH_INFO_RGCTX_FETCH: {
2150 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2152 encode_method_ref (acfg, entry->method, p, &p);
2153 encode_value (entry->in_mrgctx, p, &p);
2154 encode_value (entry->info_type, p, &p);
2155 encode_value (entry->data->type, p, &p);
2156 encode_patch (acfg, entry->data, p, &p);
2159 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2160 case MONO_PATCH_INFO_MONITOR_ENTER:
2161 case MONO_PATCH_INFO_MONITOR_EXIT:
2164 g_warning ("unable to handle jump info %d", patch_info->type);
2165 g_assert_not_reached ();
2172 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2176 MonoJumpInfo *patch_info;
2178 encode_value (n_patches, p, &p);
2181 encode_value (first_got_offset, p, &p);
2183 for (pindex = 0; pindex < patches->len; ++pindex) {
2184 patch_info = g_ptr_array_index (patches, pindex);
2186 if (patch_info->type == MONO_PATCH_INFO_NONE)
2190 encode_value (patch_info->type, p, &p);
2191 if (mono_aot_is_shared_got_patch (patch_info)) {
2192 guint32 offset = get_got_offset (acfg, patch_info);
2193 encode_value (offset, p, &p);
2195 encode_patch (acfg, patch_info, p, &p);
2203 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2207 int pindex, buf_size, n_patches;
2211 MonoJumpInfo *patch_info;
2212 MonoMethodHeader *header;
2213 guint32 method_index;
2215 guint32 first_got_offset;
2217 method = cfg->orig_method;
2218 code = cfg->native_code;
2219 header = mono_method_get_header (method);
2221 method_index = get_method_index (acfg, method);
2223 /* Make the labels local */
2224 sprintf (symbol, ".Lm_%x_p", method_index);
2226 /* Sort relocations */
2227 patches = g_ptr_array_new ();
2228 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2229 g_ptr_array_add (patches, patch_info);
2230 g_ptr_array_sort (patches, compare_patches);
2232 first_got_offset = acfg->cfgs [method_index]->got_offset;
2234 /**********************/
2235 /* Encode method info */
2236 /**********************/
2238 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2239 p = buf = g_malloc (buf_size);
2241 if (mono_class_get_cctor (method->klass))
2242 encode_klass_ref (acfg, method->klass, p, &p);
2244 /* Not needed when loading the method */
2245 encode_value (0, p, &p);
2248 if (cfg->opt & MONO_OPT_SHARED) {
2249 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2250 for (l = cfg->ldstr_list; l; l = l->next) {
2251 encode_value ((long)l->data, p, &p);
2255 /* Used only in shared mode */
2256 g_assert (!cfg->ldstr_list);
2259 for (pindex = 0; pindex < patches->len; ++pindex) {
2260 patch_info = g_ptr_array_index (patches, pindex);
2262 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2263 (patch_info->type == MONO_PATCH_INFO_NONE)) {
2264 patch_info->type = MONO_PATCH_INFO_NONE;
2269 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2270 /* Stored in a GOT slot initialized at module load time */
2271 patch_info->type = MONO_PATCH_INFO_NONE;
2275 if (is_plt_patch (patch_info)) {
2276 /* Calls are made through the PLT */
2277 patch_info->type = MONO_PATCH_INFO_NONE;
2285 g_assert (cfg->has_got_slots);
2287 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2289 acfg->stats.info_size += p - buf;
2291 /* Emit method info */
2293 emit_label (acfg, symbol);
2295 g_assert (p - buf < buf_size);
2296 emit_bytes (acfg, buf, p - buf);
2301 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
2303 guint32 cache_index;
2306 /* Reuse the unwind module to canonize and store unwind info entries */
2307 cache_index = mono_cache_unwind_info (encoded, encoded_len);
2309 /* Use +/- 1 to distinguish 0s from missing entries */
2310 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
2318 * It would be easier to use assembler symbols, but the caller needs an
2321 offset = acfg->unwind_info_offset;
2322 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
2323 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
2326 encode_value (encoded_len, p, &p);
2328 acfg->unwind_info_offset += encoded_len + (p - buf);
2334 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
2337 int k, buf_size, method_index;
2338 guint32 debug_info_size;
2341 MonoMethodHeader *header;
2342 guint8 *p, *buf, *debug_info;
2343 MonoJitInfo *jinfo = cfg->jit_info;
2345 gboolean use_unwind_ops = FALSE;
2347 method = cfg->orig_method;
2348 code = cfg->native_code;
2349 header = mono_method_get_header (method);
2351 method_index = get_method_index (acfg, method);
2353 /* Make the labels local */
2354 sprintf (symbol, ".Le_%x_p", method_index);
2356 if (!acfg->aot_opts.nodebug) {
2357 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
2360 debug_info_size = 0;
2363 buf_size = header->num_clauses * 256 + debug_info_size + 1024;
2364 p = buf = g_malloc (buf_size);
2366 #ifdef MONO_ARCH_HAVE_XP_UNWIND
2367 use_unwind_ops = cfg->unwind_ops != NULL;
2370 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0);
2372 encode_value (jinfo->code_size, p, &p);
2373 encode_value (flags, p, &p);
2375 if (use_unwind_ops) {
2376 guint32 encoded_len;
2380 * This is a duplicate of the data in the .debug_frame section, but that
2381 * section cannot be accessed using the dl interface.
2383 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
2384 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
2387 encode_value (jinfo->used_regs, p, &p);
2390 /* Exception table */
2391 if (header->num_clauses) {
2392 for (k = 0; k < header->num_clauses; ++k) {
2393 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
2395 encode_value (ei->exvar_offset, p, &p);
2397 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
2398 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
2400 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
2401 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
2402 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
2406 if (jinfo->has_generic_jit_info) {
2407 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
2409 encode_value (gi->has_this ? 1 : 0, p, &p);
2410 encode_value (gi->this_reg, p, &p);
2411 encode_value (gi->this_offset, p, &p);
2414 * Need to encode jinfo->method too, since it is not equal to 'method'
2415 * when using generic sharing.
2417 encode_method_ref (acfg, jinfo->method, p, &p);
2420 g_assert (debug_info_size < buf_size);
2422 encode_value (debug_info_size, p, &p);
2423 if (debug_info_size) {
2424 memcpy (p, debug_info, debug_info_size);
2425 p += debug_info_size;
2426 g_free (debug_info);
2429 acfg->stats.ex_info_size += p - buf;
2433 emit_label (acfg, symbol);
2435 g_assert (p - buf < buf_size);
2436 emit_bytes (acfg, buf, p - buf);
2441 emit_klass_info (MonoAotCompile *acfg, guint32 token)
2443 MonoClass *klass = mono_class_get (acfg->image, token);
2447 gboolean no_special_static, cant_encode;
2448 gpointer iter = NULL;
2450 buf_size = 10240 + (klass->vtable_size * 16);
2451 p = buf = g_malloc (buf_size);
2455 mono_class_init (klass);
2457 mono_class_get_nested_types (klass, &iter);
2458 g_assert (klass->nested_classes_inited);
2460 mono_class_setup_vtable (klass);
2463 * Emit all the information which is required for creating vtables so
2464 * the runtime does not need to create the MonoMethod structures which
2465 * take up a lot of space.
2468 no_special_static = !mono_class_has_special_static_fields (klass);
2470 /* Check whenever we have enough info to encode the vtable */
2471 cant_encode = FALSE;
2472 for (i = 0; i < klass->vtable_size; ++i) {
2473 MonoMethod *cm = klass->vtable [i];
2475 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
2479 if (klass->generic_container || cant_encode) {
2480 encode_value (-1, p, &p);
2482 encode_value (klass->vtable_size, p, &p);
2483 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);
2484 if (klass->has_cctor)
2485 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
2486 if (klass->has_finalize)
2487 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
2489 encode_value (klass->instance_size, p, &p);
2490 encode_value (mono_class_data_size (klass), p, &p);
2491 encode_value (klass->packing_size, p, &p);
2492 encode_value (klass->min_align, p, &p);
2494 for (i = 0; i < klass->vtable_size; ++i) {
2495 MonoMethod *cm = klass->vtable [i];
2498 encode_method_ref (acfg, cm, p, &p);
2500 encode_value (0, p, &p);
2504 acfg->stats.class_info_size += p - buf;
2507 sprintf (symbol, ".LK_I_%x", token - MONO_TOKEN_TYPE_DEF - 1);
2508 emit_label (acfg, symbol);
2510 g_assert (p - buf < buf_size);
2511 emit_bytes (acfg, buf, p - buf);
2516 * Calls made from AOTed code are routed through a table of jumps similar to the
2517 * ELF PLT (Program Linkage Table). The differences are the following:
2518 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
2519 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
2520 * jumps. This means the jumps need to be patched when the address of the callee is
2521 * known. Initially the PLT entries jump to code which transfers control to the
2522 * AOT runtime through the first PLT entry.
2525 emit_plt (MonoAotCompile *acfg)
2531 sprintf (symbol, "plt");
2533 emit_section_change (acfg, ".text", 0);
2534 emit_global (acfg, symbol, TRUE);
2536 /* This section will be made read-write by the AOT loader */
2537 emit_alignment (acfg, mono_pagesize ());
2539 emit_alignment (acfg, 16);
2541 emit_label (acfg, symbol);
2543 for (i = 0; i < acfg->plt_offset; ++i) {
2546 sprintf (label, ".Lp_%d", i);
2547 emit_label (acfg, label);
2550 * The first plt entry is used to transfer code to the AOT loader.
2552 arch_emit_plt_entry (acfg, i);
2555 sprintf (symbol, "plt_end");
2556 emit_global (acfg, symbol, TRUE);
2557 emit_label (acfg, symbol);
2560 static G_GNUC_UNUSED void
2561 emit_trampoline (MonoAotCompile *acfg, const char *name, guint8 *code,
2562 guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
2566 MonoJumpInfo *patch_info;
2572 sprintf (symbol, "%s", name);
2574 emit_section_change (acfg, ".text", 0);
2575 emit_global (acfg, symbol, TRUE);
2576 emit_alignment (acfg, 16);
2577 emit_label (acfg, symbol);
2579 sprintf (symbol, ".Lnamed_%s", name);
2580 emit_label (acfg, symbol);
2583 * The code should access everything through the GOT, so we pass
2586 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
2590 /* Sort relocations */
2591 patches = g_ptr_array_new ();
2592 for (patch_info = ji; patch_info; patch_info = patch_info->next)
2593 g_ptr_array_add (patches, patch_info);
2594 g_ptr_array_sort (patches, compare_patches);
2596 buf_size = patches->len * 128 + 128;
2597 buf = g_malloc (buf_size);
2600 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
2601 g_assert (p - buf < buf_size);
2603 sprintf (symbol, "%s_p", name);
2605 emit_section_change (acfg, ".text", 0);
2606 emit_global (acfg, symbol, FALSE);
2607 emit_label (acfg, symbol);
2609 emit_bytes (acfg, buf, p - buf);
2611 /* Emit debug info */
2615 sprintf (symbol, "%s", name);
2616 sprintf (symbol2, ".Lnamed_%s", name);
2619 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
2624 emit_trampolines (MonoAotCompile *acfg)
2627 int i, tramp_got_offset;
2628 MonoAotTrampoline ntype;
2629 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2637 if (!acfg->aot_opts.full_aot)
2640 g_assert (acfg->image->assembly);
2642 /* Currently, we only emit most trampolines into the mscorlib AOT image. */
2643 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2644 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
2646 * Emit the generic trampolines.
2648 * We could save some code by treating the generic trampolines as a wrapper
2649 * method, but that approach has its own complexities, so we choose the simpler
2652 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
2653 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
2655 /* Emit trampoline code */
2657 sprintf (symbol, "generic_trampoline_%d", tramp_type);
2659 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
2662 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
2663 emit_trampoline (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
2664 #if defined(TARGET_AMD64) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
2665 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
2666 emit_trampoline (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2667 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
2668 emit_trampoline (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2671 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
2672 emit_trampoline (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
2674 /* Emit the exception related code pieces */
2675 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
2676 emit_trampoline (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
2677 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
2678 emit_trampoline (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
2679 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
2680 emit_trampoline (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
2681 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
2682 emit_trampoline (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
2683 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
2684 emit_trampoline (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
2685 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
2686 emit_trampoline (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
2688 #if defined(TARGET_AMD64)
2689 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
2690 emit_trampoline (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
2693 #if defined(TARGET_AMD64) || defined(TARGET_ARM)
2694 for (i = 0; i < 128; ++i) {
2697 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
2698 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
2699 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
2700 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
2702 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
2703 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
2704 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
2705 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
2709 #if defined(TARGET_AMD64) || defined(TARGET_ARM)
2713 /* delegate_invoke_impl trampolines */
2714 l = mono_arch_get_delegate_invoke_impls ();
2716 MonoAotTrampInfo *info = l->data;
2718 emit_trampoline (acfg, info->name, info->code, info->code_size, acfg->got_offset, NULL, NULL);
2724 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
2726 /* Emit trampolines which are numerous */
2729 * These include the following:
2730 * - specific trampolines
2731 * - static rgctx invoke trampolines
2733 * These trampolines have the same code, they are parameterized by GOT
2735 * They are defined in this file, in the arch_... routines instead of
2736 * in tramp-<ARCH>.c, since it is easier to do it this way.
2740 * When running in aot-only mode, we can't create specific trampolines at
2741 * runtime, so we create a few, and save them in the AOT file.
2742 * Normal trampolines embed their argument as a literal inside the
2743 * trampoline code, we can't do that here, so instead we embed an offset
2744 * which needs to be added to the trampoline address to get the address of
2745 * the GOT slot which contains the argument value.
2746 * The generated trampolines jump to the generic trampolines using another
2747 * GOT slot, which will be setup by the AOT loader to point to the
2748 * generic trampoline code of the given type.
2752 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
2756 emit_section_change (acfg, ".text", 0);
2758 tramp_got_offset = acfg->got_offset;
2760 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
2762 case MONO_AOT_TRAMP_SPECIFIC:
2763 sprintf (symbol, "specific_trampolines");
2765 case MONO_AOT_TRAMP_STATIC_RGCTX:
2766 sprintf (symbol, "static_rgctx_trampolines");
2768 case MONO_AOT_TRAMP_IMT_THUNK:
2769 sprintf (symbol, "imt_thunks");
2772 g_assert_not_reached ();
2775 emit_global (acfg, symbol, TRUE);
2776 emit_alignment (acfg, 16);
2777 emit_label (acfg, symbol);
2779 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
2781 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
2785 case MONO_AOT_TRAMP_SPECIFIC:
2786 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
2787 tramp_got_offset += 2;
2789 case MONO_AOT_TRAMP_STATIC_RGCTX:
2790 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
2791 tramp_got_offset += 2;
2793 case MONO_AOT_TRAMP_IMT_THUNK:
2794 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
2795 tramp_got_offset += 1;
2798 g_assert_not_reached ();
2801 if (!acfg->trampoline_size [ntype]) {
2802 g_assert (tramp_size);
2803 acfg->trampoline_size [ntype] = tramp_size;
2808 /* Reserve some entries at the end of the GOT for our use */
2809 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
2812 /* Unbox trampolines */
2813 for (i = 0; i < acfg->methods->len; ++i) {
2814 MonoMethod *method = g_ptr_array_index (acfg->methods, i);
2816 char call_target [256];
2818 cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
2819 if (!cfg || !cfg->orig_method->klass->valuetype || !(method->flags & METHOD_ATTRIBUTE_VIRTUAL))
2822 if (!method->wrapper_type && !method->is_inflated) {
2823 g_assert (method->token);
2824 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
2826 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
2829 emit_section_change (acfg, ".text", 0);
2830 emit_global (acfg, symbol, TRUE);
2831 emit_label (acfg, symbol);
2833 sprintf (call_target, ".Lm_%x", get_method_index (acfg, cfg->orig_method));
2835 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
2838 acfg->got_offset += acfg->num_trampoline_got_entries;
2842 str_begins_with (const char *str1, const char *str2)
2844 int len = strlen (str2);
2845 return strncmp (str1, str2, len) == 0;
2849 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
2851 gchar **args, **ptr;
2853 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
2854 for (ptr = args; ptr && *ptr; ptr ++) {
2855 const char *arg = *ptr;
2857 if (str_begins_with (arg, "outfile=")) {
2858 opts->outfile = g_strdup (arg + strlen ("outfile="));
2859 } else if (str_begins_with (arg, "save-temps")) {
2860 opts->save_temps = TRUE;
2861 } else if (str_begins_with (arg, "keep-temps")) {
2862 opts->save_temps = TRUE;
2863 } else if (str_begins_with (arg, "write-symbols")) {
2864 opts->write_symbols = TRUE;
2865 } else if (str_begins_with (arg, "metadata-only")) {
2866 opts->metadata_only = TRUE;
2867 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
2868 opts->bind_to_runtime_version = TRUE;
2869 } else if (str_begins_with (arg, "full")) {
2870 opts->full_aot = TRUE;
2871 } else if (str_begins_with (arg, "threads=")) {
2872 opts->nthreads = atoi (arg + strlen ("threads="));
2873 } else if (str_begins_with (arg, "static")) {
2874 opts->static_link = TRUE;
2875 opts->no_dlsym = TRUE;
2876 } else if (str_begins_with (arg, "asmonly")) {
2877 opts->asm_only = TRUE;
2878 } else if (str_begins_with (arg, "asmwriter")) {
2879 opts->asm_writer = TRUE;
2880 } else if (str_begins_with (arg, "nodebug")) {
2881 opts->nodebug = TRUE;
2882 } else if (str_begins_with (arg, "ntrampolines=")) {
2883 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
2885 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
2894 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
2896 MonoMethod *method = (MonoMethod*)key;
2897 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
2898 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
2899 MonoAotCompile *acfg = user_data;
2901 new_ji->image = ji->image;
2902 new_ji->token = ji->token;
2903 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
2907 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
2909 if (klass->type_token)
2911 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2914 return can_encode_class (acfg, klass->element_class);
2919 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2921 switch (patch_info->type) {
2922 case MONO_PATCH_INFO_METHOD:
2923 case MONO_PATCH_INFO_METHODCONST: {
2924 MonoMethod *method = patch_info->data.method;
2926 if (method->wrapper_type) {
2927 switch (method->wrapper_type) {
2928 case MONO_WRAPPER_NONE:
2929 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2930 case MONO_WRAPPER_XDOMAIN_INVOKE:
2931 case MONO_WRAPPER_STFLD:
2932 case MONO_WRAPPER_LDFLD:
2933 case MONO_WRAPPER_LDFLDA:
2934 case MONO_WRAPPER_LDFLD_REMOTE:
2935 case MONO_WRAPPER_STFLD_REMOTE:
2936 case MONO_WRAPPER_STELEMREF:
2937 case MONO_WRAPPER_ISINST:
2938 case MONO_WRAPPER_PROXY_ISINST:
2939 case MONO_WRAPPER_ALLOC:
2940 case MONO_WRAPPER_REMOTING_INVOKE:
2941 case MONO_WRAPPER_STATIC_RGCTX_INVOKE:
2942 case MONO_WRAPPER_UNKNOWN:
2945 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
2949 if (!method->token) {
2950 /* The method is part of a constructed type like Int[,].Set (). */
2951 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
2952 if (method->klass->rank)
2960 case MONO_PATCH_INFO_VTABLE:
2961 case MONO_PATCH_INFO_CLASS_INIT:
2962 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2963 case MONO_PATCH_INFO_CLASS:
2964 case MONO_PATCH_INFO_IID:
2965 case MONO_PATCH_INFO_ADJUSTED_IID:
2966 if (!can_encode_class (acfg, patch_info->data.klass)) {
2967 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
2971 case MONO_PATCH_INFO_RGCTX_FETCH: {
2972 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2974 if (!can_encode_patch (acfg, entry->data))
2986 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
2991 * AOT compile a given method.
2992 * This function might be called by multiple threads, so it must be thread-safe.
2995 compile_method (MonoAotCompile *acfg, MonoMethod *method)
2998 MonoJumpInfo *patch_info;
3001 MonoMethod *wrapped;
3003 if (acfg->aot_opts.metadata_only)
3006 mono_acfg_lock (acfg);
3007 index = get_method_index (acfg, method);
3008 mono_acfg_unlock (acfg);
3010 /* fixme: maybe we can also precompile wrapper methods */
3011 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3012 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3013 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3014 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3018 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3021 wrapped = mono_marshal_method_from_wrapper (method);
3022 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
3023 // FIXME: The wrapper should be generic too, but it is not
3026 InterlockedIncrement (&acfg->stats.mcount);
3029 if (method->is_generic || method->klass->generic_container) {
3030 InterlockedIncrement (&acfg->stats.genericcount);
3035 //acfg->aot_opts.print_skipped_methods = TRUE;
3038 * Since these methods are the only ones which are compiled with
3039 * AOT support, and they are not used by runtime startup/shutdown code,
3040 * the runtime will not see AOT methods during AOT compilation,so it
3041 * does not need to support them by creating a fake GOT etc.
3043 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3044 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3045 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3046 InterlockedIncrement (&acfg->stats.genericcount);
3049 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3050 /* Let the exception happen at runtime */
3054 if (cfg->disable_aot) {
3055 if (acfg->aot_opts.print_skipped_methods)
3056 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
3057 InterlockedIncrement (&acfg->stats.ocount);
3058 mono_destroy_compile (cfg);
3062 /* Nullify patches which need no aot processing */
3063 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3064 switch (patch_info->type) {
3065 case MONO_PATCH_INFO_LABEL:
3066 case MONO_PATCH_INFO_BB:
3067 patch_info->type = MONO_PATCH_INFO_NONE;
3074 /* Collect method->token associations from the cfg */
3075 mono_acfg_lock (acfg);
3076 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3077 mono_acfg_unlock (acfg);
3080 * Check for absolute addresses.
3083 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3084 switch (patch_info->type) {
3085 case MONO_PATCH_INFO_ABS:
3086 /* unable to handle this */
3095 if (acfg->aot_opts.print_skipped_methods)
3096 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
3097 InterlockedIncrement (&acfg->stats.abscount);
3098 mono_destroy_compile (cfg);
3102 /* Lock for the rest of the code */
3103 mono_acfg_lock (acfg);
3106 * Check for methods/klasses we can't encode.
3109 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3110 if (!can_encode_patch (acfg, patch_info))
3115 if (acfg->aot_opts.print_skipped_methods)
3116 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
3117 acfg->stats.ocount++;
3118 mono_destroy_compile (cfg);
3119 mono_acfg_unlock (acfg);
3123 /* Adds generic instances referenced by this method */
3124 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3125 switch (patch_info->type) {
3126 case MONO_PATCH_INFO_METHOD: {
3127 MonoMethod *m = patch_info->data.method;
3128 if (m->is_inflated) {
3129 if (!(mono_class_generic_sharing_enabled (m->klass) &&
3130 mono_method_is_generic_sharable_impl (m, FALSE)) &&
3131 !method_has_type_vars (m)) {
3132 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
3133 if (acfg->aot_opts.full_aot)
3134 add_extra_method (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE));
3136 add_extra_method (acfg, m);
3139 add_generic_class (acfg, m->klass);
3148 /* Determine whenever the method has GOT slots */
3149 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3150 switch (patch_info->type) {
3151 case MONO_PATCH_INFO_GOT_OFFSET:
3152 case MONO_PATCH_INFO_NONE:
3154 case MONO_PATCH_INFO_IMAGE:
3155 /* The assembly is stored in GOT slot 0 */
3156 if (patch_info->data.image != acfg->image)
3157 cfg->has_got_slots = TRUE;
3160 if (!is_plt_patch (patch_info))
3161 cfg->has_got_slots = TRUE;
3166 if (!cfg->has_got_slots)
3167 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
3169 /* Make a copy of the patch info which is in the mempool */
3171 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3173 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3174 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3177 patches = new_patch_info;
3179 patches_end->next = new_patch_info;
3180 patches_end = new_patch_info;
3182 cfg->patch_info = patches;
3184 /* Make a copy of the unwind info */
3186 GSList *l, *unwind_ops;
3190 for (l = cfg->unwind_ops; l; l = l->next) {
3191 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
3192 memcpy (op, l->data, sizeof (MonoUnwindOp));
3193 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
3195 cfg->unwind_ops = g_slist_reverse (unwind_ops);
3197 /* Make a copy of the argument/local info */
3199 MonoInst **args, **locals;
3200 MonoMethodSignature *sig;
3201 MonoMethodHeader *header;
3204 sig = mono_method_signature (method);
3205 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
3206 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
3207 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3208 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
3212 header = mono_method_get_header (method);
3213 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
3214 for (i = 0; i < header->num_locals; ++i) {
3215 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3216 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
3218 cfg->locals = locals;
3221 /* Free some fields used by cfg to conserve memory */
3222 mono_mempool_destroy (cfg->mempool);
3223 cfg->mempool = NULL;
3224 g_free (cfg->varinfo);
3225 cfg->varinfo = NULL;
3229 mono_regstate_free (cfg->rs);
3233 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
3235 while (index >= acfg->cfgs_size) {
3236 MonoCompile **new_cfgs;
3239 new_size = acfg->cfgs_size * 2;
3240 new_cfgs = g_new0 (MonoCompile*, new_size);
3241 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
3242 g_free (acfg->cfgs);
3243 acfg->cfgs = new_cfgs;
3244 acfg->cfgs_size = new_size;
3246 acfg->cfgs [index] = cfg;
3248 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
3250 if (cfg->orig_method->wrapper_type)
3251 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
3253 mono_acfg_unlock (acfg);
3255 InterlockedIncrement (&acfg->stats.ccount);
3259 compile_thread_main (gpointer *user_data)
3261 MonoDomain *domain = user_data [0];
3262 MonoAotCompile *acfg = user_data [1];
3263 GPtrArray *methods = user_data [2];
3266 mono_thread_attach (domain);
3268 for (i = 0; i < methods->len; ++i)
3269 compile_method (acfg, g_ptr_array_index (methods, i));
3273 load_profile_files (MonoAotCompile *acfg)
3277 int file_index, res, method_index, i;
3284 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);
3286 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
3291 infile = fopen (tmp, "r");
3294 printf ("Using profile data file '%s'\n", tmp);
3299 res = fscanf (infile, "%32s\n", ver);
3300 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
3301 printf ("Profile file has wrong version or invalid.\n");
3307 res = fscanf (infile, "%d\n", &token);
3311 method_index = mono_metadata_token_index (token) - 1;
3313 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
3314 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
3319 /* Add missing methods */
3321 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3322 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
3323 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
3325 unordered = g_list_reverse (unordered);
3326 if (acfg->method_order)
3327 g_list_last (acfg->method_order)->next = unordered;
3329 acfg->method_order = unordered;
3335 * Collect all patches which have shared GOT entries and alloc entries for them. The
3336 * rest will get entries allocated during emit_code ().
3339 alloc_got_slots (MonoAotCompile *acfg)
3345 /* Slot 0 is reserved for the address of the current assembly */
3346 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
3347 ji->type = MONO_PATCH_INFO_IMAGE;
3348 ji->data.image = acfg->image;
3350 get_shared_got_offset (acfg, ji);
3352 for (l = acfg->method_order; l != NULL; l = l->next) {
3353 i = GPOINTER_TO_UINT (l->data);
3355 if (acfg->cfgs [i]) {
3356 MonoCompile *cfg = acfg->cfgs [i];
3358 for (ji = cfg->patch_info; ji; ji = ji->next) {
3359 if (mono_aot_is_shared_got_patch (ji))
3360 get_shared_got_offset (acfg, ji);
3367 emit_code (MonoAotCompile *acfg)
3373 sprintf (symbol, "methods");
3374 emit_section_change (acfg, ".text", 0);
3375 emit_global (acfg, symbol, TRUE);
3376 emit_alignment (acfg, 8);
3377 emit_label (acfg, symbol);
3380 * Emit some padding so the local symbol for the first method doesn't have the
3381 * same address as 'methods'.
3383 emit_zero_bytes (acfg, 16);
3385 for (l = acfg->method_order; l != NULL; l = l->next) {
3386 i = GPOINTER_TO_UINT (l->data);
3389 emit_method_code (acfg, acfg->cfgs [i]);
3392 sprintf (symbol, "methods_end");
3393 emit_section_change (acfg, ".text", 0);
3394 emit_global (acfg, symbol, FALSE);
3395 emit_alignment (acfg, 8);
3396 emit_label (acfg, symbol);
3398 sprintf (symbol, "method_offsets");
3399 emit_section_change (acfg, ".text", 1);
3400 emit_global (acfg, symbol, FALSE);
3401 emit_alignment (acfg, 8);
3402 emit_label (acfg, symbol);
3404 for (i = 0; i < acfg->nmethods; ++i) {
3405 if (acfg->cfgs [i]) {
3406 sprintf (symbol, ".Lm_%x", i);
3407 emit_symbol_diff (acfg, symbol, "methods", 0);
3409 emit_int32 (acfg, 0xffffffff);
3416 emit_info (MonoAotCompile *acfg)
3422 /* Emit method info */
3423 sprintf (symbol, "method_info");
3424 emit_section_change (acfg, ".text", 1);
3425 emit_global (acfg, symbol, FALSE);
3426 emit_alignment (acfg, 8);
3427 emit_label (acfg, symbol);
3429 /* To reduce size of generated assembly code */
3430 sprintf (symbol, "mi");
3431 emit_label (acfg, symbol);
3433 for (l = acfg->method_order; l != NULL; l = l->next) {
3434 i = GPOINTER_TO_UINT (l->data);
3437 emit_method_info (acfg, acfg->cfgs [i]);
3440 sprintf (symbol, "method_info_offsets");
3441 emit_section_change (acfg, ".text", 1);
3442 emit_global (acfg, symbol, FALSE);
3443 emit_alignment (acfg, 8);
3444 emit_label (acfg, symbol);
3446 for (i = 0; i < acfg->nmethods; ++i) {
3447 if (acfg->cfgs [i]) {
3448 sprintf (symbol, ".Lm_%x_p", i);
3449 emit_symbol_diff (acfg, symbol, "mi", 0);
3451 emit_int32 (acfg, 0);
3457 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
3460 * mono_aot_str_hash:
3462 * Hash function for strings which we use to hash strings for things which are
3463 * saved in the AOT image, since g_str_hash () can change.
3466 mono_aot_str_hash (gconstpointer v1)
3468 /* Same as g_str_hash () in glib */
3469 char *p = (char *) v1;
3474 hash = (hash << 5) - hash + *p;
3480 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
3481 #define mix(a,b,c) { \
3482 a -= c; a ^= rot(c, 4); c += b; \
3483 b -= a; b ^= rot(a, 6); a += c; \
3484 c -= b; c ^= rot(b, 8); b += a; \
3485 a -= c; a ^= rot(c,16); c += b; \
3486 b -= a; b ^= rot(a,19); a += c; \
3487 c -= b; c ^= rot(b, 4); b += a; \
3489 #define final(a,b,c) { \
3490 c ^= b; c -= rot(b,14); \
3491 a ^= c; a -= rot(c,11); \
3492 b ^= a; b -= rot(a,25); \
3493 c ^= b; c -= rot(b,16); \
3494 a ^= c; a -= rot(c,4); \
3495 b ^= a; b -= rot(a,14); \
3496 c ^= b; c -= rot(b,24); \
3500 mono_aot_type_hash (MonoType *t1)
3502 guint hash = t1->type;
3504 hash |= t1->byref << 6; /* do not collide with t1->type values */
3506 case MONO_TYPE_VALUETYPE:
3507 case MONO_TYPE_CLASS:
3508 case MONO_TYPE_SZARRAY:
3509 /* check if the distribution is good enough */
3510 return ((hash << 5) - hash) ^ mono_aot_str_hash (t1->data.klass->name);
3512 return ((hash << 5) - hash) ^ mono_aot_type_hash (t1->data.type);
3513 case MONO_TYPE_ARRAY:
3514 return ((hash << 5) - hash) ^ mono_aot_type_hash (&t1->data.array->eklass->byval_arg);
3515 case MONO_TYPE_GENERICINST:
3516 return ((hash << 5) - hash) ^ 0;
3522 * mono_aot_method_hash:
3524 * Return a hash code for methods which only depends on metadata.
3527 mono_aot_method_hash (MonoMethod *method)
3529 MonoMethodSignature *sig;
3533 guint32 *hashes_start, *hashes;
3536 /* Similar to the hash in mono_method_get_imt_slot () */
3538 sig = mono_method_signature (method);
3540 hashes_count = sig->param_count + 5;
3541 hashes_start = malloc (hashes_count * sizeof (guint32));
3542 hashes = hashes_start;
3544 /* Some wrappers are assigned to random classes */
3545 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
3546 klass = method->klass;
3548 klass = mono_defaults.object_class;
3550 if (!method->wrapper_type) {
3551 char *full_name = mono_type_full_name (&klass->byval_arg);
3553 hashes [0] = mono_aot_str_hash (full_name);
3557 hashes [0] = mono_aot_str_hash (klass->name);
3558 hashes [1] = mono_aot_str_hash (klass->name_space);
3560 hashes [2] = mono_aot_str_hash (method->name);
3561 hashes [3] = method->wrapper_type;
3562 hashes [4] = mono_aot_type_hash (sig->ret);
3563 for (i = 0; i < sig->param_count; i++) {
3564 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
3567 /* Setup internal state */
3568 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
3570 /* Handle most of the hashes */
3571 while (hashes_count > 3) {
3580 /* Handle the last 3 hashes (all the case statements fall through) */
3581 switch (hashes_count) {
3582 case 3 : c += hashes [2];
3583 case 2 : b += hashes [1];
3584 case 1 : a += hashes [0];
3586 case 0: /* nothing left to add */
3590 free (hashes_start);
3599 * mono_aot_wrapper_name:
3601 * Return a string which uniqely identifies the given wrapper method.
3604 mono_aot_wrapper_name (MonoMethod *method)
3606 char *name, *tmpsig, *klass_desc;
3608 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
3610 switch (method->wrapper_type) {
3611 case MONO_WRAPPER_RUNTIME_INVOKE:
3612 case MONO_WRAPPER_DELEGATE_INVOKE:
3613 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
3614 case MONO_WRAPPER_DELEGATE_END_INVOKE:
3615 /* This is a hack to work around the fact that runtime invoke wrappers get assigned to some random class */
3616 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
3619 klass_desc = mono_type_full_name (&method->klass->byval_arg);
3621 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
3631 * mono_aot_tramp_info_create:
3633 * Create a MonoAotTrampInfo structure from the arguments.
3636 mono_aot_tramp_info_create (const char *name, guint8 *code, guint32 code_size)
3638 MonoAotTrampInfo *info = g_new0 (MonoAotTrampInfo, 1);
3640 info->name = (char*)name;
3642 info->code_size = code_size;
3648 * mono_is_shared_got_patch:
3650 * Return whenever PATCH_INFO refers to a patch which needs a shared GOT
3654 mono_aot_is_shared_got_patch (MonoJumpInfo *patch_info)
3656 switch (patch_info->type) {
3657 case MONO_PATCH_INFO_VTABLE:
3658 case MONO_PATCH_INFO_CLASS:
3659 case MONO_PATCH_INFO_IID:
3660 case MONO_PATCH_INFO_ADJUSTED_IID:
3661 case MONO_PATCH_INFO_FIELD:
3662 case MONO_PATCH_INFO_SFLDA:
3663 case MONO_PATCH_INFO_DECLSEC:
3664 case MONO_PATCH_INFO_LDTOKEN:
3665 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3666 case MONO_PATCH_INFO_RVA:
3667 case MONO_PATCH_INFO_METHODCONST:
3668 case MONO_PATCH_INFO_IMAGE:
3675 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
3677 typedef struct HashEntry {
3678 guint32 key, value, index;
3679 struct HashEntry *next;
3683 * emit_extra_methods:
3685 * Emit methods which are not in the METHOD table, like wrappers.
3688 emit_extra_methods (MonoAotCompile *acfg)
3690 int i, table_size, buf_size;
3693 guint32 *info_offsets;
3696 HashEntry *entry, *new_entry;
3697 int nmethods, max_chain_length;
3700 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
3702 buf_size = acfg->extra_methods->len * 256 + 256;
3703 p = buf = g_malloc (buf_size);
3705 /* Encode method info */
3707 /* So offsets are > 0 */
3710 for (i = 0; i < acfg->extra_methods->len; ++i) {
3711 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3712 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3719 info_offsets [i] = p - buf;
3722 if (method->wrapper_type) {
3724 * We encode some wrappers using their name, since encoding them
3725 * directly would be difficult. This also avoids creating the wrapper
3726 * methods at runtime, since they are not needed anyway.
3728 switch (method->wrapper_type) {
3729 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3730 case MONO_WRAPPER_SYNCHRONIZED:
3731 /* encode_method_ref () can handle these */
3734 name = mono_aot_wrapper_name (method);
3740 encode_value (1, p, &p);
3741 encode_value (method->wrapper_type, p, &p);
3742 strcpy ((char*)p, name);
3743 p += strlen (name ) + 1;
3746 encode_value (0, p, &p);
3747 encode_method_ref (acfg, method, p, &p);
3750 g_assert ((p - buf) < buf_size);
3753 g_assert ((p - buf) < buf_size);
3755 /* Emit method info */
3756 sprintf (symbol, "extra_method_info");
3757 emit_section_change (acfg, ".text", 1);
3758 emit_global (acfg, symbol, FALSE);
3759 emit_alignment (acfg, 8);
3760 emit_label (acfg, symbol);
3762 emit_bytes (acfg, buf, p - buf);
3767 * Construct a chained hash table for mapping indexes in extra_method_info to
3770 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
3771 table = g_ptr_array_sized_new (table_size);
3772 for (i = 0; i < table_size; ++i)
3773 g_ptr_array_add (table, NULL);
3774 chain_lengths = g_new0 (int, table_size);
3775 max_chain_length = 0;
3776 for (i = 0; i < acfg->extra_methods->len; ++i) {
3777 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3778 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
3784 key = info_offsets [i];
3785 value = get_method_index (acfg, method);
3787 hash = mono_aot_method_hash (method) % table_size;
3789 chain_lengths [hash] ++;
3790 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
3792 /* FIXME: Allocate from the mempool */
3793 new_entry = g_new0 (HashEntry, 1);
3794 new_entry->key = key;
3795 new_entry->value = value;
3797 entry = g_ptr_array_index (table, hash);
3798 if (entry == NULL) {
3799 new_entry->index = hash;
3800 g_ptr_array_index (table, hash) = new_entry;
3803 entry = entry->next;
3805 entry->next = new_entry;
3806 new_entry->index = table->len;
3807 g_ptr_array_add (table, new_entry);
3811 //printf ("MAX: %d\n", max_chain_length);
3813 /* Emit the table */
3814 sprintf (symbol, "extra_method_table");
3815 emit_section_change (acfg, ".text", 0);
3816 emit_global (acfg, symbol, FALSE);
3817 emit_alignment (acfg, 8);
3818 emit_label (acfg, symbol);
3820 g_assert (table_size < 65000);
3821 emit_int32 (acfg, table_size);
3822 g_assert (table->len < 65000);
3823 for (i = 0; i < table->len; ++i) {
3824 HashEntry *entry = g_ptr_array_index (table, i);
3826 if (entry == NULL) {
3827 emit_int32 (acfg, 0);
3828 emit_int32 (acfg, 0);
3829 emit_int32 (acfg, 0);
3831 g_assert (entry->key > 0);
3832 emit_int32 (acfg, entry->key);
3833 emit_int32 (acfg, entry->value);
3835 emit_int32 (acfg, entry->next->index);
3837 emit_int32 (acfg, 0);
3842 * Emit a table reverse mapping method indexes to their index in extra_method_info.
3843 * This is used by mono_aot_find_jit_info ().
3845 sprintf (symbol, "extra_method_info_offsets");
3846 emit_section_change (acfg, ".text", 0);
3847 emit_global (acfg, symbol, FALSE);
3848 emit_alignment (acfg, 8);
3849 emit_label (acfg, symbol);
3851 emit_int32 (acfg, acfg->extra_methods->len);
3852 for (i = 0; i < acfg->extra_methods->len; ++i) {
3853 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
3855 emit_int32 (acfg, get_method_index (acfg, method));
3856 emit_int32 (acfg, info_offsets [i]);
3861 emit_method_order (MonoAotCompile *acfg)
3867 sprintf (symbol, "method_order");
3868 emit_section_change (acfg, ".text", 1);
3869 emit_global (acfg, symbol, FALSE);
3870 emit_alignment (acfg, 8);
3871 emit_label (acfg, symbol);
3873 /* First emit an index table */
3876 for (l = acfg->method_order; l != NULL; l = l->next) {
3877 i = GPOINTER_TO_UINT (l->data);
3879 if (acfg->cfgs [i]) {
3880 if ((index % 1024) == 0) {
3881 emit_int32 (acfg, i);
3889 emit_int32 (acfg, 0xffffff);
3891 /* Then emit the whole method order */
3892 for (l = acfg->method_order; l != NULL; l = l->next) {
3893 i = GPOINTER_TO_UINT (l->data);
3895 if (acfg->cfgs [i]) {
3896 emit_int32 (acfg, i);
3901 sprintf (symbol, "method_order_end");
3902 emit_section_change (acfg, ".text", 1);
3903 emit_global (acfg, symbol, FALSE);
3904 emit_label (acfg, symbol);
3908 emit_exception_info (MonoAotCompile *acfg)
3913 sprintf (symbol, "ex_info");
3914 emit_section_change (acfg, ".text", 1);
3915 emit_global (acfg, symbol, FALSE);
3916 emit_alignment (acfg, 8);
3917 emit_label (acfg, symbol);
3919 /* To reduce size of generated assembly */
3920 sprintf (symbol, "ex");
3921 emit_label (acfg, symbol);
3923 for (i = 0; i < acfg->nmethods; ++i) {
3925 emit_exception_debug_info (acfg, acfg->cfgs [i]);
3928 sprintf (symbol, "ex_info_offsets");
3929 emit_section_change (acfg, ".text", 1);
3930 emit_global (acfg, symbol, FALSE);
3931 emit_alignment (acfg, 8);
3932 emit_label (acfg, symbol);
3934 for (i = 0; i < acfg->nmethods; ++i) {
3935 if (acfg->cfgs [i]) {
3936 sprintf (symbol, ".Le_%x_p", i);
3937 emit_symbol_diff (acfg, symbol, "ex", 0);
3939 emit_int32 (acfg, 0);
3946 emit_unwind_info (MonoAotCompile *acfg)
3952 * The unwind info contains a lot of duplicates so we emit each unique
3953 * entry once, and only store the offset from the start of the table in the
3957 sprintf (symbol, "unwind_info");
3958 emit_section_change (acfg, ".text", 1);
3959 emit_alignment (acfg, 8);
3960 emit_label (acfg, symbol);
3961 emit_global (acfg, symbol, FALSE);
3963 for (i = 0; i < acfg->unwind_ops->len; ++i) {
3964 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
3965 guint8 *unwind_info;
3966 guint32 unwind_info_len;
3970 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
3973 encode_value (unwind_info_len, p, &p);
3974 emit_bytes (acfg, buf, p - buf);
3975 emit_bytes (acfg, unwind_info, unwind_info_len);
3977 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
3982 emit_class_info (MonoAotCompile *acfg)
3987 sprintf (symbol, "class_info");
3988 emit_section_change (acfg, ".text", 1);
3989 emit_global (acfg, symbol, FALSE);
3990 emit_alignment (acfg, 8);
3991 emit_label (acfg, symbol);
3993 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
3994 emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
3996 sprintf (symbol, "class_info_offsets");
3997 emit_section_change (acfg, ".text", 1);
3998 emit_global (acfg, symbol, FALSE);
3999 emit_alignment (acfg, 8);
4000 emit_label (acfg, symbol);
4002 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4003 sprintf (symbol, ".LK_I_%x", i);
4004 emit_symbol_diff (acfg, symbol, "class_info", 0);
4009 typedef struct ClassNameTableEntry {
4010 guint32 token, index;
4011 struct ClassNameTableEntry *next;
4012 } ClassNameTableEntry;
4015 emit_class_name_table (MonoAotCompile *acfg)
4018 guint32 token, hash;
4023 ClassNameTableEntry *entry, *new_entry;
4026 * Construct a chained hash table for mapping class names to typedef tokens.
4028 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4029 table = g_ptr_array_sized_new (table_size);
4030 for (i = 0; i < table_size; ++i)
4031 g_ptr_array_add (table, NULL);
4032 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4033 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4034 klass = mono_class_get (acfg->image, token);
4035 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4036 hash = mono_aot_str_hash (full_name) % table_size;
4039 /* FIXME: Allocate from the mempool */
4040 new_entry = g_new0 (ClassNameTableEntry, 1);
4041 new_entry->token = token;
4043 entry = g_ptr_array_index (table, hash);
4044 if (entry == NULL) {
4045 new_entry->index = hash;
4046 g_ptr_array_index (table, hash) = new_entry;
4049 entry = entry->next;
4051 entry->next = new_entry;
4052 new_entry->index = table->len;
4053 g_ptr_array_add (table, new_entry);
4057 /* Emit the table */
4058 sprintf (symbol, "class_name_table");
4059 emit_section_change (acfg, ".text", 0);
4060 emit_global (acfg, symbol, FALSE);
4061 emit_alignment (acfg, 8);
4062 emit_label (acfg, symbol);
4064 /* FIXME: Optimize memory usage */
4065 g_assert (table_size < 65000);
4066 emit_int16 (acfg, table_size);
4067 g_assert (table->len < 65000);
4068 for (i = 0; i < table->len; ++i) {
4069 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4071 if (entry == NULL) {
4072 emit_int16 (acfg, 0);
4073 emit_int16 (acfg, 0);
4075 emit_int16 (acfg, mono_metadata_token_index (entry->token));
4077 emit_int16 (acfg, entry->next->index);
4079 emit_int16 (acfg, 0);
4085 emit_image_table (MonoAotCompile *acfg)
4091 * The image table is small but referenced in a lot of places.
4092 * So we emit it at once, and reference its elements by an index.
4095 sprintf (symbol, "mono_image_table");
4096 emit_section_change (acfg, ".text", 1);
4097 emit_global (acfg, symbol, FALSE);
4098 emit_alignment (acfg, 8);
4099 emit_label (acfg, symbol);
4101 emit_int32 (acfg, acfg->image_table->len);
4102 for (i = 0; i < acfg->image_table->len; i++) {
4103 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4104 MonoAssemblyName *aname = &image->assembly->aname;
4106 /* FIXME: Support multi-module assemblies */
4107 g_assert (image->assembly->image == image);
4109 emit_string (acfg, image->assembly_name);
4110 emit_string (acfg, image->guid);
4111 emit_string (acfg, aname->culture ? aname->culture : "");
4112 emit_string (acfg, (const char*)aname->public_key_token);
4114 emit_alignment (acfg, 8);
4115 emit_int32 (acfg, aname->flags);
4116 emit_int32 (acfg, aname->major);
4117 emit_int32 (acfg, aname->minor);
4118 emit_int32 (acfg, aname->build);
4119 emit_int32 (acfg, aname->revision);
4124 emit_got_info (MonoAotCompile *acfg)
4127 int i, first_plt_got_patch, buf_size;
4129 guint32 *got_info_offsets;
4131 /* Add the patches needed by the PLT to the GOT */
4132 acfg->plt_got_offset_base = acfg->got_offset;
4133 first_plt_got_patch = acfg->shared_patches->len;
4134 for (i = 1; i < acfg->plt_offset; ++i) {
4135 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
4137 g_ptr_array_add (acfg->shared_patches, patch_info);
4140 acfg->got_offset += acfg->plt_offset;
4144 * - optimize offsets table.
4145 * - reduce number of exported symbols.
4146 * - emit info for a klass only once.
4147 * - determine when a method uses a GOT slot which is guaranteed to be already
4149 * - clean up and document the code.
4150 * - use String.Empty in class libs.
4153 /* Encode info required to decode shared GOT entries */
4154 buf_size = acfg->shared_patches->len * 64;
4155 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
4156 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->shared_patches->len * sizeof (guint32));
4157 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
4158 for (i = 0; i < acfg->shared_patches->len; ++i) {
4159 MonoJumpInfo *ji = g_ptr_array_index (acfg->shared_patches, i);
4161 got_info_offsets [i] = p - buf;
4162 /* No need to encode the patch type for non-PLT patches */
4163 if (i >= first_plt_got_patch) {
4164 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
4165 encode_value (ji->type, p, &p);
4167 encode_patch (acfg, ji, p, &p);
4170 g_assert (p - buf <= buf_size);
4172 acfg->stats.got_info_size = p - buf;
4174 /* Emit got_info table */
4175 sprintf (symbol, "got_info");
4176 emit_section_change (acfg, ".text", 1);
4177 emit_global (acfg, symbol, FALSE);
4178 emit_alignment (acfg, 8);
4179 emit_label (acfg, symbol);
4181 emit_bytes (acfg, buf, p - buf);
4183 /* Emit got_info_offsets table */
4184 sprintf (symbol, "got_info_offsets");
4185 emit_section_change (acfg, ".text", 1);
4186 emit_global (acfg, symbol, FALSE);
4187 emit_alignment (acfg, 8);
4188 emit_label (acfg, symbol);
4190 for (i = 0; i < acfg->shared_patches->len; ++i)
4191 emit_int32 (acfg, got_info_offsets [i]);
4193 acfg->stats.got_info_offsets_size = acfg->shared_patches->len * 4;
4197 emit_got (MonoAotCompile *acfg)
4201 /* Don't make GOT global so accesses to it don't need relocations */
4202 sprintf (symbol, acfg->got_symbol);
4203 emit_section_change (acfg, ".bss", 0);
4204 emit_alignment (acfg, 8);
4205 emit_local_symbol (acfg, symbol, "got_end", FALSE);
4206 emit_label (acfg, symbol);
4207 if (acfg->got_offset > 0)
4208 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4210 sprintf (symbol, "got_end");
4211 emit_label (acfg, symbol);
4213 sprintf (symbol, "mono_aot_got_addr");
4214 emit_section_change (acfg, ".data", 0);
4215 emit_global (acfg, symbol, FALSE);
4216 emit_alignment (acfg, 8);
4217 emit_label (acfg, symbol);
4218 emit_pointer (acfg, acfg->got_symbol);
4222 emit_globals (MonoAotCompile *acfg)
4227 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
4229 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
4231 opts_str = g_strdup_printf ("%d", acfg->opts);
4232 emit_string_symbol (acfg, "mono_aot_opt_flags", opts_str);
4235 emit_string_symbol (acfg, "mono_aot_full_aot", acfg->aot_opts.full_aot ? "TRUE" : "FALSE");
4237 if (acfg->aot_opts.bind_to_runtime_version) {
4238 build_info = mono_get_runtime_build_info ();
4239 emit_string_symbol (acfg, "mono_runtime_version", build_info);
4240 g_free (build_info);
4242 emit_string_symbol (acfg, "mono_runtime_version", "");
4246 * When static linking, we emit a global which will point to the symbol table.
4248 if (acfg->aot_opts.static_link) {
4253 /* Emit a string holding the assembly name */
4254 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
4256 /* Emit the names */
4257 for (i = 0; i < acfg->globals->len; ++i) {
4258 char *name = g_ptr_array_index (acfg->globals, i);
4260 sprintf (symbol, "name_%d", i);
4261 emit_section_change (acfg, ".text", 1);
4262 emit_label (acfg, symbol);
4263 emit_string (acfg, name);
4266 /* Emit the globals table */
4267 sprintf (symbol, "globals");
4268 emit_section_change (acfg, ".data", 0);
4269 /* This is not a global, since it is accessed by the init function */
4270 emit_alignment (acfg, 8);
4271 emit_label (acfg, symbol);
4273 for (i = 0; i < acfg->globals->len; ++i) {
4274 char *name = g_ptr_array_index (acfg->globals, i);
4276 sprintf (symbol, "name_%d", i);
4277 emit_pointer (acfg, symbol);
4279 sprintf (symbol, "%s", name);
4280 emit_pointer (acfg, symbol);
4282 /* Null terminate the table */
4283 emit_int32 (acfg, 0);
4284 emit_int32 (acfg, 0);
4287 * Emit a global symbol which can be passed by an embedding app to
4288 * mono_aot_register_module ().
4290 #if defined(__MACH__)
4291 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4293 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
4296 /* Get rid of characters which cannot occur in symbols */
4298 for (p = symbol; *p; ++p) {
4299 if (!(isalnum (*p) || *p == '_'))
4302 acfg->static_linking_symbol = g_strdup (symbol);
4303 emit_global_inner (acfg, symbol, FALSE);
4304 emit_alignment (acfg, 8);
4305 emit_label (acfg, symbol);
4306 emit_pointer (acfg, "globals");
4311 emit_mem_end (MonoAotCompile *acfg)
4315 sprintf (symbol, "mem_end");
4316 emit_section_change (acfg, ".text", 1);
4317 emit_global (acfg, symbol, FALSE);
4318 emit_alignment (acfg, 8);
4319 emit_label (acfg, symbol);
4323 * Emit a structure containing all the information not stored elsewhere.
4326 emit_file_info (MonoAotCompile *acfg)
4331 sprintf (symbol, "mono_aot_file_info");
4332 emit_section_change (acfg, ".data", 0);
4333 emit_alignment (acfg, 8);
4334 emit_label (acfg, symbol);
4335 emit_global (acfg, symbol, FALSE);
4337 /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
4338 emit_int32 (acfg, acfg->plt_got_offset_base);
4339 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
4340 emit_int32 (acfg, acfg->plt_offset);
4342 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4343 emit_int32 (acfg, acfg->num_trampolines [i]);
4344 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4345 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
4346 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
4347 emit_int32 (acfg, acfg->trampoline_size [i]);
4351 emit_dwarf_info (MonoAotCompile *acfg)
4353 #ifdef EMIT_DWARF_INFO
4355 char symbol [128], symbol2 [128];
4357 /* DIEs for methods */
4358 for (i = 0; i < acfg->nmethods; ++i) {
4359 MonoCompile *cfg = acfg->cfgs [i];
4364 sprintf (symbol, ".Lm_%x", i);
4365 sprintf (symbol2, ".Lme_%x", i);
4367 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, symbol, symbol2, NULL, 0, cfg->args, cfg->locals, cfg->unwind_ops, NULL);
4373 collect_methods (MonoAotCompile *acfg)
4376 MonoImage *image = acfg->image;
4378 /* Collect methods */
4379 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
4381 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
4383 method = mono_get_method (acfg->image, token, NULL);
4386 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
4390 /* Load all methods eagerly to skip the slower lazy loading code */
4391 mono_class_setup_methods (method->klass);
4393 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4394 /* Compile the wrapper instead */
4395 /* We do this here instead of add_wrappers () because it is easy to do it here */
4396 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
4400 /* Since we add the normal methods first, their index will be equal to their zero based token index */
4401 add_method_with_index (acfg, method, i);
4402 acfg->method_index ++;
4405 add_generic_instances (acfg);
4407 if (acfg->aot_opts.full_aot)
4408 add_wrappers (acfg);
4412 compile_methods (MonoAotCompile *acfg)
4416 if (acfg->aot_opts.nthreads > 0) {
4421 gpointer *user_data;
4422 MonoMethod **methods;
4424 methods_len = acfg->methods->len;
4426 len = acfg->methods->len / acfg->aot_opts.nthreads;
4429 * Partition the list of methods into fragments, and hand it to threads to
4432 threads = g_ptr_array_new ();
4433 /* Make a copy since acfg->methods is modified by compile_method () */
4434 methods = g_new0 (MonoMethod*, methods_len);
4435 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
4436 for (i = 0; i < methods_len; ++i)
4437 methods [i] = g_ptr_array_index (acfg->methods, i);
4439 while (i < methods_len) {
4440 frag = g_ptr_array_new ();
4441 for (j = 0; j < len; ++j) {
4442 if (i < methods_len) {
4443 g_ptr_array_add (frag, methods [i]);
4448 user_data = g_new0 (gpointer, 3);
4449 user_data [0] = mono_domain_get ();
4450 user_data [1] = acfg;
4451 user_data [2] = frag;
4453 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
4454 g_ptr_array_add (threads, handle);
4458 for (i = 0; i < threads->len; ++i) {
4459 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
4465 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
4466 for (i = methods_len; i < acfg->methods->len; ++i) {
4467 /* This can new methods to acfg->methods */
4468 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
4473 compile_asm (MonoAotCompile *acfg)
4475 char *command, *objfile;
4476 char *outfile_name, *tmp_outfile_name;
4478 #if defined(TARGET_AMD64)
4479 #define AS_OPTIONS "--64"
4480 #elif defined(sparc) && SIZEOF_VOID_P == 8
4481 #define AS_OPTIONS "-xarch=v9"
4483 #define AS_OPTIONS ""
4486 if (acfg->aot_opts.asm_only) {
4487 printf ("Output file: '%s'.\n", acfg->tmpfname);
4488 if (acfg->aot_opts.static_link)
4489 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
4493 if (acfg->aot_opts.static_link) {
4494 if (acfg->aot_opts.outfile)
4495 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4497 objfile = g_strdup_printf ("%s.o", acfg->image->name);
4499 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
4501 command = g_strdup_printf ("as %s %s -o %s", AS_OPTIONS, acfg->tmpfname, objfile);
4502 printf ("Executing the native assembler: %s\n", command);
4503 if (system (command) != 0) {
4511 if (acfg->aot_opts.static_link) {
4512 printf ("Output file: '%s'.\n", objfile);
4513 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
4518 if (acfg->aot_opts.outfile)
4519 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4521 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
4523 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
4526 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4527 #elif defined(__ppc__) && defined(__MACH__)
4528 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4529 #elif defined(PLATFORM_WIN32)
4530 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4532 command = g_strdup_printf ("ld -shared -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
4534 printf ("Executing the native linker: %s\n", command);
4535 if (system (command) != 0) {
4536 g_free (tmp_outfile_name);
4537 g_free (outfile_name);
4545 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
4546 printf ("Stripping the binary: %s\n", com);
4550 #if defined(TARGET_ARM) && !defined(__MACH__)
4552 * gas generates 'mapping symbols' each time code and data is mixed, which
4553 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
4555 command = g_strdup_printf ("strip --strip-symbol=\\$a --strip-symbol=\\$d %s", tmp_outfile_name);
4556 printf ("Stripping the binary: %s\n", command);
4557 if (system (command) != 0) {
4558 g_free (tmp_outfile_name);
4559 g_free (outfile_name);
4566 rename (tmp_outfile_name, outfile_name);
4568 g_free (tmp_outfile_name);
4569 g_free (outfile_name);
4572 if (acfg->aot_opts.save_temps)
4573 printf ("Retained input file.\n");
4575 unlink (acfg->tmpfname);
4580 static MonoAotCompile*
4581 acfg_create (MonoAssembly *ass, guint32 opts)
4583 MonoImage *image = ass->image;
4584 MonoAotCompile *acfg;
4586 acfg = g_new0 (MonoAotCompile, 1);
4587 acfg->methods = g_ptr_array_new ();
4588 acfg->method_indexes = g_hash_table_new (NULL, NULL);
4589 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
4590 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4591 acfg->patch_to_shared_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
4592 acfg->shared_patches = g_ptr_array_new ();
4593 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
4594 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
4595 acfg->image_hash = g_hash_table_new (NULL, NULL);
4596 acfg->image_table = g_ptr_array_new ();
4597 acfg->globals = g_ptr_array_new ();
4598 acfg->image = image;
4600 acfg->mempool = mono_mempool_new ();
4601 acfg->extra_methods = g_ptr_array_new ();
4602 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
4603 acfg->unwind_ops = g_ptr_array_new ();
4604 InitializeCriticalSection (&acfg->mutex);
4610 acfg_free (MonoAotCompile *acfg)
4614 img_writer_destroy (acfg->w);
4615 for (i = 0; i < acfg->nmethods; ++i)
4617 g_free (acfg->cfgs [i]);
4618 g_free (acfg->cfgs);
4619 g_free (acfg->static_linking_symbol);
4620 g_ptr_array_free (acfg->methods, TRUE);
4621 g_ptr_array_free (acfg->shared_patches, TRUE);
4622 g_ptr_array_free (acfg->image_table, TRUE);
4623 g_ptr_array_free (acfg->globals, TRUE);
4624 g_ptr_array_free (acfg->unwind_ops, TRUE);
4625 g_hash_table_destroy (acfg->method_indexes);
4626 g_hash_table_destroy (acfg->plt_offset_to_patch);
4627 g_hash_table_destroy (acfg->patch_to_plt_offset);
4628 g_hash_table_destroy (acfg->patch_to_shared_got_offset);
4629 g_hash_table_destroy (acfg->method_to_cfg);
4630 g_hash_table_destroy (acfg->token_info_hash);
4631 g_hash_table_destroy (acfg->image_hash);
4632 g_hash_table_destroy (acfg->unwind_info_offsets);
4633 mono_mempool_destroy (acfg->mempool);
4638 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4640 MonoImage *image = ass->image;
4642 MonoAotCompile *acfg;
4643 char *outfile_name, *tmp_outfile_name, *p;
4647 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
4649 acfg = acfg_create (ass, opts);
4651 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
4652 acfg->aot_opts.write_symbols = TRUE;
4653 acfg->aot_opts.ntrampolines = 10240;
4655 mono_aot_parse_options (aot_options, &acfg->aot_opts);
4657 //acfg->aot_opts.print_skipped_methods = TRUE;
4659 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4660 if (acfg->aot_opts.full_aot) {
4661 printf ("--aot=full is not supported on this platform.\n");
4666 if (acfg->aot_opts.static_link)
4667 acfg->aot_opts.asm_writer = TRUE;
4669 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
4670 if (acfg->aot_opts.outfile)
4671 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4673 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
4675 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
4677 acfg->fp = fopen (tmp_outfile_name, "w");
4678 g_assert (acfg->fp);
4680 acfg->w = img_writer_create (acfg->fp, TRUE);
4681 acfg->use_bin_writer = TRUE;
4683 if (acfg->aot_opts.asm_only) {
4684 if (acfg->aot_opts.outfile)
4685 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
4687 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
4688 acfg->fp = fopen (acfg->tmpfname, "w+");
4690 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
4691 acfg->fp = fdopen (i, "w+");
4693 g_assert (acfg->fp);
4695 acfg->w = img_writer_create (acfg->fp, FALSE);
4697 tmp_outfile_name = NULL;
4698 outfile_name = NULL;
4701 load_profile_files (acfg);
4703 if (!acfg->aot_opts.nodebug)
4704 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL);
4706 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
4707 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
4708 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? 1024 : 0;
4710 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? 128 : 0;
4712 acfg->got_symbol = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
4714 /* Get rid of characters which cannot occur in symbols */
4715 p = acfg->got_symbol;
4716 for (p = acfg->got_symbol; *p; ++p) {
4717 if (!(isalnum (*p) || *p == '_'))
4721 acfg->method_index = 1;
4723 collect_methods (acfg);
4725 acfg->cfgs_size = acfg->methods->len + 32;
4726 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
4728 /* PLT offset 0 is reserved for the PLT trampoline */
4729 acfg->plt_offset = 1;
4733 compile_methods (acfg);
4737 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
4741 alloc_got_slots (acfg);
4743 img_writer_emit_start (acfg->w);
4746 mono_dwarf_writer_emit_base_info (acfg->dwarf, arch_get_cie_program ());
4752 emit_extra_methods (acfg);
4754 emit_method_order (acfg);
4756 emit_trampolines (acfg);
4758 emit_class_name_table (acfg);
4760 emit_got_info (acfg);
4762 emit_exception_info (acfg);
4764 emit_unwind_info (acfg);
4766 emit_class_info (acfg);
4770 emit_image_table (acfg);
4774 emit_file_info (acfg);
4776 emit_globals (acfg);
4779 emit_dwarf_info (acfg);
4781 emit_mem_end (acfg);
4785 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
4787 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)));
4790 res = img_writer_emit_writeout (acfg->w);
4795 if (acfg->use_bin_writer) {
4796 rename (tmp_outfile_name, outfile_name);
4798 res = compile_asm (acfg);
4805 acfg->stats.link_time = TV_ELAPSED (atv, btv);
4807 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);
4808 if (acfg->stats.genericcount)
4809 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
4810 if (acfg->stats.abscount)
4811 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
4812 if (acfg->stats.lmfcount)
4813 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
4814 if (acfg->stats.ocount)
4815 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
4816 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);
4817 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
4820 printf ("GOT slot distribution:\n");
4821 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
4822 if (acfg->stats.got_slot_types [i])
4823 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
4826 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);
4834 * Support for emitting debug info for JITted code.
4836 * This works as follows:
4837 * - the runtime writes out an xdb.s file containing DWARF debug info.
4838 * - the user calls a gdb macro
4839 * - the macro compiles and loads this shared library using add-symbol-file.
4841 * This is based on the xdebug functionality in the Kaffe Java VM.
4843 * We emit assembly code instead of using the ELF writer, so we can emit debug info
4844 * incrementally as each method is JITted, and the debugger doesn't have to call
4845 * into the runtime to emit the shared library, which would cause all kinds of
4846 * complications, like threading issues, and the fact that the ELF writer's
4847 * emit_writeout () function cannot be called more than once.
4850 /* The recommended gdb macro is: */
4853 shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
4854 add-symbol-file xdb.so 0
4858 static MonoDwarfWriter *xdebug_writer;
4859 static FILE *xdebug_fp;
4862 mono_xdebug_init (void)
4868 xdebug_fp = fopen ("xdb.s", "w");
4870 w = img_writer_create (xdebug_fp, FALSE);
4872 img_writer_emit_start (w);
4874 /* This file will contain the IL code for methods which don't have debug info */
4875 il_file = fopen ("xdb.il", "w");
4877 xdebug_writer = mono_dwarf_writer_create (w, il_file);
4879 /* Emit something so the file has a text segment */
4880 img_writer_emit_section_change (w, ".text", 0);
4881 img_writer_emit_string (w, "");
4883 mono_dwarf_writer_emit_base_info (xdebug_writer, arch_get_cie_program ());
4887 * mono_save_xdebug_info:
4889 * Emit debugging info for METHOD into an assembly file which can be assembled
4890 * and loaded into gdb to provide debugging info for JITted code.
4891 * LOCKING: Acquires the loader lock.
4894 mono_save_xdebug_info (MonoCompile *cfg)
4899 mono_loader_lock ();
4900 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 ()));
4902 mono_loader_unlock ();
4906 * mono_save_trampoline_xdebug_info:
4908 * Same as mono_save_xdebug_info, but for trampolines.
4909 * LOCKING: Acquires the loader lock.
4912 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
4917 mono_loader_lock ();
4918 mono_dwarf_writer_emit_trampoline (xdebug_writer, tramp_name, NULL, NULL, code, code_size, unwind_info);
4920 mono_loader_unlock ();
4928 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
4934 mono_xdebug_init (void)
4939 mono_save_xdebug_info (MonoCompile *cfg)
4944 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)