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 * - optimize the trampolines, generate more code in the arch files.
13 * - make things more consistent with how elf works, for example, use ELF
15 * Remaining generics sharing work:
16 * - optimize the size of the data which is encoded.
17 * - optimize the runtime loading of data:
18 * - the trampoline code calls mono_jit_info_table_find () to find the rgctx,
19 * which loads the debugging+exception handling info for the method. This is a
20 * huge waste of time and code, since the rgctx structure is currently empty.
21 * - every shared method has a MonoGenericJitInfo structure which is only really
22 * used for handling catch clauses with open types, not a very common use case.
25 #include <sys/types.h>
46 #include <mono/metadata/tabledefs.h>
47 #include <mono/metadata/class.h>
48 #include <mono/metadata/object.h>
49 #include <mono/metadata/tokentype.h>
50 #include <mono/metadata/appdomain.h>
51 #include <mono/metadata/debug-helpers.h>
52 #include <mono/metadata/assembly.h>
53 #include <mono/metadata/metadata-internals.h>
54 #include <mono/metadata/marshal.h>
55 #include <mono/metadata/gc-internal.h>
56 #include <mono/metadata/monitor.h>
57 #include <mono/metadata/mempool-internals.h>
58 #include <mono/metadata/mono-endian.h>
59 #include <mono/metadata/threads-types.h>
60 #include <mono/utils/mono-logger.h>
61 #include <mono/utils/mono-compiler.h>
62 #include <mono/utils/mono-time.h>
63 #include <mono/utils/mono-mmap.h>
66 #include "image-writer.h"
67 #include "dwarfwriter.h"
69 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
71 #define TV_DECLARE(name) gint64 name
72 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
73 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
76 #define SHARED_EXT ".dll"
77 #elif defined(__ppc__) && defined(__MACH__)
78 #define SHARED_EXT ".dylib"
80 #define SHARED_EXT ".so"
83 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
84 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
85 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
87 typedef struct MonoAotOptions {
90 gboolean write_symbols;
91 gboolean metadata_only;
92 gboolean bind_to_runtime_version;
102 gboolean print_skipped_methods;
108 typedef struct MonoAotStats {
109 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
110 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
111 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
112 int got_slots, offsets_size;
113 int got_slot_types [MONO_PATCH_INFO_NONE];
114 int jit_time, gen_time, link_time;
117 typedef struct MonoAotCompile {
120 GHashTable *method_indexes;
121 GHashTable *method_depth;
124 GHashTable *patch_to_plt_offset;
125 GHashTable *plt_offset_to_patch;
126 GHashTable *patch_to_got_offset;
127 GHashTable **patch_to_got_offset_by_type;
128 GPtrArray *got_patches;
129 GHashTable *image_hash;
130 GHashTable *method_to_cfg;
131 GHashTable *token_info_hash;
132 GPtrArray *extra_methods;
133 GPtrArray *image_table;
136 guint32 *plt_got_info_offsets;
137 guint32 got_offset, plt_offset, plt_got_offset_base;
138 guint32 final_got_size;
139 /* Number of GOT entries reserved for trampolines */
140 guint32 num_trampoline_got_entries;
142 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
143 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
144 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
146 MonoAotOptions aot_opts;
149 MonoMemPool *mempool;
152 char *static_linking_symbol;
153 CRITICAL_SECTION mutex;
154 gboolean use_bin_writer;
156 MonoDwarfWriter *dwarf;
160 GHashTable *unwind_info_offsets;
161 GPtrArray *unwind_ops;
162 guint32 unwind_info_offset;
165 GHashTable *method_label_hash;
166 const char *temp_prefix;
167 guint32 label_generator;
169 MonoAotFileFlags flags;
170 MonoDynamicStream blob;
173 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
174 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
176 /* This points to the current acfg in LLVM mode */
177 static MonoAotCompile *llvm_acfg;
179 #ifdef HAVE_ARRAY_ELEM_INIT
180 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
181 #define MSGSTRFIELD1(line) str##line
182 static const struct msgstr_t {
183 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
184 #include "patch-info.h"
187 #define PATCH_INFO(a,b) b,
188 #include "patch-info.h"
191 static const gint16 opidx [] = {
192 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
193 #include "patch-info.h"
197 static G_GNUC_UNUSED const char*
198 get_patch_name (int info)
200 return (const char*)&opstr + opidx [info];
204 #define PATCH_INFO(a,b) b,
205 static const char* const
206 patch_types [MONO_PATCH_INFO_NUM + 1] = {
207 #include "patch-info.h"
211 static G_GNUC_UNUSED const char*
212 get_patch_name (int info)
214 return patch_types [info];
219 /* Wrappers around the image writer functions */
222 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
224 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
228 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
230 img_writer_emit_push_section (acfg->w, section_name, subsection);
234 emit_pop_section (MonoAotCompile *acfg)
236 img_writer_emit_pop_section (acfg->w);
240 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
242 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
246 emit_label (MonoAotCompile *acfg, const char *name)
248 img_writer_emit_label (acfg->w, name);
252 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
254 img_writer_emit_bytes (acfg->w, buf, size);
258 emit_string (MonoAotCompile *acfg, const char *value)
260 img_writer_emit_string (acfg->w, value);
264 emit_line (MonoAotCompile *acfg)
266 img_writer_emit_line (acfg->w);
270 emit_alignment (MonoAotCompile *acfg, int size)
272 img_writer_emit_alignment (acfg->w, size);
276 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
278 img_writer_emit_pointer_unaligned (acfg->w, target);
282 emit_pointer (MonoAotCompile *acfg, const char *target)
284 img_writer_emit_pointer (acfg->w, target);
288 emit_int16 (MonoAotCompile *acfg, int value)
290 img_writer_emit_int16 (acfg->w, value);
294 emit_int32 (MonoAotCompile *acfg, int value)
296 img_writer_emit_int32 (acfg->w, value);
300 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
302 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
306 emit_zero_bytes (MonoAotCompile *acfg, int num)
308 img_writer_emit_zero_bytes (acfg->w, num);
312 emit_byte (MonoAotCompile *acfg, guint8 val)
314 img_writer_emit_byte (acfg->w, val);
317 static G_GNUC_UNUSED void
318 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
320 img_writer_emit_global (acfg->w, name, func);
324 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
326 if (acfg->aot_opts.no_dlsym) {
327 g_ptr_array_add (acfg->globals, g_strdup (name));
328 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
330 img_writer_emit_global (acfg->w, name, func);
335 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
337 img_writer_emit_symbol_size (acfg->w, name, end_label);
341 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
343 img_writer_emit_section_change (acfg->w, ".text", 1);
344 emit_global (acfg, name, FALSE);
345 img_writer_emit_label (acfg->w, name);
346 img_writer_emit_string (acfg->w, value);
349 static G_GNUC_UNUSED void
350 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
353 guint8 b = value & 0x7f;
355 if (value != 0) /* more bytes to come */
361 static G_GNUC_UNUSED void
362 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
365 gboolean negative = (value < 0);
372 /* the following is unnecessary if the
373 * implementation of >>= uses an arithmetic rather
374 * than logical shift for a signed left operand
378 value |= - ((gint64)1 <<(size - 7));
379 /* sign bit of byte is second high order bit (0x40) */
380 if ((value == 0 && !(byte & 0x40)) ||
381 (value == -1 && (byte & 0x40)))
385 emit_byte (acfg, byte);
389 static G_GNUC_UNUSED void
390 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
395 guint8 b = value & 0x7f;
397 if (value != 0) /* more bytes to come */
405 static G_GNUC_UNUSED void
406 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
409 gboolean negative = (value < 0);
417 /* the following is unnecessary if the
418 * implementation of >>= uses an arithmetic rather
419 * than logical shift for a signed left operand
423 value |= - (1 <<(size - 7));
424 /* sign bit of byte is second high order bit (0x40) */
425 if ((value == 0 && !(byte & 0x40)) ||
426 (value == -1 && (byte & 0x40)))
436 /* ARCHITECTURE SPECIFIC CODE */
438 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
439 #define EMIT_DWARF_INFO 1
442 #if defined(TARGET_ARM)
443 #define AOT_FUNC_ALIGNMENT 4
445 #define AOT_FUNC_ALIGNMENT 16
448 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
449 #define PPC_LD_OP "ld"
450 #define PPC_LDX_OP "ldx"
452 #define PPC_LD_OP "lwz"
453 #define PPC_LDX_OP "lwzx"
457 * arch_emit_direct_call:
459 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
463 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
465 #if defined(TARGET_X86) || defined(TARGET_AMD64)
466 /* Need to make sure this is exactly 5 bytes long */
467 emit_byte (acfg, '\xe8');
468 emit_symbol_diff (acfg, target, ".", -4);
470 #elif defined(TARGET_ARM)
471 if (acfg->use_bin_writer) {
478 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
479 emit_bytes (acfg, buf, 4);
481 img_writer_emit_unset_mode (acfg->w);
482 fprintf (acfg->fp, "bl %s\n", target);
485 #elif defined(TARGET_POWERPC)
486 if (acfg->use_bin_writer) {
487 g_assert_not_reached ();
489 img_writer_emit_unset_mode (acfg->w);
490 fprintf (acfg->fp, "bl %s\n", target);
494 g_assert_not_reached ();
500 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
502 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
503 * in in the 2. slot of every GOT, and require every method to place the GOT
504 * address in r30, even when it doesn't access the GOT otherwise. This way,
505 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
510 * PPC64 uses function descriptors which greatly complicate all code, since
511 * these are used very inconsistently in the runtime. Some functions like
512 * mono_compile_method () return ftn descriptors, while others like the
513 * trampoline creation functions do not.
514 * We assume that all GOT slots contain function descriptors, and create
515 * descriptors in aot-runtime.c when needed.
516 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
517 * from function descriptors, we could do the same, but it would require
518 * rewriting all the ppc/aot code to handle function descriptors properly.
519 * So instead, we use the same approach as on PPC32.
520 * This is a horrible mess, but fixing it would probably lead to an even bigger
524 #ifdef MONO_ARCH_AOT_SUPPORTED
526 * arch_emit_got_offset:
528 * The memory pointed to by CODE should hold native code for computing the GOT
529 * address. Emit this code while patching it with the offset between code and
530 * the GOT. CODE_SIZE is set to the number of bytes emitted.
533 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
535 #if defined(TARGET_POWERPC64)
536 g_assert (!acfg->use_bin_writer);
537 img_writer_emit_unset_mode (acfg->w);
539 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
540 * unsupported relocations. So we store the got address into the .Lgot_addr
541 * symbol which is in the text segment, compute its address, and load it.
543 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
544 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
545 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
546 fprintf (acfg->fp, "add 30, 30, 0\n");
547 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
548 acfg->label_generator ++;
550 #elif defined(TARGET_POWERPC)
551 g_assert (!acfg->use_bin_writer);
552 img_writer_emit_unset_mode (acfg->w);
553 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
554 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
555 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
556 acfg->label_generator ++;
559 guint32 offset = mono_arch_get_patch_offset (code);
560 emit_bytes (acfg, code, offset);
561 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
563 *code_size = offset + 4;
568 * arch_emit_got_access:
570 * The memory pointed to by CODE should hold native code for loading a GOT
571 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
572 * CODE_SIZE is set to the number of bytes emitted.
575 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
577 /* Emit beginning of instruction */
578 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
580 /* Emit the offset */
582 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
583 *code_size = mono_arch_get_patch_offset (code) + 4;
584 #elif defined(TARGET_X86)
585 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
586 *code_size = mono_arch_get_patch_offset (code) + 4;
587 #elif defined(TARGET_ARM)
588 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
589 *code_size = mono_arch_get_patch_offset (code) + 4;
590 #elif defined(TARGET_POWERPC)
596 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
597 g_assert (code - buf == 8);
598 emit_bytes (acfg, buf, code - buf);
599 *code_size = code - buf;
602 g_assert_not_reached ();
609 * arch_emit_plt_entry:
611 * Emit code for the PLT entry with index INDEX.
614 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
616 #if defined(TARGET_X86)
618 /* It is filled up during loading by the AOT loader. */
619 emit_zero_bytes (acfg, 16);
621 /* Need to make sure this is 9 bytes long */
622 emit_byte (acfg, '\xe9');
623 emit_symbol_diff (acfg, acfg->plt_symbol, ".", -4);
624 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
626 #elif defined(TARGET_AMD64)
628 * We can't emit jumps because they are 32 bits only so they can't be patched.
629 * So we make indirect calls through GOT entries which are patched by the AOT
630 * loader to point to .Lpd entries.
632 /* jmpq *<offset>(%rip) */
633 emit_byte (acfg, '\xff');
634 emit_byte (acfg, '\x25');
635 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
636 /* Used by mono_aot_get_plt_info_offset */
637 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
638 #elif defined(TARGET_ARM)
643 * - optimize OP_AOTCONST implementation
644 * - optimize the PLT entries
645 * - optimize SWITCH AOT implementation
648 if (acfg->use_bin_writer && FALSE) {
649 /* FIXME: mono_arch_patch_plt_entry () needs to decode this */
650 /* We only emit 1 relocation since we implement it ourselves anyway */
651 img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, acfg->got_symbol, ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
652 /* FIXME: A 2 instruction encoding is sufficient in most cases */
653 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
654 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
655 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
656 emit_bytes (acfg, buf, code - buf);
657 /* Used by mono_aot_get_plt_info_offset */
658 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
660 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
661 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
662 emit_bytes (acfg, buf, code - buf);
663 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
664 /* Used by mono_aot_get_plt_info_offset */
665 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
668 * The plt_got_info_offset is computed automatically by
669 * mono_aot_get_plt_info_offset (), so no need to save it here.
671 #elif defined(TARGET_POWERPC)
672 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
674 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
675 g_assert (!acfg->use_bin_writer);
676 img_writer_emit_unset_mode (acfg->w);
677 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
678 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
679 fprintf (acfg->fp, "add 11, 11, 30\n");
680 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
681 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
682 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
683 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
685 fprintf (acfg->fp, "mtctr 11\n");
686 fprintf (acfg->fp, "bctr\n");
687 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
689 g_assert_not_reached ();
694 * arch_emit_specific_trampoline:
696 * Emit code for a specific trampoline. OFFSET is the offset of the first of
697 * two GOT slots which contain the generic trampoline address and the trampoline
698 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
701 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
704 * The trampolines created here are variations of the specific
705 * trampolines created in mono_arch_create_specific_trampoline (). The
707 * - the generic trampoline address is taken from a got slot.
708 * - the offset of the got slot where the trampoline argument is stored
709 * is embedded in the instruction stream, and the generic trampoline
710 * can load the argument by loading the offset, adding it to the
711 * address of the trampoline to get the address of the got slot, and
712 * loading the argument from there.
713 * - all the trampolines should be of the same length.
715 #if defined(TARGET_AMD64)
716 /* This should be exactly 16 bytes long */
718 /* call *<offset>(%rip) */
719 emit_byte (acfg, '\x41');
720 emit_byte (acfg, '\xff');
721 emit_byte (acfg, '\x15');
722 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
723 /* This should be relative to the start of the trampoline */
724 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 19);
725 emit_zero_bytes (acfg, 5);
726 #elif defined(TARGET_ARM)
730 /* This should be exactly 20 bytes long */
733 ARM_PUSH (code, 0x5fff);
734 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
735 /* Load the value from the GOT */
736 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
738 ARM_BLX_REG (code, ARMREG_R1);
740 g_assert (code - buf == 16);
743 emit_bytes (acfg, buf, code - buf);
745 * Only one offset is needed, since the second one would be equal to the
748 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
749 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
750 #elif defined(TARGET_POWERPC)
757 g_assert (!acfg->use_bin_writer);
760 * PPC has no ip relative addressing, so we need to compute the address
761 * of the mscorlib got. That is slow and complex, so instead, we store it
762 * in the second got slot of every aot image. The caller already computed
763 * the address of its got and placed it into r30.
765 img_writer_emit_unset_mode (acfg->w);
766 /* Load mscorlib got address */
767 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
768 /* Load generic trampoline address */
769 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
770 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
771 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
772 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
773 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
775 fprintf (acfg->fp, "mtctr 11\n");
776 /* Load trampoline argument */
777 /* On ppc, we pass it normally to the generic trampoline */
778 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
779 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
780 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
781 /* Branch to generic trampoline */
782 fprintf (acfg->fp, "bctr\n");
784 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
785 *tramp_size = 10 * 4;
790 g_assert_not_reached ();
795 * arch_emit_unbox_trampoline:
797 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
798 * CALL_TARGET is the symbol pointing to the native code of METHOD.
801 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, MonoGenericSharingContext *gsctx, const char *call_target)
803 #if defined(TARGET_AMD64)
808 this_reg = mono_arch_get_this_arg_reg (mono_method_signature (method), gsctx, NULL);
810 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
812 emit_bytes (acfg, buf, code - buf);
814 emit_byte (acfg, '\xe9');
815 emit_symbol_diff (acfg, call_target, ".", -4);
816 #elif defined(TARGET_ARM)
823 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
826 ARM_ADD_REG_IMM8 (code, this_pos, this_pos, sizeof (MonoObject));
828 emit_bytes (acfg, buf, code - buf);
830 if (acfg->use_bin_writer) {
837 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
838 emit_bytes (acfg, buf, 4);
840 fprintf (acfg->fp, "\n\tb %s\n", call_target);
842 #elif defined(TARGET_POWERPC)
845 if (MONO_TYPE_ISSTRUCT (mono_method_signature (method)->ret))
848 g_assert (!acfg->use_bin_writer);
850 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
851 fprintf (acfg->fp, "\n\tb %s\n", call_target);
853 g_assert_not_reached ();
858 * arch_emit_static_rgctx_trampoline:
860 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
861 * two GOT slots which contain the rgctx argument, and the method to jump to.
862 * TRAMP_SIZE is set to the size of the emitted trampoline.
863 * These kinds of trampolines cannot be enumerated statically, since there could
864 * be one trampoline per method instantiation, so we emit the same code for all
865 * trampolines, and parameterize them using two GOT slots.
868 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
870 #if defined(TARGET_AMD64)
871 /* This should be exactly 13 bytes long */
874 /* mov <OFFSET>(%rip), %r10 */
875 emit_byte (acfg, '\x4d');
876 emit_byte (acfg, '\x8b');
877 emit_byte (acfg, '\x15');
878 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
880 /* jmp *<offset>(%rip) */
881 emit_byte (acfg, '\xff');
882 emit_byte (acfg, '\x25');
883 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
884 #elif defined(TARGET_ARM)
888 /* This should be exactly 24 bytes long */
891 /* Load rgctx value */
892 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
893 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
894 /* Load branch addr + branch */
895 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
896 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
898 g_assert (code - buf == 16);
901 emit_bytes (acfg, buf, code - buf);
902 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
903 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
904 #elif defined(TARGET_POWERPC)
911 g_assert (!acfg->use_bin_writer);
914 * PPC has no ip relative addressing, so we need to compute the address
915 * of the mscorlib got. That is slow and complex, so instead, we store it
916 * in the second got slot of every aot image. The caller already computed
917 * the address of its got and placed it into r30.
919 img_writer_emit_unset_mode (acfg->w);
920 /* Load mscorlib got address */
921 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
923 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
924 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
925 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
926 /* Load target address */
927 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
928 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
929 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
930 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
931 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
932 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
934 fprintf (acfg->fp, "mtctr 11\n");
935 /* Branch to the target address */
936 fprintf (acfg->fp, "bctr\n");
938 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
939 *tramp_size = 11 * 4;
945 g_assert_not_reached ();
950 * arch_emit_imt_thunk:
952 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
953 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
954 * key is the IMT key, and ptr holds the address of a memory location holding
955 * the address to branch to if the IMT arg matches the key. The array is
956 * terminated by a pair whose key is NULL, and whose ptr is the address of the
958 * TRAMP_SIZE is set to the size of the emitted trampoline.
961 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
963 #if defined(TARGET_AMD64)
967 code = buf = g_malloc (256);
969 /* FIXME: Optimize this, i.e. use binary search etc. */
970 /* Maybe move the body into a separate function (slower, but much smaller) */
972 /* R10 is a free register */
975 amd64_alu_membase_imm (code, X86_CMP, AMD64_R10, 0, 0);
977 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
980 amd64_alu_membase_reg (code, X86_CMP, AMD64_R10, 0, MONO_ARCH_IMT_REG);
982 amd64_branch8 (code, X86_CC_Z, FALSE, 0);
985 amd64_alu_reg_imm (code, X86_ADD, AMD64_R10, 2 * sizeof (gpointer));
986 amd64_jump_code (code, labels [0]);
989 mono_amd64_patch (labels [2], code);
990 amd64_mov_reg_membase (code, AMD64_R10, AMD64_R10, sizeof (gpointer), 8);
991 amd64_jump_membase (code, AMD64_R10, 0);
995 mono_amd64_patch (labels [1], code);
996 x86_breakpoint (code);
998 /* mov <OFFSET>(%rip), %r10 */
999 emit_byte (acfg, '\x4d');
1000 emit_byte (acfg, '\x8b');
1001 emit_byte (acfg, '\x15');
1002 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1004 emit_bytes (acfg, buf, code - buf);
1006 *tramp_size = code - buf + 7;
1007 #elif defined(TARGET_ARM)
1009 guint8 *code, *code2, *labels [16];
1013 /* The IMT method is in v5 */
1015 /* Need at least two free registers, plus a slot for storing the pc */
1016 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1018 /* Load the parameter from the GOT */
1019 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1020 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1023 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1024 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1026 ARM_B_COND (code, ARMCOND_EQ, 0);
1028 /* End-of-loop check */
1029 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1031 ARM_B_COND (code, ARMCOND_EQ, 0);
1034 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1037 arm_patch (labels [4], labels [1]);
1040 arm_patch (labels [2], code);
1041 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1042 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1043 /* Save it to the third stack slot */
1044 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1045 /* Restore the registers and branch */
1046 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1049 arm_patch (labels [3], code);
1054 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1056 emit_bytes (acfg, buf, code - buf);
1057 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1059 *tramp_size = code - buf + 4;
1060 #elif defined(TARGET_POWERPC)
1062 guint8 *code, *labels [16];
1066 /* Load the mscorlib got address */
1067 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1068 /* Load the parameter from the GOT */
1069 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1070 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1072 /* Load and check key */
1074 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1075 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1077 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1079 /* End-of-loop check */
1080 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1082 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1085 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1088 mono_ppc_patch (labels [4], labels [1]);
1091 mono_ppc_patch (labels [2], code);
1092 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1093 /* r11 now contains the value of the vtable slot */
1094 /* this is not a function descriptor on ppc64 */
1095 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1096 ppc_mtctr (code, ppc_r11);
1097 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1100 mono_ppc_patch (labels [3], code);
1104 *tramp_size = code - buf;
1106 emit_bytes (acfg, buf, code - buf);
1108 g_assert_not_reached ();
1113 * arch_get_cie_program:
1115 * Get the unwind bytecode for the DWARF CIE.
1118 arch_get_cie_program (void)
1123 mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, AMD64_RSP, 8);
1124 mono_add_unwind_op_offset (l, (guint8*)NULL, (guint8*)NULL, AMD64_RIP, -8);
1127 #elif defined(TARGET_POWERPC)
1130 mono_add_unwind_op_def_cfa (l, (guint8*)NULL, (guint8*)NULL, ppc_r1, 0);
1138 /* END OF ARCH SPECIFIC CODE */
1141 mono_get_field_token (MonoClassField *field)
1143 MonoClass *klass = field->parent;
1146 for (i = 0; i < klass->field.count; ++i) {
1147 if (field == &klass->fields [i])
1148 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1151 g_assert_not_reached ();
1156 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1160 //printf ("ENCODE: %d 0x%x.\n", value, value);
1163 * Same encoding as the one used in the metadata, extended to handle values
1164 * greater than 0x1fffffff.
1166 if ((value >= 0) && (value <= 127))
1168 else if ((value >= 0) && (value <= 16383)) {
1169 p [0] = 0x80 | (value >> 8);
1170 p [1] = value & 0xff;
1172 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1173 p [0] = (value >> 24) | 0xc0;
1174 p [1] = (value >> 16) & 0xff;
1175 p [2] = (value >> 8) & 0xff;
1176 p [3] = value & 0xff;
1181 p [1] = (value >> 24) & 0xff;
1182 p [2] = (value >> 16) & 0xff;
1183 p [3] = (value >> 8) & 0xff;
1184 p [4] = value & 0xff;
1192 stream_init (MonoDynamicStream *sh)
1195 sh->alloc_size = 4096;
1196 sh->data = g_malloc (4096);
1198 /* So offsets are > 0 */
1203 make_room_in_stream (MonoDynamicStream *stream, int size)
1205 if (size <= stream->alloc_size)
1208 while (stream->alloc_size <= size) {
1209 if (stream->alloc_size < 4096)
1210 stream->alloc_size = 4096;
1212 stream->alloc_size *= 2;
1215 stream->data = g_realloc (stream->data, stream->alloc_size);
1219 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1223 make_room_in_stream (stream, stream->index + len);
1224 memcpy (stream->data + stream->index, data, len);
1225 idx = stream->index;
1226 stream->index += len;
1233 * Add data to the binary blob inside the aot image. Returns the offset inside the
1234 * blob where the data was stored.
1237 add_to_blob (MonoAotCompile *acfg, guint8 *data, guint32 data_len)
1239 if (acfg->blob.alloc_size == 0)
1240 stream_init (&acfg->blob);
1242 return add_stream_data (&acfg->blob, (char*)data, data_len);
1246 * emit_offset_table:
1248 * Emit a table of increasing offsets in a compact form using differential encoding.
1249 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1250 * group size, the more compact the table becomes, but the slower it becomes to compute
1251 * a given entry. Returns the size of the table.
1254 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1256 gint32 current_offset;
1257 int i, buf_size, ngroups, index_entry_size;
1259 guint32 *index_offsets;
1261 ngroups = (noffsets + (group_size - 1)) / group_size;
1263 index_offsets = g_new0 (guint32, ngroups);
1265 buf_size = noffsets * 4;
1266 p = buf = g_malloc0 (buf_size);
1269 for (i = 0; i < noffsets; ++i) {
1270 //printf ("D: %d -> %d\n", i, offsets [i]);
1271 if ((i % group_size) == 0) {
1272 index_offsets [i / group_size] = p - buf;
1273 /* Emit the full value for these entries */
1274 encode_value (offsets [i], p, &p);
1276 /* The offsets are allowed to be non-increasing */
1277 //g_assert (offsets [i] >= current_offset);
1278 encode_value (offsets [i] - current_offset, p, &p);
1280 current_offset = offsets [i];
1283 if (ngroups && index_offsets [ngroups - 1] < 65000)
1284 index_entry_size = 2;
1286 index_entry_size = 4;
1288 /* Emit the header */
1289 emit_int32 (acfg, noffsets);
1290 emit_int32 (acfg, group_size);
1291 emit_int32 (acfg, ngroups);
1292 emit_int32 (acfg, index_entry_size);
1294 /* Emit the index */
1295 for (i = 0; i < ngroups; ++i) {
1296 if (index_entry_size == 2)
1297 emit_int16 (acfg, index_offsets [i]);
1299 emit_int32 (acfg, index_offsets [i]);
1303 emit_bytes (acfg, buf, p - buf);
1305 return (int)(p - buf) + (ngroups * 4);
1309 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1313 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1317 index = g_hash_table_size (cfg->image_hash);
1318 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1319 g_ptr_array_add (cfg->image_table, image);
1325 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1328 MonoClass *k = NULL;
1330 /* FIXME: Search referenced images as well */
1331 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
1332 k = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1337 if (i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows)
1338 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1344 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1349 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1350 * standard metadata encoding.
1353 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1357 if (klass->generic_class) {
1359 g_assert (klass->type_token);
1361 /* Find a typespec for a class if possible */
1362 token = find_typespec_for_class (acfg, klass);
1364 encode_value (token, p, &p);
1365 encode_value (get_image_index (acfg, acfg->image), p, &p);
1367 MonoClass *gclass = klass->generic_class->container_class;
1368 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1371 /* Encode it ourselves */
1373 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1374 encode_value (MONO_TYPE_GENERICINST, p, &p);
1375 encode_klass_ref (acfg, gclass, p, &p);
1376 encode_value (inst->type_argc, p, &p);
1377 for (i = 0; i < inst->type_argc; ++i)
1378 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1380 } else if (klass->type_token) {
1381 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1382 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1383 encode_value (get_image_index (acfg, klass->image), p, &p);
1384 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1385 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1386 g_assert (container);
1389 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1390 encode_value (klass->byval_arg.type, p, &p);
1392 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1394 encode_value (container->is_method, p, &p);
1395 if (container->is_method)
1396 encode_method_ref (acfg, container->owner.method, p, &p);
1398 encode_klass_ref (acfg, container->owner.klass, p, &p);
1401 g_assert (klass->rank > 0);
1402 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1403 encode_value (get_image_index (acfg, klass->image), p, &p);
1404 encode_value (klass->rank, p, &p);
1405 encode_klass_ref (acfg, klass->element_class, p, &p);
1411 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1413 guint32 token = mono_get_field_token (field);
1416 encode_klass_ref (cfg, field->parent, p, &p);
1417 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1418 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1423 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1427 MonoGenericInst *inst;
1429 /* Encode the context */
1430 inst = context->class_inst;
1431 encode_value (inst ? 1 : 0, p, &p);
1433 encode_value (inst->type_argc, p, &p);
1434 for (i = 0; i < inst->type_argc; ++i)
1435 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1437 inst = context->method_inst;
1438 encode_value (inst ? 1 : 0, p, &p);
1440 encode_value (inst->type_argc, p, &p);
1441 for (i = 0; i < inst->type_argc; ++i)
1442 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1448 #define MAX_IMAGE_INDEX 250
1451 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1453 guint32 image_index = get_image_index (acfg, method->klass->image);
1454 guint32 token = method->token;
1455 MonoJumpInfoToken *ji;
1460 * The encoding for most methods is as follows:
1461 * - image index encoded as a leb128
1462 * - token index encoded as a leb128
1463 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1464 * types of method encodings.
1467 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1469 /* Mark methods which can't use aot trampolines because they need the further
1470 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1472 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1473 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1474 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1477 * Some wrapper methods are shared using their signature, encode their
1478 * stringified signature instead.
1479 * FIXME: Optimize disk usage
1482 if (method->wrapper_type) {
1483 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1484 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1485 if (strcmp (method->name, "runtime_invoke_dynamic")) {
1486 name = mono_aot_wrapper_name (method);
1487 } else if (mono_marshal_method_from_wrapper (method) != method) {
1488 /* Direct wrapper, encode it normally */
1490 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1493 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1494 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1495 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1497 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1498 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1499 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1501 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1502 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1503 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1509 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1510 strcpy ((char*)p, name);
1511 p += strlen (name) + 1;
1513 } else if (method->wrapper_type) {
1514 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1516 encode_value (method->wrapper_type, p, &p);
1518 switch (method->wrapper_type) {
1519 case MONO_WRAPPER_REMOTING_INVOKE:
1520 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1521 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1524 m = mono_marshal_method_from_wrapper (method);
1526 encode_method_ref (acfg, m, p, &p);
1529 case MONO_WRAPPER_PROXY_ISINST:
1530 case MONO_WRAPPER_LDFLD:
1531 case MONO_WRAPPER_LDFLDA:
1532 case MONO_WRAPPER_STFLD:
1533 case MONO_WRAPPER_ISINST: {
1534 MonoClass *proxy_class = (MonoClass*)mono_marshal_method_from_wrapper (method);
1535 encode_klass_ref (acfg, proxy_class, p, &p);
1538 case MONO_WRAPPER_LDFLD_REMOTE:
1539 case MONO_WRAPPER_STFLD_REMOTE:
1541 case MONO_WRAPPER_ALLOC: {
1542 int alloc_type = mono_gc_get_managed_allocator_type (method);
1543 g_assert (alloc_type != -1);
1544 encode_value (alloc_type, p, &p);
1547 case MONO_WRAPPER_STELEMREF:
1549 case MONO_WRAPPER_UNKNOWN:
1550 if (strcmp (method->name, "FastMonitorEnter") == 0)
1551 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1552 else if (strcmp (method->name, "FastMonitorExit") == 0)
1553 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1555 g_assert_not_reached ();
1557 case MONO_WRAPPER_SYNCHRONIZED:
1558 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1559 case MONO_WRAPPER_RUNTIME_INVOKE: {
1562 m = mono_marshal_method_from_wrapper (method);
1564 g_assert (m != method);
1565 encode_method_ref (acfg, m, p, &p);
1569 g_assert_not_reached ();
1571 } else if (mono_method_signature (method)->is_inflated) {
1573 * This is a generic method, find the original token which referenced it and
1575 * Obtain the token from information recorded by the JIT.
1577 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1579 image_index = get_image_index (acfg, ji->image);
1580 g_assert (image_index < MAX_IMAGE_INDEX);
1583 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1584 encode_value (image_index, p, &p);
1585 encode_value (token, p, &p);
1587 MonoMethod *declaring;
1588 MonoGenericContext *context = mono_method_get_context (method);
1590 g_assert (method->is_inflated);
1591 declaring = ((MonoMethodInflated*)method)->declaring;
1594 * This might be a non-generic method of a generic instance, which
1595 * doesn't have a token since the reference is generated by the JIT
1596 * like Nullable:Box/Unbox, or by generic sharing.
1599 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
1600 /* Encode the klass */
1601 encode_klass_ref (acfg, method->klass, p, &p);
1602 /* Encode the method */
1603 image_index = get_image_index (acfg, method->klass->image);
1604 g_assert (image_index < MAX_IMAGE_INDEX);
1605 g_assert (declaring->token);
1606 token = declaring->token;
1607 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1608 encode_value (image_index, p, &p);
1609 encode_value (token, p, &p);
1610 encode_generic_context (acfg, context, p, &p);
1612 } else if (token == 0) {
1613 /* This might be a method of a constructed type like int[,].Set */
1614 /* Obtain the token from information recorded by the JIT */
1615 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1617 image_index = get_image_index (acfg, ji->image);
1618 g_assert (image_index < MAX_IMAGE_INDEX);
1621 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1622 encode_value (image_index, p, &p);
1623 encode_value (token, p, &p);
1626 g_assert (method->klass->rank);
1628 /* Encode directly */
1629 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
1630 encode_klass_ref (acfg, method->klass, p, &p);
1631 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
1632 encode_value (0, p, &p);
1633 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
1634 encode_value (1, p, &p);
1635 else if (!strcmp (method->name, "Get"))
1636 encode_value (2, p, &p);
1637 else if (!strcmp (method->name, "Address"))
1638 encode_value (3, p, &p);
1639 else if (!strcmp (method->name, "Set"))
1640 encode_value (4, p, &p);
1642 g_assert_not_reached ();
1645 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
1646 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
1652 compare_patches (gconstpointer a, gconstpointer b)
1656 i = (*(MonoJumpInfo**)a)->ip.i;
1657 j = (*(MonoJumpInfo**)b)->ip.i;
1671 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
1674 static inline gboolean
1675 is_plt_patch (MonoJumpInfo *patch_info)
1677 switch (patch_info->type) {
1678 case MONO_PATCH_INFO_METHOD:
1679 case MONO_PATCH_INFO_INTERNAL_METHOD:
1680 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
1681 case MONO_PATCH_INFO_ICALL_ADDR:
1682 case MONO_PATCH_INFO_CLASS_INIT:
1683 case MONO_PATCH_INFO_RGCTX_FETCH:
1684 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
1685 case MONO_PATCH_INFO_MONITOR_ENTER:
1686 case MONO_PATCH_INFO_MONITOR_EXIT:
1687 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
1695 get_plt_offset (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
1699 if (is_plt_patch (patch_info)) {
1700 int idx = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_plt_offset, patch_info));
1702 // FIXME: This breaks the calculation of final_got_size
1703 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
1705 * Allocate a separate PLT slot for each such patch, since some plt
1706 * entries will refer to the method itself, and some will refer to the
1715 MonoJumpInfo *new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
1717 g_assert (!acfg->final_got_size);
1719 res = acfg->plt_offset;
1720 g_hash_table_insert (acfg->plt_offset_to_patch, GUINT_TO_POINTER (res), new_ji);
1721 g_hash_table_insert (acfg->patch_to_plt_offset, new_ji, GUINT_TO_POINTER (res));
1722 acfg->plt_offset ++;
1732 * Returns the offset of the GOT slot where the runtime object resulting from resolving
1733 * JI could be found if it exists, otherwise allocates a new one.
1736 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
1740 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
1742 return got_offset - 1;
1744 g_assert (!acfg->final_got_size);
1746 got_offset = acfg->got_offset;
1747 acfg->got_offset ++;
1749 acfg->stats.got_slots ++;
1750 acfg->stats.got_slot_types [ji->type] ++;
1752 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
1753 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
1754 g_ptr_array_add (acfg->got_patches, ji);
1759 /* Add a method to the list of methods which need to be emitted */
1761 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
1764 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
1765 g_ptr_array_add (acfg->methods, method);
1766 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
1767 acfg->nmethods = acfg->methods->len + 1;
1770 if (method->wrapper_type || extra)
1771 g_ptr_array_add (acfg->extra_methods, method);
1775 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
1777 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1785 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
1789 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
1793 index = acfg->method_index;
1794 add_method_with_index (acfg, method, index, extra);
1796 /* FIXME: Fix quadratic behavior */
1797 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
1799 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
1801 acfg->method_index ++;
1807 add_method (MonoAotCompile *acfg, MonoMethod *method)
1809 return add_method_full (acfg, method, FALSE, 0);
1813 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
1815 add_method_full (acfg, method, TRUE, 0);
1819 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
1821 add_method_full (acfg, method, TRUE, depth);
1825 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
1827 MonoAotCompile *acfg = user_data;
1828 MonoJitICallInfo *callinfo = value;
1829 MonoMethod *wrapper;
1835 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
1836 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
1839 add_method (acfg, wrapper);
1843 get_runtime_invoke_sig (MonoMethodSignature *sig)
1845 MonoMethodBuilder *mb;
1848 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
1849 m = mono_mb_create_method (mb, sig, 16);
1850 return mono_marshal_get_runtime_invoke (m, FALSE);
1854 can_marshal_struct (MonoClass *klass)
1856 MonoClassField *field;
1857 gboolean can_marshal = TRUE;
1858 gpointer iter = NULL;
1860 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
1863 /* Only allow a few field types to avoid asserts in the marshalling code */
1864 while ((field = mono_class_get_fields (klass, &iter))) {
1865 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
1868 switch (field->type->type) {
1873 case MONO_TYPE_BOOLEAN:
1876 case MONO_TYPE_CHAR:
1884 case MONO_TYPE_STRING:
1886 case MONO_TYPE_VALUETYPE:
1887 if (!can_marshal_struct (mono_class_from_mono_type (field->type)))
1888 can_marshal = FALSE;
1891 can_marshal = FALSE;
1897 /* Its hard to compute whenever these can be marshalled or not */
1898 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
1905 add_wrappers (MonoAotCompile *acfg)
1907 MonoMethod *method, *m;
1909 MonoMethodSignature *sig, *csig;
1913 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
1914 * so there is only one wrapper of a given type, or inlining their contents into their
1919 * FIXME: This depends on the fact that different wrappers have different
1923 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
1925 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
1926 gboolean skip = FALSE;
1928 method = mono_get_method (acfg->image, token, NULL);
1930 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
1931 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
1932 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
1935 if (method->is_generic || method->klass->generic_container)
1938 /* Skip methods which can not be handled by get_runtime_invoke () */
1939 sig = mono_method_signature (method);
1940 if ((sig->ret->type == MONO_TYPE_PTR) ||
1941 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
1944 for (j = 0; j < sig->param_count; j++) {
1945 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
1949 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
1950 if (!method->klass->contextbound) {
1951 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
1954 /* Supported by the dynamic runtime-invoke wrapper */
1962 //printf ("%s\n", mono_method_full_name (method, TRUE));
1963 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
1967 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
1968 #ifdef MONO_ARCH_HAVE_TLS_GET
1969 MonoMethodDesc *desc;
1970 MonoMethod *orig_method;
1974 /* Runtime invoke wrappers */
1976 /* void runtime-invoke () [.cctor] */
1977 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1978 csig->ret = &mono_defaults.void_class->byval_arg;
1979 add_method (acfg, get_runtime_invoke_sig (csig));
1981 /* void runtime-invoke () [Finalize] */
1982 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
1984 csig->ret = &mono_defaults.void_class->byval_arg;
1985 add_method (acfg, get_runtime_invoke_sig (csig));
1987 /* void runtime-invoke (string) [exception ctor] */
1988 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
1990 csig->ret = &mono_defaults.void_class->byval_arg;
1991 csig->params [0] = &mono_defaults.string_class->byval_arg;
1992 add_method (acfg, get_runtime_invoke_sig (csig));
1994 /* void runtime-invoke (string, string) [exception ctor] */
1995 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
1997 csig->ret = &mono_defaults.void_class->byval_arg;
1998 csig->params [0] = &mono_defaults.string_class->byval_arg;
1999 csig->params [1] = &mono_defaults.string_class->byval_arg;
2000 add_method (acfg, get_runtime_invoke_sig (csig));
2002 /* string runtime-invoke () [Exception.ToString ()] */
2003 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2005 csig->ret = &mono_defaults.string_class->byval_arg;
2006 add_method (acfg, get_runtime_invoke_sig (csig));
2008 /* void runtime-invoke (string, Exception) [exception ctor] */
2009 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2011 csig->ret = &mono_defaults.void_class->byval_arg;
2012 csig->params [0] = &mono_defaults.string_class->byval_arg;
2013 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2014 add_method (acfg, get_runtime_invoke_sig (csig));
2016 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2017 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2019 csig->ret = &(mono_class_from_name (
2020 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2021 csig->params [0] = &mono_defaults.string_class->byval_arg;
2022 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2023 add_method (acfg, get_runtime_invoke_sig (csig));
2025 /* runtime-invoke used by finalizers */
2026 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2028 /* This is used by mono_runtime_capture_context () */
2029 method = mono_get_context_capture_method ();
2031 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2033 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2034 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2037 /* JIT icall wrappers */
2038 /* FIXME: locking */
2039 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2042 add_method (acfg, mono_marshal_get_stelemref ());
2044 #ifdef MONO_ARCH_HAVE_TLS_GET
2045 /* Managed Allocators */
2046 nallocators = mono_gc_get_managed_allocator_types ();
2047 for (i = 0; i < nallocators; ++i) {
2048 m = mono_gc_get_managed_allocator_by_type (i);
2050 add_method (acfg, m);
2053 /* Monitor Enter/Exit */
2054 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2055 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2056 g_assert (orig_method);
2057 mono_method_desc_free (desc);
2058 method = mono_monitor_get_fast_path (orig_method);
2060 add_method (acfg, method);
2062 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2063 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2064 g_assert (orig_method);
2065 mono_method_desc_free (desc);
2066 method = mono_monitor_get_fast_path (orig_method);
2068 add_method (acfg, method);
2073 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2074 * we use the original method instead at runtime.
2075 * Since full-aot doesn't support remoting, this is not a problem.
2078 /* remoting-invoke wrappers */
2079 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2080 MonoMethodSignature *sig;
2082 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2083 method = mono_get_method (acfg->image, token, NULL);
2085 sig = mono_method_signature (method);
2087 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2088 m = mono_marshal_get_remoting_invoke_with_check (method);
2090 add_method (acfg, m);
2095 /* delegate-invoke wrappers */
2096 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2099 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2100 klass = mono_class_get (acfg->image, token);
2102 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2103 method = mono_get_delegate_invoke (klass);
2105 m = mono_marshal_get_delegate_invoke (method, NULL);
2107 add_method (acfg, m);
2109 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2110 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2112 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2113 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2117 /* Synchronized wrappers */
2118 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2119 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2120 method = mono_get_method (acfg->image, token, NULL);
2122 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)
2123 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2126 /* pinvoke wrappers */
2127 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2129 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2131 method = mono_get_method (acfg->image, token, NULL);
2133 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2134 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2135 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2139 /* StructureToPtr/PtrToStructure wrappers */
2140 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2143 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2144 klass = mono_class_get (acfg->image, token);
2146 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2147 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2148 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2154 has_type_vars (MonoClass *klass)
2156 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2159 return has_type_vars (klass->element_class);
2160 if (klass->generic_class) {
2161 MonoGenericContext *context = &klass->generic_class->context;
2162 if (context->class_inst) {
2165 for (i = 0; i < context->class_inst->type_argc; ++i)
2166 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2174 method_has_type_vars (MonoMethod *method)
2176 if (has_type_vars (method->klass))
2179 if (method->is_inflated) {
2180 MonoGenericContext *context = mono_method_get_context (method);
2181 if (context->method_inst) {
2184 for (i = 0; i < context->method_inst->type_argc; ++i)
2185 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2193 * add_generic_class:
2195 * Add all methods of a generic class.
2198 add_generic_class (MonoAotCompile *acfg, MonoClass *klass)
2203 mono_class_init (klass);
2205 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2208 if (has_type_vars (klass))
2211 if (!klass->generic_class && !klass->rank)
2215 while ((method = mono_class_get_methods (klass, &iter))) {
2216 if (mono_method_is_generic_sharable_impl (method, FALSE))
2220 if (method->is_generic)
2225 * FIXME: Instances which are referenced by these methods are not added,
2226 * for example Array.Resize<int> for List<int>.Add ().
2228 add_extra_method (acfg, method);
2231 if (klass->delegate) {
2232 method = mono_get_delegate_invoke (klass);
2234 method = mono_marshal_get_delegate_invoke (method, NULL);
2236 add_method (acfg, method);
2240 * For ICollection<T>, add instances of the helper methods
2241 * in Array, since a T[] could be cast to ICollection<T>.
2243 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2244 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2245 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2246 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2250 if (!strcmp (klass->name, "IEnumerator`1"))
2251 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2253 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2255 /* Add the T[]/InternalEnumerator class */
2256 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2260 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2261 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2265 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2266 add_generic_class (acfg, nclass);
2270 while ((method = mono_class_get_methods (array_class, &iter))) {
2271 if (strstr (method->name, name_prefix)) {
2272 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2273 add_extra_method (acfg, m);
2277 g_free (name_prefix);
2280 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2281 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2282 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2283 MonoClass *icomparable, *gcomparer;
2284 MonoGenericContext ctx;
2285 MonoType *args [16];
2287 memset (&ctx, 0, sizeof (ctx));
2289 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2290 g_assert (icomparable);
2291 args [0] = &tclass->byval_arg;
2292 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2294 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2295 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2296 g_assert (gcomparer);
2297 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx));
2303 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts)
2306 MonoGenericContext ctx;
2307 MonoType *args [16];
2309 memset (&ctx, 0, sizeof (ctx));
2311 for (i = 0; i < ninsts; ++i) {
2312 args [0] = insts [i];
2313 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2314 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx));
2319 * add_generic_instances:
2321 * Add instances referenced by the METHODSPEC/TYPESPEC table.
2324 add_generic_instances (MonoAotCompile *acfg)
2329 MonoMethodHeader *header;
2330 MonoMethodSignature *sig;
2331 MonoGenericContext *context;
2333 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2334 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2335 method = mono_get_method (acfg->image, token, NULL);
2337 context = mono_method_get_context (method);
2338 if (context && ((context->class_inst && context->class_inst->is_open) ||
2339 (context->method_inst && context->method_inst->is_open)))
2342 if (method->klass->image != acfg->image)
2345 if (mono_method_is_generic_sharable_impl (method, FALSE))
2349 add_extra_method (acfg, method);
2352 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
2355 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
2357 klass = mono_class_get (acfg->image, token);
2358 if (!klass || klass->rank)
2361 add_generic_class (acfg, klass);
2364 /* Add types of args/locals */
2365 for (i = 0; i < acfg->methods->len; ++i) {
2368 method = g_ptr_array_index (acfg->methods, i);
2370 sig = mono_method_signature (method);
2373 for (j = 0; j < sig->param_count; ++j)
2374 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
2375 add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]));
2378 header = mono_method_get_header (method);
2381 for (j = 0; j < header->num_locals; ++j)
2382 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
2383 add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]));
2387 if (acfg->image == mono_defaults.corlib) {
2389 MonoType *insts [256];
2392 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
2393 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
2394 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
2395 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
2396 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
2397 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
2398 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
2399 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
2400 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
2401 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
2402 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
2403 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
2405 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
2406 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
2408 add_instances_of (acfg, klass, insts, ninsts);
2409 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
2411 add_instances_of (acfg, klass, insts, ninsts);
2413 /* Add instances of the array generic interfaces for primitive types */
2414 /* This will add instances of the InternalArray_ helper methods in Array too */
2415 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
2417 add_instances_of (acfg, klass, insts, ninsts);
2418 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
2420 add_instances_of (acfg, klass, insts, ninsts);
2421 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
2423 add_instances_of (acfg, klass, insts, ninsts);
2426 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
2427 * used for all instances of GetGenericValueImpl by the AOT runtime.
2430 MonoGenericContext ctx;
2431 MonoType *args [16];
2432 MonoMethod *get_method;
2433 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
2435 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
2438 memset (&ctx, 0, sizeof (ctx));
2439 args [0] = &mono_defaults.object_class->byval_arg;
2440 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
2441 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
2448 * is_direct_callable:
2450 * Return whenever the method identified by JI is directly callable without
2451 * going through the PLT.
2454 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
2456 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2457 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2459 gboolean direct_callable = TRUE;
2461 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
2462 direct_callable = FALSE;
2463 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
2464 // FIXME: Maybe call the wrapper directly ?
2465 direct_callable = FALSE;
2467 if (direct_callable)
2476 * emit_and_reloc_code:
2478 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
2479 * is true, calls are made through the GOT too. This is used for emitting trampolines
2480 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
2481 * since trampolines are needed to make PTL work.
2484 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
2486 int i, pindex, start_index, method_index;
2488 MonoJumpInfo *patch_info;
2489 MonoMethodHeader *header;
2490 gboolean skip, direct_call;
2492 char direct_call_target [128];
2495 header = mono_method_get_header (method);
2497 method_index = get_method_index (acfg, method);
2500 /* Collect and sort relocations */
2501 patches = g_ptr_array_new ();
2502 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
2503 g_ptr_array_add (patches, patch_info);
2504 g_ptr_array_sort (patches, compare_patches);
2507 for (i = 0; i < code_len; i++) {
2509 for (pindex = start_index; pindex < patches->len; ++pindex) {
2510 patch_info = g_ptr_array_index (patches, pindex);
2511 if (patch_info->ip.i >= i)
2515 #ifdef MONO_ARCH_AOT_SUPPORTED
2517 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
2518 start_index = pindex;
2520 switch (patch_info->type) {
2521 case MONO_PATCH_INFO_NONE:
2523 case MONO_PATCH_INFO_GOT_OFFSET: {
2526 arch_emit_got_offset (acfg, code + i, &code_size);
2529 patch_info->type = MONO_PATCH_INFO_NONE;
2534 * If this patch is a call, try emitting a direct call instead of
2535 * through a PLT entry. This is possible if the called method is in
2536 * the same assembly and requires no initialization.
2538 direct_call = FALSE;
2539 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
2540 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
2541 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
2542 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
2544 sprintf (direct_call_target, "%sm_%x", acfg->temp_prefix, get_method_index (acfg, callee_cfg->orig_method));
2545 patch_info->type = MONO_PATCH_INFO_NONE;
2546 acfg->stats.direct_calls ++;
2549 acfg->stats.all_calls ++;
2552 if (!got_only && !direct_call) {
2553 int plt_offset = get_plt_offset (acfg, patch_info);
2554 if (plt_offset != -1) {
2555 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
2557 sprintf (direct_call_target, "%sp_%d", acfg->temp_prefix, plt_offset);
2559 /* Nullify the patch */
2560 patch_info->type = MONO_PATCH_INFO_NONE;
2567 arch_emit_direct_call (acfg, direct_call_target, &call_size);
2572 got_slot = get_got_offset (acfg, patch_info);
2574 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
2581 #endif /* MONO_ARCH_AOT_SUPPORTED */
2584 /* Find next patch */
2586 for (pindex = start_index; pindex < patches->len; ++pindex) {
2587 patch_info = g_ptr_array_index (patches, pindex);
2588 if (patch_info->ip.i >= i)
2592 /* Try to emit multiple bytes at once */
2593 if (pindex < patches->len && patch_info->ip.i > i) {
2594 emit_bytes (acfg, code + i, patch_info->ip.i - i);
2595 i = patch_info->ip.i - 1;
2597 emit_bytes (acfg, code + i, 1);
2606 * Modify SYMBOL so it only includes characters permissible in symbols.
2609 sanitize_symbol (char *symbol)
2611 int i, len = strlen (symbol);
2613 for (i = 0; i < len; ++i)
2614 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
2619 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
2621 char *name1, *name2, *cached;
2622 int i, j, len, count;
2624 name1 = mono_method_full_name (method, TRUE);
2625 len = strlen (name1);
2626 name2 = malloc (strlen (prefix) + len + 16);
2627 memcpy (name2, prefix, strlen (prefix));
2628 j = strlen (prefix);
2629 for (i = 0; i < len; ++i) {
2630 if (isalnum (name1 [i])) {
2631 name2 [j ++] = name1 [i];
2632 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
2634 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
2637 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
2646 while (g_hash_table_lookup (cache, name2)) {
2647 sprintf (name2 + j, "_%d", count);
2651 cached = g_strdup (name2);
2652 g_hash_table_insert (cache, cached, cached);
2658 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
2663 char *debug_sym = NULL;
2665 int func_alignment = AOT_FUNC_ALIGNMENT;
2666 MonoMethodHeader *header;
2668 method = cfg->orig_method;
2669 code = cfg->native_code;
2670 header = mono_method_get_header (method);
2672 method_index = get_method_index (acfg, method);
2674 /* Emit unbox trampoline */
2675 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
2676 char call_target [256];
2678 if (!method->wrapper_type && !method->is_inflated) {
2679 g_assert (method->token);
2680 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
2682 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
2685 emit_section_change (acfg, ".text", 0);
2686 emit_global (acfg, symbol, TRUE);
2687 emit_label (acfg, symbol);
2689 sprintf (call_target, "%sm_%x", acfg->temp_prefix, method_index);
2691 arch_emit_unbox_trampoline (acfg, cfg->orig_method, cfg->generic_sharing_context, call_target);
2694 /* Make the labels local */
2695 sprintf (symbol, "%sm_%x", acfg->temp_prefix, method_index);
2697 emit_section_change (acfg, ".text", 0);
2698 emit_alignment (acfg, func_alignment);
2699 emit_label (acfg, symbol);
2701 if (acfg->aot_opts.write_symbols) {
2703 * Write a C style symbol for every method, this has two uses:
2704 * - it works on platforms where the dwarf debugging info is not
2706 * - it allows the setting of breakpoints of aot-ed methods.
2708 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
2710 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
2711 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
2712 emit_label (acfg, debug_sym);
2715 if (cfg->verbose_level > 0)
2716 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
2718 acfg->stats.code_size += cfg->code_len;
2720 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
2722 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
2726 if (acfg->aot_opts.write_symbols) {
2727 emit_symbol_size (acfg, debug_sym, ".");
2731 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
2732 emit_label (acfg, symbol);
2738 * Encode PATCH_INFO into its disk representation.
2741 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
2745 switch (patch_info->type) {
2746 case MONO_PATCH_INFO_NONE:
2748 case MONO_PATCH_INFO_IMAGE:
2749 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
2751 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
2753 case MONO_PATCH_INFO_METHOD_REL:
2754 encode_value ((gint)patch_info->data.offset, p, &p);
2756 case MONO_PATCH_INFO_SWITCH: {
2757 gpointer *table = (gpointer *)patch_info->data.table->table;
2760 encode_value (patch_info->data.table->table_size, p, &p);
2761 for (k = 0; k < patch_info->data.table->table_size; k++)
2762 encode_value ((int)(gssize)table [k], p, &p);
2765 case MONO_PATCH_INFO_METHODCONST:
2766 case MONO_PATCH_INFO_METHOD:
2767 case MONO_PATCH_INFO_METHOD_JUMP:
2768 case MONO_PATCH_INFO_ICALL_ADDR:
2769 case MONO_PATCH_INFO_METHOD_RGCTX:
2770 encode_method_ref (acfg, patch_info->data.method, p, &p);
2772 case MONO_PATCH_INFO_INTERNAL_METHOD:
2773 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
2774 guint32 len = strlen (patch_info->data.name);
2776 encode_value (len, p, &p);
2778 memcpy (p, patch_info->data.name, len);
2783 case MONO_PATCH_INFO_LDSTR: {
2784 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
2785 guint32 token = patch_info->data.token->token;
2786 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
2787 encode_value (image_index, p, &p);
2788 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
2791 case MONO_PATCH_INFO_RVA:
2792 case MONO_PATCH_INFO_DECLSEC:
2793 case MONO_PATCH_INFO_LDTOKEN:
2794 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
2795 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
2796 encode_value (patch_info->data.token->token, p, &p);
2797 encode_value (patch_info->data.token->has_context, p, &p);
2798 if (patch_info->data.token->has_context)
2799 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
2801 case MONO_PATCH_INFO_EXC_NAME: {
2802 MonoClass *ex_class;
2805 mono_class_from_name (mono_defaults.exception_class->image,
2806 "System", patch_info->data.target);
2807 g_assert (ex_class);
2808 encode_klass_ref (acfg, ex_class, p, &p);
2811 case MONO_PATCH_INFO_R4:
2812 encode_value (*((guint32 *)patch_info->data.target), p, &p);
2814 case MONO_PATCH_INFO_R8:
2815 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
2816 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
2818 case MONO_PATCH_INFO_VTABLE:
2819 case MONO_PATCH_INFO_CLASS:
2820 case MONO_PATCH_INFO_IID:
2821 case MONO_PATCH_INFO_ADJUSTED_IID:
2822 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2824 case MONO_PATCH_INFO_CLASS_INIT:
2825 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
2826 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
2828 case MONO_PATCH_INFO_FIELD:
2829 case MONO_PATCH_INFO_SFLDA:
2830 encode_field_info (acfg, patch_info->data.field, p, &p);
2832 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
2834 case MONO_PATCH_INFO_RGCTX_FETCH: {
2835 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
2837 encode_method_ref (acfg, entry->method, p, &p);
2838 encode_value (entry->in_mrgctx, p, &p);
2839 encode_value (entry->info_type, p, &p);
2840 encode_value (entry->data->type, p, &p);
2841 encode_patch (acfg, entry->data, p, &p);
2844 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2845 case MONO_PATCH_INFO_MONITOR_ENTER:
2846 case MONO_PATCH_INFO_MONITOR_EXIT:
2847 case MONO_PATCH_INFO_SEQ_POINT_INFO:
2849 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2850 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
2851 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
2854 g_warning ("unable to handle jump info %d", patch_info->type);
2855 g_assert_not_reached ();
2862 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
2865 guint32 pindex, offset;
2866 MonoJumpInfo *patch_info;
2868 encode_value (n_patches, p, &p);
2870 for (pindex = 0; pindex < patches->len; ++pindex) {
2871 patch_info = g_ptr_array_index (patches, pindex);
2873 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
2877 offset = get_got_offset (acfg, patch_info);
2878 encode_value (offset, p, &p);
2885 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
2889 int pindex, buf_size, n_patches;
2892 MonoJumpInfo *patch_info;
2893 MonoMethodHeader *header;
2894 guint32 method_index;
2896 guint32 first_got_offset;
2898 method = cfg->orig_method;
2899 code = cfg->native_code;
2900 header = mono_method_get_header (method);
2902 method_index = get_method_index (acfg, method);
2904 /* Sort relocations */
2905 patches = g_ptr_array_new ();
2906 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
2907 g_ptr_array_add (patches, patch_info);
2908 g_ptr_array_sort (patches, compare_patches);
2910 first_got_offset = acfg->cfgs [method_index]->got_offset;
2912 /**********************/
2913 /* Encode method info */
2914 /**********************/
2916 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
2917 p = buf = g_malloc (buf_size);
2919 if (mono_class_get_cctor (method->klass))
2920 encode_klass_ref (acfg, method->klass, p, &p);
2922 /* Not needed when loading the method */
2923 encode_value (0, p, &p);
2926 if (cfg->opt & MONO_OPT_SHARED) {
2927 encode_value (g_list_length (cfg->ldstr_list), p, &p);
2928 for (l = cfg->ldstr_list; l; l = l->next) {
2929 encode_value ((long)l->data, p, &p);
2933 /* Used only in shared mode */
2934 g_assert (!cfg->ldstr_list);
2937 for (pindex = 0; pindex < patches->len; ++pindex) {
2938 patch_info = g_ptr_array_index (patches, pindex);
2940 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
2941 (patch_info->type == MONO_PATCH_INFO_NONE)) {
2942 patch_info->type = MONO_PATCH_INFO_NONE;
2947 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
2948 /* Stored in a GOT slot initialized at module load time */
2949 patch_info->type = MONO_PATCH_INFO_NONE;
2953 if (is_plt_patch (patch_info)) {
2954 /* Calls are made through the PLT */
2955 patch_info->type = MONO_PATCH_INFO_NONE;
2963 g_assert (cfg->has_got_slots);
2965 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
2967 acfg->stats.info_size += p - buf;
2969 g_assert (p - buf < buf_size);
2971 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
2976 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
2978 guint32 cache_index;
2981 /* Reuse the unwind module to canonize and store unwind info entries */
2982 cache_index = mono_cache_unwind_info (encoded, encoded_len);
2984 /* Use +/- 1 to distinguish 0s from missing entries */
2985 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
2993 * It would be easier to use assembler symbols, but the caller needs an
2996 offset = acfg->unwind_info_offset;
2997 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
2998 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3001 encode_value (encoded_len, p, &p);
3003 acfg->unwind_info_offset += encoded_len + (p - buf);
3009 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3012 int i, k, buf_size, method_index;
3013 guint32 debug_info_size;
3015 MonoMethodHeader *header;
3016 guint8 *p, *buf, *debug_info;
3017 MonoJitInfo *jinfo = cfg->jit_info;
3019 gboolean use_unwind_ops = FALSE;
3020 GPtrArray *seq_points;
3022 method = cfg->orig_method;
3023 code = cfg->native_code;
3024 header = mono_method_get_header (method);
3026 method_index = get_method_index (acfg, method);
3028 if (!acfg->aot_opts.nodebug) {
3029 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3032 debug_info_size = 0;
3035 buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (cfg->seq_points ? (cfg->seq_points->len * 16) : 0);
3036 p = buf = g_malloc (buf_size);
3038 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3039 use_unwind_ops = cfg->unwind_ops != NULL;
3042 seq_points = cfg->seq_points;
3044 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points ? 8 : 0);
3046 if (cfg->compile_llvm) {
3047 /* Emitted by LLVM into the .eh_frame section */
3048 encode_value (0, p, &p);
3050 encode_value (jinfo->code_size, p, &p);
3052 encode_value (flags, p, &p);
3054 if (use_unwind_ops) {
3055 guint32 encoded_len;
3059 * This is a duplicate of the data in the .debug_frame section, but that
3060 * section cannot be accessed using the dl interface.
3062 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3063 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3066 encode_value (jinfo->used_regs, p, &p);
3069 /* Exception table */
3070 if (jinfo->num_clauses)
3071 encode_value (jinfo->num_clauses, p, &p);
3073 for (k = 0; k < jinfo->num_clauses; ++k) {
3074 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3076 encode_value (ei->flags, p, &p);
3077 encode_value (ei->exvar_offset, p, &p);
3079 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER)
3080 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3082 if (ei->data.catch_class) {
3083 encode_value (1, p, &p);
3084 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3086 encode_value (0, p, &p);
3090 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3091 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3092 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3095 if (jinfo->has_generic_jit_info) {
3096 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3098 encode_value (gi->has_this ? 1 : 0, p, &p);
3099 encode_value (gi->this_reg, p, &p);
3100 encode_value (gi->this_offset, p, &p);
3103 * Need to encode jinfo->method too, since it is not equal to 'method'
3104 * when using generic sharing.
3106 encode_method_ref (acfg, jinfo->method, p, &p);
3110 int il_offset, native_offset, last_il_offset, last_native_offset;
3112 encode_value (seq_points->len, p, &p);
3113 last_il_offset = last_native_offset = 0;
3114 for (i = 0; i < seq_points->len; i += 2) {
3115 il_offset = GPOINTER_TO_INT (g_ptr_array_index (seq_points, i));
3116 native_offset = GPOINTER_TO_INT (g_ptr_array_index (seq_points, i + 1));
3117 encode_value (il_offset - last_il_offset, p, &p);
3118 encode_value (native_offset - last_native_offset, p, &p);
3119 last_il_offset = il_offset;
3120 last_native_offset = native_offset;
3125 g_assert (debug_info_size < buf_size);
3127 encode_value (debug_info_size, p, &p);
3128 if (debug_info_size) {
3129 memcpy (p, debug_info, debug_info_size);
3130 p += debug_info_size;
3131 g_free (debug_info);
3134 acfg->stats.ex_info_size += p - buf;
3136 g_assert (p - buf < buf_size);
3139 cfg->ex_info_offset = add_to_blob (acfg, buf, p - buf);
3144 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3146 MonoClass *klass = mono_class_get (acfg->image, token);
3148 int i, buf_size, res;
3149 gboolean no_special_static, cant_encode;
3150 gpointer iter = NULL;
3152 buf_size = 10240 + (klass->vtable_size * 16);
3153 p = buf = g_malloc (buf_size);
3157 mono_class_init (klass);
3159 mono_class_get_nested_types (klass, &iter);
3160 g_assert (klass->nested_classes_inited);
3162 mono_class_setup_vtable (klass);
3165 * Emit all the information which is required for creating vtables so
3166 * the runtime does not need to create the MonoMethod structures which
3167 * take up a lot of space.
3170 no_special_static = !mono_class_has_special_static_fields (klass);
3172 /* Check whenever we have enough info to encode the vtable */
3173 cant_encode = FALSE;
3174 for (i = 0; i < klass->vtable_size; ++i) {
3175 MonoMethod *cm = klass->vtable [i];
3177 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3181 if (klass->generic_container || cant_encode) {
3182 encode_value (-1, p, &p);
3184 encode_value (klass->vtable_size, p, &p);
3185 encode_value ((klass->generic_container ? (1 << 8) : 0) | (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);
3186 if (klass->has_cctor)
3187 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3188 if (klass->has_finalize)
3189 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3191 encode_value (klass->instance_size, p, &p);
3192 encode_value (mono_class_data_size (klass), p, &p);
3193 encode_value (klass->packing_size, p, &p);
3194 encode_value (klass->min_align, p, &p);
3196 for (i = 0; i < klass->vtable_size; ++i) {
3197 MonoMethod *cm = klass->vtable [i];
3200 encode_method_ref (acfg, cm, p, &p);
3202 encode_value (0, p, &p);
3206 acfg->stats.class_info_size += p - buf;
3208 g_assert (p - buf < buf_size);
3209 res = add_to_blob (acfg, buf, p - buf);
3216 * Calls made from AOTed code are routed through a table of jumps similar to the
3217 * ELF PLT (Program Linkage Table). The differences are the following:
3218 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3219 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3220 * jumps. This means the jumps need to be patched when the address of the callee is
3221 * known. Initially the PLT entries jump to code which transfers control to the
3222 * AOT runtime through the first PLT entry.
3225 emit_plt (MonoAotCompile *acfg)
3231 cache = g_hash_table_new (g_str_hash, g_str_equal);
3234 sprintf (symbol, "plt");
3236 emit_section_change (acfg, ".text", 0);
3237 emit_global (acfg, symbol, TRUE);
3239 /* This section will be made read-write by the AOT loader */
3240 emit_alignment (acfg, mono_pagesize ());
3242 emit_alignment (acfg, 16);
3244 emit_label (acfg, symbol);
3245 emit_label (acfg, acfg->plt_symbol);
3247 for (i = 0; i < acfg->plt_offset; ++i) {
3249 char *debug_sym = NULL;
3252 sprintf (label, "%sp_%d", acfg->temp_prefix, i);
3256 * If the target is directly callable, alias the plt symbol to point to
3258 * FIXME: Use this to simplify emit_and_reloc_code ().
3259 * FIXME: Avoid the got slot.
3260 * FIXME: Add support to the binary writer.
3262 ji = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3263 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
3264 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
3265 fprintf (acfg->fp, "\n.set %s, .Lm_%x\n", label, get_method_index (acfg, callee_cfg->orig_method));
3270 emit_label (acfg, label);
3272 if (acfg->aot_opts.write_symbols) {
3273 MonoJumpInfo *ji = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
3277 case MONO_PATCH_INFO_METHOD:
3278 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3280 case MONO_PATCH_INFO_INTERNAL_METHOD:
3281 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
3283 case MONO_PATCH_INFO_CLASS_INIT:
3284 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
3285 sanitize_symbol (debug_sym);
3287 case MONO_PATCH_INFO_RGCTX_FETCH:
3288 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
3290 case MONO_PATCH_INFO_ICALL_ADDR: {
3291 char *s = get_debug_sym (ji->data.method, "", cache);
3293 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
3297 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
3298 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
3300 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3301 debug_sym = g_strdup_printf ("plt__generic_class_init");
3308 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
3309 emit_label (acfg, debug_sym);
3315 * The first plt entry is used to transfer code to the AOT loader.
3317 arch_emit_plt_entry (acfg, i);
3320 emit_symbol_size (acfg, debug_sym, ".");
3325 emit_symbol_size (acfg, acfg->plt_symbol, ".");
3327 sprintf (symbol, "plt_end");
3328 emit_global (acfg, symbol, TRUE);
3329 emit_label (acfg, symbol);
3331 g_hash_table_destroy (cache);
3334 static G_GNUC_UNUSED void
3335 emit_trampoline (MonoAotCompile *acfg, const char *name, guint8 *code,
3336 guint32 code_size, int got_offset, MonoJumpInfo *ji, GSList *unwind_ops)
3338 char start_symbol [256];
3341 MonoJumpInfo *patch_info;
3347 sprintf (start_symbol, "%s", name);
3349 emit_section_change (acfg, ".text", 0);
3350 emit_global (acfg, start_symbol, TRUE);
3351 emit_alignment (acfg, 16);
3352 emit_label (acfg, start_symbol);
3354 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
3355 emit_label (acfg, symbol);
3358 * The code should access everything through the GOT, so we pass
3361 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
3363 emit_symbol_size (acfg, start_symbol, ".");
3367 /* Sort relocations */
3368 patches = g_ptr_array_new ();
3369 for (patch_info = ji; patch_info; patch_info = patch_info->next)
3370 if (patch_info->type != MONO_PATCH_INFO_NONE)
3371 g_ptr_array_add (patches, patch_info);
3372 g_ptr_array_sort (patches, compare_patches);
3374 buf_size = patches->len * 128 + 128;
3375 buf = g_malloc (buf_size);
3378 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
3379 g_assert (p - buf < buf_size);
3381 sprintf (symbol, "%s_p", name);
3383 emit_section_change (acfg, ".text", 0);
3384 emit_global (acfg, symbol, FALSE);
3385 emit_label (acfg, symbol);
3387 emit_bytes (acfg, buf, p - buf);
3389 /* Emit debug info */
3393 sprintf (symbol, "%s", name);
3394 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
3397 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
3402 emit_trampolines (MonoAotCompile *acfg)
3405 int i, tramp_got_offset;
3406 MonoAotTrampoline ntype;
3407 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3415 if (!acfg->aot_opts.full_aot)
3418 g_assert (acfg->image->assembly);
3420 /* Currently, we only emit most trampolines into the mscorlib AOT image. */
3421 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3422 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
3424 * Emit the generic trampolines.
3426 * We could save some code by treating the generic trampolines as a wrapper
3427 * method, but that approach has its own complexities, so we choose the simpler
3430 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
3431 code = mono_arch_create_trampoline_code_full (tramp_type, &code_size, &ji, &unwind_ops, TRUE);
3433 /* Emit trampoline code */
3435 sprintf (symbol, "generic_trampoline_%d", tramp_type);
3437 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, unwind_ops);
3440 code = mono_arch_get_nullified_class_init_trampoline (&code_size);
3441 emit_trampoline (acfg, "nullified_class_init_trampoline", code, code_size, acfg->got_offset, NULL, NULL);
3442 #if defined(TARGET_AMD64) && defined(MONO_ARCH_MONITOR_OBJECT_REG)
3443 code = mono_arch_create_monitor_enter_trampoline_full (&code_size, &ji, TRUE);
3444 emit_trampoline (acfg, "monitor_enter_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3445 code = mono_arch_create_monitor_exit_trampoline_full (&code_size, &ji, TRUE);
3446 emit_trampoline (acfg, "monitor_exit_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3449 code = mono_arch_create_generic_class_init_trampoline_full (&code_size, &ji, TRUE);
3450 emit_trampoline (acfg, "generic_class_init_trampoline", code, code_size, acfg->got_offset, ji, NULL);
3452 /* Emit the exception related code pieces */
3453 code = mono_arch_get_restore_context_full (&code_size, &ji, TRUE);
3454 emit_trampoline (acfg, "restore_context", code, code_size, acfg->got_offset, ji, NULL);
3455 code = mono_arch_get_call_filter_full (&code_size, &ji, TRUE);
3456 emit_trampoline (acfg, "call_filter", code, code_size, acfg->got_offset, ji, NULL);
3457 code = mono_arch_get_throw_exception_full (&code_size, &ji, TRUE);
3458 emit_trampoline (acfg, "throw_exception", code, code_size, acfg->got_offset, ji, NULL);
3459 code = mono_arch_get_rethrow_exception_full (&code_size, &ji, TRUE);
3460 emit_trampoline (acfg, "rethrow_exception", code, code_size, acfg->got_offset, ji, NULL);
3461 code = mono_arch_get_throw_exception_by_name_full (&code_size, &ji, TRUE);
3462 emit_trampoline (acfg, "throw_exception_by_name", code, code_size, acfg->got_offset, ji, NULL);
3463 code = mono_arch_get_throw_corlib_exception_full (&code_size, &ji, TRUE);
3464 emit_trampoline (acfg, "throw_corlib_exception", code, code_size, acfg->got_offset, ji, NULL);
3466 #if defined(TARGET_AMD64)
3467 code = mono_arch_get_throw_pending_exception_full (&code_size, &ji, TRUE);
3468 emit_trampoline (acfg, "throw_pending_exception", code, code_size, acfg->got_offset, ji, NULL);
3471 for (i = 0; i < 128; ++i) {
3474 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
3475 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3476 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3477 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3479 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
3480 code = mono_arch_create_rgctx_lazy_fetch_trampoline_full (offset, &code_size, &ji, TRUE);
3481 sprintf (symbol, "rgctx_fetch_trampoline_%u", offset);
3482 emit_trampoline (acfg, symbol, code, code_size, acfg->got_offset, ji, NULL);
3488 /* delegate_invoke_impl trampolines */
3489 l = mono_arch_get_delegate_invoke_impls ();
3491 MonoAotTrampInfo *info = l->data;
3493 emit_trampoline (acfg, info->name, info->code, info->code_size, acfg->got_offset, NULL, NULL);
3498 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
3500 /* Emit trampolines which are numerous */
3503 * These include the following:
3504 * - specific trampolines
3505 * - static rgctx invoke trampolines
3507 * These trampolines have the same code, they are parameterized by GOT
3509 * They are defined in this file, in the arch_... routines instead of
3510 * in tramp-<ARCH>.c, since it is easier to do it this way.
3514 * When running in aot-only mode, we can't create specific trampolines at
3515 * runtime, so we create a few, and save them in the AOT file.
3516 * Normal trampolines embed their argument as a literal inside the
3517 * trampoline code, we can't do that here, so instead we embed an offset
3518 * which needs to be added to the trampoline address to get the address of
3519 * the GOT slot which contains the argument value.
3520 * The generated trampolines jump to the generic trampolines using another
3521 * GOT slot, which will be setup by the AOT loader to point to the
3522 * generic trampoline code of the given type.
3526 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
3530 emit_section_change (acfg, ".text", 0);
3532 tramp_got_offset = acfg->got_offset;
3534 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
3536 case MONO_AOT_TRAMP_SPECIFIC:
3537 sprintf (symbol, "specific_trampolines");
3539 case MONO_AOT_TRAMP_STATIC_RGCTX:
3540 sprintf (symbol, "static_rgctx_trampolines");
3542 case MONO_AOT_TRAMP_IMT_THUNK:
3543 sprintf (symbol, "imt_thunks");
3546 g_assert_not_reached ();
3549 emit_global (acfg, symbol, TRUE);
3550 emit_alignment (acfg, 16);
3551 emit_label (acfg, symbol);
3553 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
3555 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
3559 case MONO_AOT_TRAMP_SPECIFIC:
3560 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
3561 tramp_got_offset += 2;
3563 case MONO_AOT_TRAMP_STATIC_RGCTX:
3564 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
3565 tramp_got_offset += 2;
3567 case MONO_AOT_TRAMP_IMT_THUNK:
3568 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
3569 tramp_got_offset += 1;
3572 g_assert_not_reached ();
3575 if (!acfg->trampoline_size [ntype]) {
3576 g_assert (tramp_size);
3577 acfg->trampoline_size [ntype] = tramp_size;
3582 /* Reserve some entries at the end of the GOT for our use */
3583 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
3586 acfg->got_offset += acfg->num_trampoline_got_entries;
3590 str_begins_with (const char *str1, const char *str2)
3592 int len = strlen (str2);
3593 return strncmp (str1, str2, len) == 0;
3597 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
3599 gchar **args, **ptr;
3601 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
3602 for (ptr = args; ptr && *ptr; ptr ++) {
3603 const char *arg = *ptr;
3605 if (str_begins_with (arg, "outfile=")) {
3606 opts->outfile = g_strdup (arg + strlen ("outfile="));
3607 } else if (str_begins_with (arg, "save-temps")) {
3608 opts->save_temps = TRUE;
3609 } else if (str_begins_with (arg, "keep-temps")) {
3610 opts->save_temps = TRUE;
3611 } else if (str_begins_with (arg, "write-symbols")) {
3612 opts->write_symbols = TRUE;
3613 } else if (str_begins_with (arg, "metadata-only")) {
3614 opts->metadata_only = TRUE;
3615 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
3616 opts->bind_to_runtime_version = TRUE;
3617 } else if (str_begins_with (arg, "full")) {
3618 opts->full_aot = TRUE;
3619 } else if (str_begins_with (arg, "threads=")) {
3620 opts->nthreads = atoi (arg + strlen ("threads="));
3621 } else if (str_begins_with (arg, "static")) {
3622 opts->static_link = TRUE;
3623 opts->no_dlsym = TRUE;
3624 } else if (str_begins_with (arg, "asmonly")) {
3625 opts->asm_only = TRUE;
3626 } else if (str_begins_with (arg, "asmwriter")) {
3627 opts->asm_writer = TRUE;
3628 } else if (str_begins_with (arg, "nodebug")) {
3629 opts->nodebug = TRUE;
3630 } else if (str_begins_with (arg, "ntrampolines=")) {
3631 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
3632 } else if (str_begins_with (arg, "autoreg")) {
3633 opts->autoreg = TRUE;
3634 } else if (str_begins_with (arg, "tool-prefix=")) {
3635 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
3636 } else if (str_begins_with (arg, "autoreg")) {
3637 opts->autoreg = TRUE;
3638 } else if (str_begins_with (arg, "soft-debug")) {
3639 opts->soft_debug = TRUE;
3640 } else if (str_begins_with (arg, "print-skipped")) {
3641 opts->print_skipped_methods = TRUE;
3642 } else if (str_begins_with (arg, "stats")) {
3645 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
3654 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
3656 MonoMethod *method = (MonoMethod*)key;
3657 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
3658 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
3659 MonoAotCompile *acfg = user_data;
3661 new_ji->image = ji->image;
3662 new_ji->token = ji->token;
3663 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
3667 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
3669 if (klass->type_token)
3671 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3674 return can_encode_class (acfg, klass->element_class);
3679 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
3681 switch (patch_info->type) {
3682 case MONO_PATCH_INFO_METHOD:
3683 case MONO_PATCH_INFO_METHODCONST: {
3684 MonoMethod *method = patch_info->data.method;
3686 if (method->wrapper_type) {
3687 switch (method->wrapper_type) {
3688 case MONO_WRAPPER_NONE:
3689 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
3690 case MONO_WRAPPER_XDOMAIN_INVOKE:
3691 case MONO_WRAPPER_STFLD:
3692 case MONO_WRAPPER_LDFLD:
3693 case MONO_WRAPPER_LDFLDA:
3694 case MONO_WRAPPER_LDFLD_REMOTE:
3695 case MONO_WRAPPER_STFLD_REMOTE:
3696 case MONO_WRAPPER_STELEMREF:
3697 case MONO_WRAPPER_ISINST:
3698 case MONO_WRAPPER_PROXY_ISINST:
3699 case MONO_WRAPPER_ALLOC:
3700 case MONO_WRAPPER_REMOTING_INVOKE:
3701 case MONO_WRAPPER_UNKNOWN:
3704 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
3708 if (!method->token) {
3709 /* The method is part of a constructed type like Int[,].Set (). */
3710 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
3711 if (method->klass->rank)
3719 case MONO_PATCH_INFO_VTABLE:
3720 case MONO_PATCH_INFO_CLASS_INIT:
3721 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3722 case MONO_PATCH_INFO_CLASS:
3723 case MONO_PATCH_INFO_IID:
3724 case MONO_PATCH_INFO_ADJUSTED_IID:
3725 if (!can_encode_class (acfg, patch_info->data.klass)) {
3726 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
3730 case MONO_PATCH_INFO_RGCTX_FETCH: {
3731 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3733 if (!can_encode_patch (acfg, entry->data))
3745 add_generic_class (MonoAotCompile *acfg, MonoClass *klass);
3750 * AOT compile a given method.
3751 * This function might be called by multiple threads, so it must be thread-safe.
3754 compile_method (MonoAotCompile *acfg, MonoMethod *method)
3757 MonoJumpInfo *patch_info;
3760 MonoMethod *wrapped;
3762 if (acfg->aot_opts.metadata_only)
3765 mono_acfg_lock (acfg);
3766 index = get_method_index (acfg, method);
3767 mono_acfg_unlock (acfg);
3769 /* fixme: maybe we can also precompile wrapper methods */
3770 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3771 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3772 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
3773 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
3777 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
3780 wrapped = mono_marshal_method_from_wrapper (method);
3781 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
3782 // FIXME: The wrapper should be generic too, but it is not
3785 InterlockedIncrement (&acfg->stats.mcount);
3788 if (method->is_generic || method->klass->generic_container) {
3789 InterlockedIncrement (&acfg->stats.genericcount);
3794 //acfg->aot_opts.print_skipped_methods = TRUE;
3797 * Since these methods are the only ones which are compiled with
3798 * AOT support, and they are not used by runtime startup/shutdown code,
3799 * the runtime will not see AOT methods during AOT compilation,so it
3800 * does not need to support them by creating a fake GOT etc.
3802 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
3803 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
3804 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
3805 InterlockedIncrement (&acfg->stats.genericcount);
3808 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
3809 /* Let the exception happen at runtime */
3813 if (cfg->disable_aot) {
3814 if (acfg->aot_opts.print_skipped_methods)
3815 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
3816 InterlockedIncrement (&acfg->stats.ocount);
3817 mono_destroy_compile (cfg);
3821 /* Nullify patches which need no aot processing */
3822 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3823 switch (patch_info->type) {
3824 case MONO_PATCH_INFO_LABEL:
3825 case MONO_PATCH_INFO_BB:
3826 patch_info->type = MONO_PATCH_INFO_NONE;
3833 /* Collect method->token associations from the cfg */
3834 mono_acfg_lock (acfg);
3835 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
3836 mono_acfg_unlock (acfg);
3839 * Check for absolute addresses.
3842 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3843 switch (patch_info->type) {
3844 case MONO_PATCH_INFO_ABS:
3845 /* unable to handle this */
3854 if (acfg->aot_opts.print_skipped_methods)
3855 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
3856 InterlockedIncrement (&acfg->stats.abscount);
3857 mono_destroy_compile (cfg);
3861 /* Lock for the rest of the code */
3862 mono_acfg_lock (acfg);
3865 * Check for methods/klasses we can't encode.
3868 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3869 if (!can_encode_patch (acfg, patch_info))
3874 if (acfg->aot_opts.print_skipped_methods)
3875 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
3876 acfg->stats.ocount++;
3877 mono_destroy_compile (cfg);
3878 mono_acfg_unlock (acfg);
3882 /* Adds generic instances referenced by this method */
3884 * The depth is used to avoid infinite loops when generic virtual recursion is
3887 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3889 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3890 switch (patch_info->type) {
3891 case MONO_PATCH_INFO_METHOD: {
3892 MonoMethod *m = patch_info->data.method;
3893 if (m->is_inflated) {
3894 if (!(mono_class_generic_sharing_enabled (m->klass) &&
3895 mono_method_is_generic_sharable_impl (m, FALSE)) &&
3896 !method_has_type_vars (m)) {
3897 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
3898 if (acfg->aot_opts.full_aot)
3899 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
3901 add_extra_method_with_depth (acfg, m, depth + 1);
3904 add_generic_class (acfg, m->klass);
3908 case MONO_PATCH_INFO_VTABLE: {
3909 MonoClass *klass = patch_info->data.klass;
3911 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
3912 add_generic_class (acfg, klass);
3921 /* Determine whenever the method has GOT slots */
3922 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3923 switch (patch_info->type) {
3924 case MONO_PATCH_INFO_GOT_OFFSET:
3925 case MONO_PATCH_INFO_NONE:
3927 case MONO_PATCH_INFO_IMAGE:
3928 /* The assembly is stored in GOT slot 0 */
3929 if (patch_info->data.image != acfg->image)
3930 cfg->has_got_slots = TRUE;
3933 if (!is_plt_patch (patch_info))
3934 cfg->has_got_slots = TRUE;
3939 if (!cfg->has_got_slots)
3940 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
3943 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
3945 /* Make a copy of the patch info which is in the mempool */
3947 MonoJumpInfo *patches = NULL, *patches_end = NULL;
3949 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
3950 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
3953 patches = new_patch_info;
3955 patches_end->next = new_patch_info;
3956 patches_end = new_patch_info;
3958 cfg->patch_info = patches;
3960 /* Make a copy of the unwind info */
3962 GSList *l, *unwind_ops;
3966 for (l = cfg->unwind_ops; l; l = l->next) {
3967 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
3968 memcpy (op, l->data, sizeof (MonoUnwindOp));
3969 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
3971 cfg->unwind_ops = g_slist_reverse (unwind_ops);
3973 /* Make a copy of the argument/local info */
3975 MonoInst **args, **locals;
3976 MonoMethodSignature *sig;
3977 MonoMethodHeader *header;
3980 sig = mono_method_signature (method);
3981 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
3982 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
3983 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3984 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
3988 header = mono_method_get_header (method);
3989 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
3990 for (i = 0; i < header->num_locals; ++i) {
3991 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
3992 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
3994 cfg->locals = locals;
3997 /* Free some fields used by cfg to conserve memory */
3998 mono_mempool_destroy (cfg->mempool);
3999 cfg->mempool = NULL;
4000 g_free (cfg->varinfo);
4001 cfg->varinfo = NULL;
4005 mono_regstate_free (cfg->rs);
4009 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
4011 while (index >= acfg->cfgs_size) {
4012 MonoCompile **new_cfgs;
4015 new_size = acfg->cfgs_size * 2;
4016 new_cfgs = g_new0 (MonoCompile*, new_size);
4017 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4018 g_free (acfg->cfgs);
4019 acfg->cfgs = new_cfgs;
4020 acfg->cfgs_size = new_size;
4022 acfg->cfgs [index] = cfg;
4024 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4027 if (cfg->orig_method->wrapper_type)
4028 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4031 mono_acfg_unlock (acfg);
4033 InterlockedIncrement (&acfg->stats.ccount);
4037 compile_thread_main (gpointer *user_data)
4039 MonoDomain *domain = user_data [0];
4040 MonoAotCompile *acfg = user_data [1];
4041 GPtrArray *methods = user_data [2];
4044 mono_thread_attach (domain);
4046 for (i = 0; i < methods->len; ++i)
4047 compile_method (acfg, g_ptr_array_index (methods, i));
4051 load_profile_files (MonoAotCompile *acfg)
4055 int file_index, res, method_index, i;
4062 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);
4064 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4069 infile = fopen (tmp, "r");
4072 printf ("Using profile data file '%s'\n", tmp);
4077 res = fscanf (infile, "%32s\n", ver);
4078 if ((res != 1) || strcmp (ver, "#VER:1") != 0) {
4079 printf ("Profile file has wrong version or invalid.\n");
4085 res = fscanf (infile, "%d\n", &token);
4089 method_index = mono_metadata_token_index (token) - 1;
4091 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index)))
4092 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4097 /* Add missing methods */
4099 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4100 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4101 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4103 unordered = g_list_reverse (unordered);
4104 if (acfg->method_order)
4105 g_list_last (acfg->method_order)->next = unordered;
4107 acfg->method_order = unordered;
4110 /* Used by the LLVM backend */
4112 mono_aot_get_got_offset (MonoJumpInfo *ji)
4114 return get_got_offset (llvm_acfg, ji);
4118 mono_aot_get_method_name (MonoCompile *cfg)
4120 guint32 method_index = get_method_index (llvm_acfg, cfg->orig_method);
4122 /* LLVM converts these to .Lm_%x */
4123 return g_strdup_printf ("m_%x", method_index);
4127 mono_aot_get_method_debug_name (MonoCompile *cfg)
4129 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
4133 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
4135 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
4139 ji->data.target = data;
4141 if (!can_encode_patch (llvm_acfg, ji))
4144 offset = get_plt_offset (llvm_acfg, ji);
4146 return g_strdup_printf (".Lp_%d", offset);
4150 mono_aot_patch_info_dup (MonoJumpInfo* ji)
4154 mono_acfg_lock (llvm_acfg);
4155 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
4156 mono_acfg_unlock (llvm_acfg);
4166 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
4170 emit_llvm_file (MonoAotCompile *acfg)
4172 char *command, *opts;
4174 MonoJumpInfo *patch_info;
4177 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
4181 /* Compute the final size of the got */
4182 for (i = 0; i < acfg->nmethods; ++i) {
4183 if (acfg->cfgs [i]) {
4184 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
4185 if (patch_info->type != MONO_PATCH_INFO_NONE) {
4186 if (!is_plt_patch (patch_info))
4187 get_got_offset (acfg, patch_info);
4189 get_plt_offset (acfg, patch_info);
4194 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
4196 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
4199 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
4200 * a lot of time, and doesn't seem to save much space.
4201 * The following optimizations cannot be enabled:
4202 * - 'globalopt', which seems to remove our methods, even though they have a global
4203 * alias pointing at them.
4204 * - 'constmerge'/'globaldce', which seems to remove our got symbol.
4207 opts = g_strdup ("-instcombine -simplifycfg");
4209 command = g_strdup_printf ("opt -f %s -o temp.bc temp.bc", opts);
4210 printf ("Executing opt: %s\n", command);
4211 if (system (command) != 0) {
4217 //command = g_strdup_printf ("llc -march=arm -mtriple=arm-linux-gnueabi -f -relocation-model=pic -unwind-tables temp.bc");
4218 command = g_strdup_printf ("llc -f -relocation-model=pic -unwind-tables -o temp.s temp.bc");
4219 printf ("Executing llc: %s\n", command);
4221 if (system (command) != 0) {
4228 emit_code (MonoAotCompile *acfg)
4234 #if defined(TARGET_POWERPC64)
4235 sprintf (symbol, ".Lgot_addr");
4236 emit_section_change (acfg, ".text", 0);
4237 emit_alignment (acfg, 8);
4238 emit_label (acfg, symbol);
4239 emit_pointer (acfg, acfg->got_symbol);
4243 sprintf (symbol, "methods");
4244 emit_section_change (acfg, ".text", 0);
4245 emit_global (acfg, symbol, TRUE);
4246 emit_alignment (acfg, 8);
4247 emit_label (acfg, symbol);
4251 * Emit some padding so the local symbol for the first method doesn't have the
4252 * same address as 'methods'.
4254 emit_zero_bytes (acfg, 16);
4256 for (l = acfg->method_order; l != NULL; l = l->next) {
4257 i = GPOINTER_TO_UINT (l->data);
4259 if (acfg->cfgs [i]) {
4260 if (acfg->cfgs [i]->compile_llvm)
4261 acfg->stats.llvm_count ++;
4263 emit_method_code (acfg, acfg->cfgs [i]);
4267 sprintf (symbol, "methods_end");
4268 emit_section_change (acfg, ".text", 0);
4269 emit_global (acfg, symbol, FALSE);
4270 emit_alignment (acfg, 8);
4271 emit_label (acfg, symbol);
4273 sprintf (symbol, "code_offsets");
4274 emit_section_change (acfg, ".text", 1);
4275 emit_global (acfg, symbol, FALSE);
4276 emit_alignment (acfg, 8);
4277 emit_label (acfg, symbol);
4279 acfg->stats.offsets_size += acfg->nmethods * 4;
4281 for (i = 0; i < acfg->nmethods; ++i) {
4282 if (acfg->cfgs [i]) {
4283 sprintf (symbol, "%sm_%x", acfg->temp_prefix, i);
4284 emit_symbol_diff (acfg, symbol, "methods", 0);
4286 emit_int32 (acfg, 0xffffffff);
4293 emit_info (MonoAotCompile *acfg)
4300 offsets = g_new0 (gint32, acfg->nmethods);
4302 for (l = acfg->method_order; l != NULL; l = l->next) {
4303 i = GPOINTER_TO_UINT (l->data);
4305 if (acfg->cfgs [i]) {
4306 emit_method_info (acfg, acfg->cfgs [i]);
4307 offsets [i] = acfg->cfgs [i]->method_info_offset;
4313 sprintf (symbol, "method_info_offsets");
4314 emit_section_change (acfg, ".text", 1);
4315 emit_global (acfg, symbol, FALSE);
4316 emit_alignment (acfg, 8);
4317 emit_label (acfg, symbol);
4319 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
4324 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
4327 * mono_aot_str_hash:
4329 * Hash function for strings which we use to hash strings for things which are
4330 * saved in the AOT image, since g_str_hash () can change.
4333 mono_aot_str_hash (gconstpointer v1)
4335 /* Same as g_str_hash () in glib */
4336 char *p = (char *) v1;
4341 hash = (hash << 5) - hash + *p;
4347 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
4348 #define mix(a,b,c) { \
4349 a -= c; a ^= rot(c, 4); c += b; \
4350 b -= a; b ^= rot(a, 6); a += c; \
4351 c -= b; c ^= rot(b, 8); b += a; \
4352 a -= c; a ^= rot(c,16); c += b; \
4353 b -= a; b ^= rot(a,19); a += c; \
4354 c -= b; c ^= rot(b, 4); b += a; \
4356 #define final(a,b,c) { \
4357 c ^= b; c -= rot(b,14); \
4358 a ^= c; a -= rot(c,11); \
4359 b ^= a; b -= rot(a,25); \
4360 c ^= b; c -= rot(b,16); \
4361 a ^= c; a -= rot(c,4); \
4362 b ^= a; b -= rot(a,14); \
4363 c ^= b; c -= rot(b,24); \
4367 mono_aot_type_hash (MonoType *t1)
4369 guint hash = t1->type;
4371 hash |= t1->byref << 6; /* do not collide with t1->type values */
4373 case MONO_TYPE_VALUETYPE:
4374 case MONO_TYPE_CLASS:
4375 case MONO_TYPE_SZARRAY:
4376 /* check if the distribution is good enough */
4377 return ((hash << 5) - hash) ^ mono_aot_str_hash (t1->data.klass->name);
4379 return ((hash << 5) - hash) ^ mono_aot_type_hash (t1->data.type);
4380 case MONO_TYPE_ARRAY:
4381 return ((hash << 5) - hash) ^ mono_aot_type_hash (&t1->data.array->eklass->byval_arg);
4382 case MONO_TYPE_GENERICINST:
4383 return ((hash << 5) - hash) ^ 0;
4389 * mono_aot_method_hash:
4391 * Return a hash code for methods which only depends on metadata.
4394 mono_aot_method_hash (MonoMethod *method)
4396 MonoMethodSignature *sig;
4400 guint32 *hashes_start, *hashes;
4403 /* Similar to the hash in mono_method_get_imt_slot () */
4405 sig = mono_method_signature (method);
4407 hashes_count = sig->param_count + 5;
4408 hashes_start = malloc (hashes_count * sizeof (guint32));
4409 hashes = hashes_start;
4411 /* Some wrappers are assigned to random classes */
4412 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
4413 klass = method->klass;
4415 klass = mono_defaults.object_class;
4417 if (!method->wrapper_type) {
4418 char *full_name = mono_type_full_name (&klass->byval_arg);
4420 hashes [0] = mono_aot_str_hash (full_name);
4424 hashes [0] = mono_aot_str_hash (klass->name);
4425 hashes [1] = mono_aot_str_hash (klass->name_space);
4427 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
4428 /* The method name includes a stringified pointer */
4431 hashes [2] = mono_aot_str_hash (method->name);
4432 hashes [3] = method->wrapper_type;
4433 hashes [4] = mono_aot_type_hash (sig->ret);
4434 for (i = 0; i < sig->param_count; i++) {
4435 hashes [5 + i] = mono_aot_type_hash (sig->params [i]);
4438 /* Setup internal state */
4439 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
4441 /* Handle most of the hashes */
4442 while (hashes_count > 3) {
4451 /* Handle the last 3 hashes (all the case statements fall through) */
4452 switch (hashes_count) {
4453 case 3 : c += hashes [2];
4454 case 2 : b += hashes [1];
4455 case 1 : a += hashes [0];
4457 case 0: /* nothing left to add */
4461 free (hashes_start);
4470 * mono_aot_wrapper_name:
4472 * Return a string which uniqely identifies the given wrapper method.
4475 mono_aot_wrapper_name (MonoMethod *method)
4477 char *name, *tmpsig, *klass_desc;
4479 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
4481 switch (method->wrapper_type) {
4482 case MONO_WRAPPER_RUNTIME_INVOKE:
4483 if (!strcmp (method->name, "runtime_invoke_dynamic"))
4484 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
4486 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
4488 case MONO_WRAPPER_DELEGATE_INVOKE:
4489 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
4490 case MONO_WRAPPER_DELEGATE_END_INVOKE:
4491 /* This is a hack to work around the fact that these wrappers get assigned to some random class */
4492 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
4495 klass_desc = mono_type_full_name (&method->klass->byval_arg);
4496 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
4497 g_free (klass_desc);
4507 * mono_aot_get_array_helper_from_wrapper;
4509 * Get the helper method in Array called by an array wrapper method.
4512 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
4516 MonoGenericContext ctx;
4517 MonoType *args [16];
4518 char *mname, *iname, *s, *s2, *helper_name = NULL;
4520 prefix = "System.Collections.Generic";
4521 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
4522 s2 = strstr (s, "`1.");
4528 //printf ("X: %s %s\n", iname, mname);
4530 if (!strcmp (iname, "IList"))
4531 helper_name = g_strdup_printf ("InternalArray__%s", mname);
4533 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
4534 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
4536 g_free (helper_name);
4539 if (m->is_generic) {
4540 memset (&ctx, 0, sizeof (ctx));
4541 args [0] = &method->klass->element_class->byval_arg;
4542 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4543 m = mono_class_inflate_generic_method (m, &ctx);
4550 * mono_aot_tramp_info_create:
4552 * Create a MonoAotTrampInfo structure from the arguments.
4555 mono_aot_tramp_info_create (const char *name, guint8 *code, guint32 code_size)
4557 MonoAotTrampInfo *info = g_new0 (MonoAotTrampInfo, 1);
4559 info->name = (char*)name;
4561 info->code_size = code_size;
4566 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
4568 typedef struct HashEntry {
4569 guint32 key, value, index;
4570 struct HashEntry *next;
4574 * emit_extra_methods:
4576 * Emit methods which are not in the METHOD table, like wrappers.
4579 emit_extra_methods (MonoAotCompile *acfg)
4581 int i, table_size, buf_size;
4584 guint32 *info_offsets;
4587 HashEntry *entry, *new_entry;
4588 int nmethods, max_chain_length;
4591 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
4593 /* Emit method info */
4595 for (i = 0; i < acfg->extra_methods->len; ++i) {
4596 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4597 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4604 p = buf = g_malloc (buf_size);
4609 if (method->wrapper_type) {
4611 * We encode some wrappers using their name, since encoding them
4612 * directly would be difficult. This also avoids creating the wrapper
4613 * methods at runtime, since they are not needed anyway.
4615 switch (method->wrapper_type) {
4616 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4617 case MONO_WRAPPER_SYNCHRONIZED:
4618 /* encode_method_ref () can handle these */
4620 case MONO_WRAPPER_RUNTIME_INVOKE:
4621 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
4622 /* Direct wrapper, encode normally */
4626 name = mono_aot_wrapper_name (method);
4632 encode_value (1, p, &p);
4633 encode_value (method->wrapper_type, p, &p);
4634 strcpy ((char*)p, name);
4635 p += strlen (name ) + 1;
4638 encode_value (0, p, &p);
4639 encode_method_ref (acfg, method, p, &p);
4642 g_assert ((p - buf) < buf_size);
4644 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
4649 * Construct a chained hash table for mapping indexes in extra_method_info to
4652 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
4653 table = g_ptr_array_sized_new (table_size);
4654 for (i = 0; i < table_size; ++i)
4655 g_ptr_array_add (table, NULL);
4656 chain_lengths = g_new0 (int, table_size);
4657 max_chain_length = 0;
4658 for (i = 0; i < acfg->extra_methods->len; ++i) {
4659 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4660 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
4666 key = info_offsets [i];
4667 value = get_method_index (acfg, method);
4669 hash = mono_aot_method_hash (method) % table_size;
4671 chain_lengths [hash] ++;
4672 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
4674 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
4675 new_entry->key = key;
4676 new_entry->value = value;
4678 entry = g_ptr_array_index (table, hash);
4679 if (entry == NULL) {
4680 new_entry->index = hash;
4681 g_ptr_array_index (table, hash) = new_entry;
4684 entry = entry->next;
4686 entry->next = new_entry;
4687 new_entry->index = table->len;
4688 g_ptr_array_add (table, new_entry);
4692 //printf ("MAX: %d\n", max_chain_length);
4694 /* Emit the table */
4695 sprintf (symbol, "extra_method_table");
4696 emit_section_change (acfg, ".text", 0);
4697 emit_global (acfg, symbol, FALSE);
4698 emit_alignment (acfg, 8);
4699 emit_label (acfg, symbol);
4701 emit_int32 (acfg, table_size);
4702 for (i = 0; i < table->len; ++i) {
4703 HashEntry *entry = g_ptr_array_index (table, i);
4705 if (entry == NULL) {
4706 emit_int32 (acfg, 0);
4707 emit_int32 (acfg, 0);
4708 emit_int32 (acfg, 0);
4710 //g_assert (entry->key > 0);
4711 emit_int32 (acfg, entry->key);
4712 emit_int32 (acfg, entry->value);
4714 emit_int32 (acfg, entry->next->index);
4716 emit_int32 (acfg, 0);
4721 * Emit a table reverse mapping method indexes to their index in extra_method_info.
4722 * This is used by mono_aot_find_jit_info ().
4724 sprintf (symbol, "extra_method_info_offsets");
4725 emit_section_change (acfg, ".text", 0);
4726 emit_global (acfg, symbol, FALSE);
4727 emit_alignment (acfg, 8);
4728 emit_label (acfg, symbol);
4730 emit_int32 (acfg, acfg->extra_methods->len);
4731 for (i = 0; i < acfg->extra_methods->len; ++i) {
4732 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
4734 emit_int32 (acfg, get_method_index (acfg, method));
4735 emit_int32 (acfg, info_offsets [i]);
4740 emit_exception_info (MonoAotCompile *acfg)
4746 offsets = g_new0 (gint32, acfg->nmethods);
4747 for (i = 0; i < acfg->nmethods; ++i) {
4748 if (acfg->cfgs [i]) {
4749 emit_exception_debug_info (acfg, acfg->cfgs [i]);
4750 offsets [i] = acfg->cfgs [i]->ex_info_offset;
4756 sprintf (symbol, "ex_info_offsets");
4757 emit_section_change (acfg, ".text", 1);
4758 emit_global (acfg, symbol, FALSE);
4759 emit_alignment (acfg, 8);
4760 emit_label (acfg, symbol);
4762 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
4767 emit_unwind_info (MonoAotCompile *acfg)
4773 * The unwind info contains a lot of duplicates so we emit each unique
4774 * entry once, and only store the offset from the start of the table in the
4778 sprintf (symbol, "unwind_info");
4779 emit_section_change (acfg, ".text", 1);
4780 emit_alignment (acfg, 8);
4781 emit_label (acfg, symbol);
4782 emit_global (acfg, symbol, FALSE);
4784 for (i = 0; i < acfg->unwind_ops->len; ++i) {
4785 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
4786 guint8 *unwind_info;
4787 guint32 unwind_info_len;
4791 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
4794 encode_value (unwind_info_len, p, &p);
4795 emit_bytes (acfg, buf, p - buf);
4796 emit_bytes (acfg, unwind_info, unwind_info_len);
4798 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
4803 emit_class_info (MonoAotCompile *acfg)
4809 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
4810 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
4811 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
4813 sprintf (symbol, "class_info_offsets");
4814 emit_section_change (acfg, ".text", 1);
4815 emit_global (acfg, symbol, FALSE);
4816 emit_alignment (acfg, 8);
4817 emit_label (acfg, symbol);
4819 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
4823 typedef struct ClassNameTableEntry {
4824 guint32 token, index;
4825 struct ClassNameTableEntry *next;
4826 } ClassNameTableEntry;
4829 emit_class_name_table (MonoAotCompile *acfg)
4832 guint32 token, hash;
4837 ClassNameTableEntry *entry, *new_entry;
4840 * Construct a chained hash table for mapping class names to typedef tokens.
4842 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
4843 table = g_ptr_array_sized_new (table_size);
4844 for (i = 0; i < table_size; ++i)
4845 g_ptr_array_add (table, NULL);
4846 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
4847 token = MONO_TOKEN_TYPE_DEF | (i + 1);
4848 klass = mono_class_get (acfg->image, token);
4849 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
4850 hash = mono_aot_str_hash (full_name) % table_size;
4853 /* FIXME: Allocate from the mempool */
4854 new_entry = g_new0 (ClassNameTableEntry, 1);
4855 new_entry->token = token;
4857 entry = g_ptr_array_index (table, hash);
4858 if (entry == NULL) {
4859 new_entry->index = hash;
4860 g_ptr_array_index (table, hash) = new_entry;
4863 entry = entry->next;
4865 entry->next = new_entry;
4866 new_entry->index = table->len;
4867 g_ptr_array_add (table, new_entry);
4871 /* Emit the table */
4872 sprintf (symbol, "class_name_table");
4873 emit_section_change (acfg, ".text", 0);
4874 emit_global (acfg, symbol, FALSE);
4875 emit_alignment (acfg, 8);
4876 emit_label (acfg, symbol);
4878 /* FIXME: Optimize memory usage */
4879 g_assert (table_size < 65000);
4880 emit_int16 (acfg, table_size);
4881 g_assert (table->len < 65000);
4882 for (i = 0; i < table->len; ++i) {
4883 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
4885 if (entry == NULL) {
4886 emit_int16 (acfg, 0);
4887 emit_int16 (acfg, 0);
4889 emit_int16 (acfg, mono_metadata_token_index (entry->token));
4891 emit_int16 (acfg, entry->next->index);
4893 emit_int16 (acfg, 0);
4899 emit_image_table (MonoAotCompile *acfg)
4905 * The image table is small but referenced in a lot of places.
4906 * So we emit it at once, and reference its elements by an index.
4909 sprintf (symbol, "mono_image_table");
4910 emit_section_change (acfg, ".text", 1);
4911 emit_global (acfg, symbol, FALSE);
4912 emit_alignment (acfg, 8);
4913 emit_label (acfg, symbol);
4915 emit_int32 (acfg, acfg->image_table->len);
4916 for (i = 0; i < acfg->image_table->len; i++) {
4917 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
4918 MonoAssemblyName *aname = &image->assembly->aname;
4920 /* FIXME: Support multi-module assemblies */
4921 g_assert (image->assembly->image == image);
4923 emit_string (acfg, image->assembly_name);
4924 emit_string (acfg, image->guid);
4925 emit_string (acfg, aname->culture ? aname->culture : "");
4926 emit_string (acfg, (const char*)aname->public_key_token);
4928 emit_alignment (acfg, 8);
4929 emit_int32 (acfg, aname->flags);
4930 emit_int32 (acfg, aname->major);
4931 emit_int32 (acfg, aname->minor);
4932 emit_int32 (acfg, aname->build);
4933 emit_int32 (acfg, aname->revision);
4938 emit_got_info (MonoAotCompile *acfg)
4941 int i, first_plt_got_patch, buf_size;
4943 guint32 *got_info_offsets;
4945 /* Add the patches needed by the PLT to the GOT */
4946 acfg->plt_got_offset_base = acfg->got_offset;
4947 first_plt_got_patch = acfg->got_patches->len;
4948 for (i = 1; i < acfg->plt_offset; ++i) {
4949 MonoJumpInfo *patch_info = g_hash_table_lookup (acfg->plt_offset_to_patch, GUINT_TO_POINTER (i));
4951 g_ptr_array_add (acfg->got_patches, patch_info);
4954 acfg->got_offset += acfg->plt_offset;
4958 * - optimize offsets table.
4959 * - reduce number of exported symbols.
4960 * - emit info for a klass only once.
4961 * - determine when a method uses a GOT slot which is guaranteed to be already
4963 * - clean up and document the code.
4964 * - use String.Empty in class libs.
4967 /* Encode info required to decode shared GOT entries */
4968 buf_size = acfg->got_patches->len * 64;
4969 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
4970 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
4971 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
4973 if (acfg->plt_offset)
4974 acfg->plt_got_info_offsets [0] = 0;
4975 for (i = 0; i < acfg->got_patches->len; ++i) {
4976 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
4980 encode_value (ji->type, p, &p);
4981 encode_patch (acfg, ji, p, &p);
4983 g_assert (p - buf <= buf_size);
4984 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
4986 if (i >= first_plt_got_patch)
4987 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
4988 acfg->stats.got_info_size += p - buf;
4991 /* Emit got_info_offsets table */
4992 sprintf (symbol, "got_info_offsets");
4993 emit_section_change (acfg, ".text", 1);
4994 emit_global (acfg, symbol, FALSE);
4995 emit_alignment (acfg, 8);
4996 emit_label (acfg, symbol);
4998 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
4999 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
5003 emit_got (MonoAotCompile *acfg)
5008 /* Don't make GOT global so accesses to it don't need relocations */
5009 sprintf (symbol, "%s", acfg->got_symbol);
5010 emit_section_change (acfg, ".bss", 0);
5011 emit_alignment (acfg, 8);
5012 emit_local_symbol (acfg, symbol, "got_end", FALSE);
5013 emit_label (acfg, symbol);
5014 if (acfg->got_offset > 0)
5015 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5017 sprintf (symbol, "got_end");
5018 emit_label (acfg, symbol);
5021 sprintf (symbol, "mono_aot_got_addr");
5022 emit_section_change (acfg, ".data", 0);
5023 emit_global (acfg, symbol, FALSE);
5024 emit_alignment (acfg, 8);
5025 emit_label (acfg, symbol);
5026 emit_pointer (acfg, acfg->got_symbol);
5029 typedef struct GlobalsTableEntry {
5030 guint32 value, index;
5031 struct GlobalsTableEntry *next;
5032 } GlobalsTableEntry;
5035 emit_globals_table (MonoAotCompile *acfg)
5041 GlobalsTableEntry *entry, *new_entry;
5044 * Construct a chained hash table for mapping global names to their index in
5045 * the globals table.
5047 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
5048 table = g_ptr_array_sized_new (table_size);
5049 for (i = 0; i < table_size; ++i)
5050 g_ptr_array_add (table, NULL);
5051 for (i = 0; i < acfg->globals->len; ++i) {
5052 char *name = g_ptr_array_index (acfg->globals, i);
5054 hash = mono_aot_str_hash (name) % table_size;
5056 /* FIXME: Allocate from the mempool */
5057 new_entry = g_new0 (GlobalsTableEntry, 1);
5058 new_entry->value = i;
5060 entry = g_ptr_array_index (table, hash);
5061 if (entry == NULL) {
5062 new_entry->index = hash;
5063 g_ptr_array_index (table, hash) = new_entry;
5066 entry = entry->next;
5068 entry->next = new_entry;
5069 new_entry->index = table->len;
5070 g_ptr_array_add (table, new_entry);
5074 /* Emit the table */
5075 sprintf (symbol, ".Lglobals_hash");
5076 emit_section_change (acfg, ".text", 0);
5077 emit_alignment (acfg, 8);
5078 emit_label (acfg, symbol);
5080 /* FIXME: Optimize memory usage */
5081 g_assert (table_size < 65000);
5082 emit_int16 (acfg, table_size);
5083 for (i = 0; i < table->len; ++i) {
5084 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
5086 if (entry == NULL) {
5087 emit_int16 (acfg, 0);
5088 emit_int16 (acfg, 0);
5090 emit_int16 (acfg, entry->value + 1);
5092 emit_int16 (acfg, entry->next->index);
5094 emit_int16 (acfg, 0);
5098 /* Emit the names */
5099 for (i = 0; i < acfg->globals->len; ++i) {
5100 char *name = g_ptr_array_index (acfg->globals, i);
5102 sprintf (symbol, "name_%d", i);
5103 emit_section_change (acfg, ".text", 1);
5104 emit_label (acfg, symbol);
5105 emit_string (acfg, name);
5108 /* Emit the globals table */
5109 sprintf (symbol, ".Lglobals");
5110 emit_section_change (acfg, ".data", 0);
5111 /* This is not a global, since it is accessed by the init function */
5112 emit_alignment (acfg, 8);
5113 emit_label (acfg, symbol);
5115 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
5116 emit_pointer (acfg, symbol);
5118 for (i = 0; i < acfg->globals->len; ++i) {
5119 char *name = g_ptr_array_index (acfg->globals, i);
5121 sprintf (symbol, "name_%d", i);
5122 emit_pointer (acfg, symbol);
5124 sprintf (symbol, "%s", name);
5125 emit_pointer (acfg, symbol);
5127 /* Null terminate the table */
5128 emit_int32 (acfg, 0);
5129 emit_int32 (acfg, 0);
5133 emit_globals (MonoAotCompile *acfg)
5137 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
5139 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
5141 if (acfg->aot_opts.bind_to_runtime_version) {
5142 build_info = mono_get_runtime_build_info ();
5143 emit_string_symbol (acfg, "mono_runtime_version", build_info);
5144 g_free (build_info);
5146 emit_string_symbol (acfg, "mono_runtime_version", "");
5150 * When static linking, we emit a global which will point to the symbol table.
5152 if (acfg->aot_opts.static_link) {
5156 /* Emit a string holding the assembly name */
5157 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
5159 emit_globals_table (acfg);
5162 * Emit a global symbol which can be passed by an embedding app to
5163 * mono_aot_register_module ().
5165 #if defined(__MACH__)
5166 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5168 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5171 /* Get rid of characters which cannot occur in symbols */
5173 for (p = symbol; *p; ++p) {
5174 if (!(isalnum (*p) || *p == '_'))
5177 acfg->static_linking_symbol = g_strdup (symbol);
5178 emit_global_inner (acfg, symbol, FALSE);
5179 emit_alignment (acfg, 8);
5180 emit_label (acfg, symbol);
5181 sprintf (symbol, "%sglobals", acfg->temp_prefix);
5182 emit_pointer (acfg, symbol);
5187 emit_autoreg (MonoAotCompile *acfg)
5192 * Emit a function into the .ctor section which will be called by the ELF
5193 * loader to register this module with the runtime.
5195 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
5198 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
5200 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
5201 /* Based on code generated by gcc */
5202 img_writer_emit_unset_mode (acfg->w);
5206 ".section .ctors,\"aw\",@progbits\n"
5210 ".section .opd,\"aw\"\n"
5213 ".long .%s,.TOC.@tocbase32\n"
5216 ".type .%s,@function\n"
5217 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
5219 ".section .ctors,\"aw\",@progbits\n"
5223 ".section .opd,\"aw\"\n"
5226 ".long .%1$s,.TOC.@tocbase32\n"
5227 ".size %1$s,.-%1$s\n"
5229 ".type .%1$s,@function\n"
5230 ".%1$s:\n", symbol);
5241 "lis 3, .Lglobals@h\n"
5242 "ori 3, 3, .Lglobals@l\n"
5243 "bl .mono_aot_register_module\n"
5253 ".size .%s,.-.%s\n", symbol, symbol);
5256 ".size .%1$s,.-.%1$s\n", symbol);
5265 emit_mem_end (MonoAotCompile *acfg)
5269 sprintf (symbol, "mem_end");
5270 emit_section_change (acfg, ".text", 1);
5271 emit_global (acfg, symbol, FALSE);
5272 emit_alignment (acfg, 8);
5273 emit_label (acfg, symbol);
5277 * Emit a structure containing all the information not stored elsewhere.
5280 emit_file_info (MonoAotCompile *acfg)
5285 sprintf (symbol, "mono_aot_file_info");
5286 emit_section_change (acfg, ".data", 0);
5287 emit_alignment (acfg, 8);
5288 emit_label (acfg, symbol);
5289 emit_global (acfg, symbol, FALSE);
5291 /* The data emitted here must match MonoAotFileInfo in aot-runtime.c. */
5292 emit_int32 (acfg, acfg->plt_got_offset_base);
5293 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5294 emit_int32 (acfg, acfg->plt_offset);
5295 emit_int32 (acfg, acfg->nmethods);
5296 emit_int32 (acfg, acfg->flags);
5297 emit_int32 (acfg, acfg->opts);
5299 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5300 emit_int32 (acfg, acfg->num_trampolines [i]);
5301 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5302 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
5303 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
5304 emit_int32 (acfg, acfg->trampoline_size [i]);
5308 emit_blob (MonoAotCompile *acfg)
5312 sprintf (symbol, "blob");
5313 emit_section_change (acfg, ".text", 1);
5314 emit_global (acfg, symbol, FALSE);
5315 emit_alignment (acfg, 8);
5316 emit_label (acfg, symbol);
5318 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
5322 emit_dwarf_info (MonoAotCompile *acfg)
5324 #ifdef EMIT_DWARF_INFO
5326 char symbol [128], symbol2 [128];
5328 /* DIEs for methods */
5329 for (i = 0; i < acfg->nmethods; ++i) {
5330 MonoCompile *cfg = acfg->cfgs [i];
5335 // FIXME: LLVM doesn't define .Lme_...
5336 if (cfg->compile_llvm)
5339 sprintf (symbol, "%sm_%x", acfg->temp_prefix, i);
5340 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
5342 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, symbol, symbol2, 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 ()));
5348 collect_methods (MonoAotCompile *acfg)
5351 MonoImage *image = acfg->image;
5353 /* Collect methods */
5354 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
5356 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
5358 method = mono_get_method (acfg->image, token, NULL);
5361 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
5365 /* Load all methods eagerly to skip the slower lazy loading code */
5366 mono_class_setup_methods (method->klass);
5368 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5369 /* Compile the wrapper instead */
5370 /* We do this here instead of add_wrappers () because it is easy to do it here */
5371 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
5375 /* FIXME: Some mscorlib methods don't have debug info */
5377 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
5378 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5379 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5380 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
5381 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
5382 if (!mono_debug_lookup_method (method)) {
5383 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
5390 /* Since we add the normal methods first, their index will be equal to their zero based token index */
5391 add_method_with_index (acfg, method, i, FALSE);
5392 acfg->method_index ++;
5395 add_generic_instances (acfg);
5397 if (acfg->aot_opts.full_aot)
5398 add_wrappers (acfg);
5402 compile_methods (MonoAotCompile *acfg)
5406 if (acfg->aot_opts.nthreads > 0) {
5411 gpointer *user_data;
5412 MonoMethod **methods;
5414 methods_len = acfg->methods->len;
5416 len = acfg->methods->len / acfg->aot_opts.nthreads;
5419 * Partition the list of methods into fragments, and hand it to threads to
5422 threads = g_ptr_array_new ();
5423 /* Make a copy since acfg->methods is modified by compile_method () */
5424 methods = g_new0 (MonoMethod*, methods_len);
5425 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
5426 for (i = 0; i < methods_len; ++i)
5427 methods [i] = g_ptr_array_index (acfg->methods, i);
5429 while (i < methods_len) {
5430 frag = g_ptr_array_new ();
5431 for (j = 0; j < len; ++j) {
5432 if (i < methods_len) {
5433 g_ptr_array_add (frag, methods [i]);
5438 user_data = g_new0 (gpointer, 3);
5439 user_data [0] = mono_domain_get ();
5440 user_data [1] = acfg;
5441 user_data [2] = frag;
5443 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
5444 g_ptr_array_add (threads, handle);
5448 for (i = 0; i < threads->len; ++i) {
5449 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
5455 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
5456 for (i = methods_len; i < acfg->methods->len; ++i) {
5457 /* This can new methods to acfg->methods */
5458 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
5463 compile_asm (MonoAotCompile *acfg)
5465 char *command, *objfile;
5466 char *outfile_name, *tmp_outfile_name;
5467 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
5469 #if defined(TARGET_AMD64)
5470 #define AS_OPTIONS "--64"
5471 #elif defined(TARGET_POWERPC64)
5472 #define AS_OPTIONS "-a64 -mppc64"
5473 #define LD_OPTIONS "-m elf64ppc"
5474 #elif defined(sparc) && SIZEOF_VOID_P == 8
5475 #define AS_OPTIONS "-xarch=v9"
5477 #define AS_OPTIONS ""
5481 #define LD_OPTIONS ""
5485 #define EH_LD_OPTIONS "--eh-frame-hdr"
5487 #define EH_LD_OPTIONS ""
5490 if (acfg->aot_opts.asm_only) {
5491 printf ("Output file: '%s'.\n", acfg->tmpfname);
5492 if (acfg->aot_opts.static_link)
5493 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5497 if (acfg->aot_opts.static_link) {
5498 if (acfg->aot_opts.outfile)
5499 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5501 objfile = g_strdup_printf ("%s.o", acfg->image->name);
5503 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
5505 command = g_strdup_printf ("%sas %s %s -o %s", tool_prefix, AS_OPTIONS, acfg->tmpfname, objfile);
5506 printf ("Executing the native assembler: %s\n", command);
5507 if (system (command) != 0) {
5515 if (acfg->aot_opts.static_link) {
5516 printf ("Output file: '%s'.\n", objfile);
5517 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
5522 if (acfg->aot_opts.outfile)
5523 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5525 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5527 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5530 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5531 #elif defined(__ppc__) && defined(__MACH__)
5532 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5533 #elif defined(HOST_WIN32)
5534 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
5536 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
5538 printf ("Executing the native linker: %s\n", command);
5539 if (system (command) != 0) {
5540 g_free (tmp_outfile_name);
5541 g_free (outfile_name);
5549 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
5550 printf ("Stripping the binary: %s\n", com);
5554 #if defined(TARGET_ARM) && !defined(__MACH__)
5556 * gas generates 'mapping symbols' each time code and data is mixed, which
5557 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
5559 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
5560 printf ("Stripping the binary: %s\n", command);
5561 if (system (command) != 0) {
5562 g_free (tmp_outfile_name);
5563 g_free (outfile_name);
5570 rename (tmp_outfile_name, outfile_name);
5572 g_free (tmp_outfile_name);
5573 g_free (outfile_name);
5576 if (acfg->aot_opts.save_temps)
5577 printf ("Retained input file.\n");
5579 unlink (acfg->tmpfname);
5584 static MonoAotCompile*
5585 acfg_create (MonoAssembly *ass, guint32 opts)
5587 MonoImage *image = ass->image;
5588 MonoAotCompile *acfg;
5591 acfg = g_new0 (MonoAotCompile, 1);
5592 acfg->methods = g_ptr_array_new ();
5593 acfg->method_indexes = g_hash_table_new (NULL, NULL);
5594 acfg->method_depth = g_hash_table_new (NULL, NULL);
5595 acfg->plt_offset_to_patch = g_hash_table_new (NULL, NULL);
5596 acfg->patch_to_plt_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5597 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5598 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
5599 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
5600 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
5601 acfg->got_patches = g_ptr_array_new ();
5602 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
5603 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
5604 acfg->image_hash = g_hash_table_new (NULL, NULL);
5605 acfg->image_table = g_ptr_array_new ();
5606 acfg->globals = g_ptr_array_new ();
5607 acfg->image = image;
5609 acfg->mempool = mono_mempool_new ();
5610 acfg->extra_methods = g_ptr_array_new ();
5611 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
5612 acfg->unwind_ops = g_ptr_array_new ();
5613 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
5614 InitializeCriticalSection (&acfg->mutex);
5620 acfg_free (MonoAotCompile *acfg)
5624 img_writer_destroy (acfg->w);
5625 for (i = 0; i < acfg->nmethods; ++i)
5627 g_free (acfg->cfgs [i]);
5628 g_free (acfg->cfgs);
5629 g_free (acfg->static_linking_symbol);
5630 g_free (acfg->got_symbol);
5631 g_free (acfg->plt_symbol);
5632 g_ptr_array_free (acfg->methods, TRUE);
5633 g_ptr_array_free (acfg->got_patches, TRUE);
5634 g_ptr_array_free (acfg->image_table, TRUE);
5635 g_ptr_array_free (acfg->globals, TRUE);
5636 g_ptr_array_free (acfg->unwind_ops, TRUE);
5637 g_hash_table_destroy (acfg->method_indexes);
5638 g_hash_table_destroy (acfg->method_depth);
5639 g_hash_table_destroy (acfg->plt_offset_to_patch);
5640 g_hash_table_destroy (acfg->patch_to_plt_offset);
5641 g_hash_table_destroy (acfg->patch_to_got_offset);
5642 g_hash_table_destroy (acfg->method_to_cfg);
5643 g_hash_table_destroy (acfg->token_info_hash);
5644 g_hash_table_destroy (acfg->image_hash);
5645 g_hash_table_destroy (acfg->unwind_info_offsets);
5646 g_hash_table_destroy (acfg->method_label_hash);
5647 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
5648 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
5649 g_free (acfg->patch_to_got_offset_by_type);
5650 mono_mempool_destroy (acfg->mempool);
5655 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
5657 MonoImage *image = ass->image;
5659 MonoAotCompile *acfg;
5660 char *outfile_name, *tmp_outfile_name, *p;
5664 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
5666 acfg = acfg_create (ass, opts);
5668 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
5669 acfg->aot_opts.write_symbols = TRUE;
5670 acfg->aot_opts.ntrampolines = 1024;
5672 mono_aot_parse_options (aot_options, &acfg->aot_opts);
5674 if (acfg->aot_opts.static_link)
5675 acfg->aot_opts.autoreg = TRUE;
5677 //acfg->aot_opts.print_skipped_methods = TRUE;
5679 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5680 if (acfg->aot_opts.full_aot) {
5681 printf ("--aot=full is not supported on this platform.\n");
5686 if (acfg->aot_opts.static_link)
5687 acfg->aot_opts.asm_writer = TRUE;
5689 if (acfg->aot_opts.soft_debug) {
5690 MonoDebugOptions *opt = mini_get_debug_options ();
5692 opt->mdb_optimizations = TRUE;
5693 opt->gen_seq_points = TRUE;
5695 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
5696 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
5703 acfg->aot_opts.asm_writer = TRUE;
5704 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
5707 if (acfg->aot_opts.full_aot)
5708 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
5710 load_profile_files (acfg);
5712 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
5713 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
5714 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? 1024 : 0;
5716 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? 128 : 0;
5718 acfg->got_symbol = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
5719 acfg->plt_symbol = g_strdup_printf ("mono_aot_%s_plt", acfg->image->assembly->aname.name);
5721 /* Get rid of characters which cannot occur in symbols */
5722 for (p = acfg->got_symbol; *p; ++p) {
5723 if (!(isalnum (*p) || *p == '_'))
5726 for (p = acfg->plt_symbol; *p; ++p) {
5727 if (!(isalnum (*p) || *p == '_'))
5731 acfg->method_index = 1;
5733 collect_methods (acfg);
5735 acfg->cfgs_size = acfg->methods->len + 32;
5736 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
5738 /* PLT offset 0 is reserved for the PLT trampoline */
5739 acfg->plt_offset = 1;
5743 mono_llvm_create_aot_module (acfg->got_symbol);
5746 /* GOT offset 0 is reserved for the address of the current assembly */
5750 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
5751 ji->type = MONO_PATCH_INFO_IMAGE;
5752 ji->data.image = acfg->image;
5754 get_got_offset (acfg, ji);
5756 /* Slot 1 is reserved for the mscorlib got addr */
5757 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
5758 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
5759 get_got_offset (acfg, ji);
5764 compile_methods (acfg);
5768 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
5773 emit_llvm_file (acfg);
5776 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
5777 if (acfg->aot_opts.outfile)
5778 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5780 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
5783 * Can't use g_file_open_tmp () as it will be deleted at exit, and
5784 * it might be in another file system so the rename () won't work.
5786 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
5788 acfg->fp = fopen (tmp_outfile_name, "w");
5790 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
5794 acfg->w = img_writer_create (acfg->fp, TRUE);
5795 acfg->use_bin_writer = TRUE;
5798 /* Append to the .s file created by llvm */
5799 /* FIXME: Use multiple files instead */
5800 acfg->tmpfname = g_strdup ("temp.s");
5801 acfg->fp = fopen (acfg->tmpfname, "a");
5803 if (acfg->aot_opts.asm_only) {
5804 if (acfg->aot_opts.outfile)
5805 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
5807 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
5808 acfg->fp = fopen (acfg->tmpfname, "w+");
5810 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
5811 acfg->fp = fdopen (i, "w+");
5813 g_assert (acfg->fp);
5815 acfg->w = img_writer_create (acfg->fp, FALSE);
5817 tmp_outfile_name = NULL;
5818 outfile_name = NULL;
5821 acfg->temp_prefix = img_writer_get_temp_label_prefix (acfg->w);
5823 if (!acfg->aot_opts.nodebug)
5824 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
5826 img_writer_emit_start (acfg->w);
5829 mono_dwarf_writer_emit_base_info (acfg->dwarf, arch_get_cie_program ());
5835 emit_extra_methods (acfg);
5837 emit_trampolines (acfg);
5839 emit_class_name_table (acfg);
5841 emit_got_info (acfg);
5843 emit_exception_info (acfg);
5845 emit_unwind_info (acfg);
5847 emit_class_info (acfg);
5851 emit_image_table (acfg);
5855 emit_file_info (acfg);
5859 emit_globals (acfg);
5861 emit_autoreg (acfg);
5864 emit_dwarf_info (acfg);
5865 mono_dwarf_writer_close (acfg->dwarf);
5868 emit_mem_end (acfg);
5872 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
5875 g_assert (acfg->got_offset == acfg->final_got_size);
5877 printf ("Code: %d Info: %d Ex Info: %d Unwind Info: %d Class Info: %d PLT: %d GOT Info: %d GOT: %d Offsets: %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, (int)(acfg->got_offset * sizeof (gpointer)), acfg->stats.offsets_size);
5880 res = img_writer_emit_writeout (acfg->w);
5885 if (acfg->use_bin_writer) {
5886 int err = rename (tmp_outfile_name, outfile_name);
5889 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
5893 res = compile_asm (acfg);
5900 acfg->stats.link_time = TV_ELAPSED (atv, btv);
5902 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);
5903 if (acfg->stats.genericcount)
5904 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
5905 if (acfg->stats.abscount)
5906 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
5907 if (acfg->stats.lmfcount)
5908 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
5909 if (acfg->stats.ocount)
5910 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
5912 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
5913 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);
5914 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
5916 if (acfg->aot_opts.stats) {
5919 printf ("GOT slot distribution:\n");
5920 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
5921 if (acfg->stats.got_slot_types [i])
5922 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
5925 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);
5933 * Support for emitting debug info for JITted code.
5935 * This works as follows:
5936 * - the runtime writes out an xdb.s file containing DWARF debug info.
5937 * - the user calls a gdb macro
5938 * - the macro compiles and loads this shared library using add-symbol-file.
5940 * This is based on the xdebug functionality in the Kaffe Java VM.
5942 * We emit assembly code instead of using the ELF writer, so we can emit debug info
5943 * incrementally as each method is JITted, and the debugger doesn't have to call
5944 * into the runtime to emit the shared library, which would cause all kinds of
5945 * complications, like threading issues, and the fact that the ELF writer's
5946 * emit_writeout () function cannot be called more than once.
5947 * GDB 7.0 and later has a JIT interface.
5950 #define USE_GDB_JIT_INTERFACE
5952 /* The recommended gdb macro is: */
5955 shell rm -f xdb.so && as --64 -o xdb.o xdb.s && ld -shared -o xdb.so xdb.o
5956 add-symbol-file xdb.so 0
5961 * GDB JIT interface definitions.
5963 * http://sources.redhat.com/gdb/onlinedocs/gdb_30.html
5972 struct jit_code_entry
5974 struct jit_code_entry *next_entry;
5975 struct jit_code_entry *prev_entry;
5976 const char *symfile_addr;
5977 guint64 symfile_size;
5980 struct jit_descriptor
5983 /* This type should be jit_actions_t, but we use guint32
5984 to be explicit about the bitwidth. */
5985 guint32 action_flag;
5986 struct jit_code_entry *relevant_entry;
5987 struct jit_code_entry *first_entry;
5992 #define MONO_NOINLINE __declspec (noinline)
5994 #define MONO_NOINLINE __attribute__((noinline))
5997 /* GDB puts a breakpoint in this function. */
5998 void MONO_NOINLINE __jit_debug_register_code(void);
6000 #if defined(ENABLE_LLVM) && ((LLVM_MAJOR_VERSION == 2 && LLVM_MINOR_VERSION >= 7) || LLVM_MAJOR_VERSION > 2)
6001 /* LLVM already defines these */
6002 extern struct jit_descriptor __jit_debug_descriptor;
6005 /* Make sure to specify the version statically, because the
6006 debugger may check the version before we can set it. */
6007 struct jit_descriptor __jit_debug_descriptor = { 1, 0, 0, 0 };
6009 void MONO_NOINLINE __jit_debug_register_code(void) { };
6012 static MonoImageWriter *xdebug_w;
6013 static MonoDwarfWriter *xdebug_writer;
6014 static FILE *xdebug_fp, *il_file;
6015 static gboolean use_gdb_interface, save_symfiles;
6016 static int il_file_line_index;
6017 static GHashTable *xdebug_syms;
6020 mono_xdebug_init (char *options)
6025 args = g_strsplit (options, ",", -1);
6026 for (ptr = args; ptr && *ptr; ptr ++) {
6029 if (!strcmp (arg, "gdb"))
6030 use_gdb_interface = TRUE;
6031 if (!strcmp (arg, "save-symfiles"))
6032 save_symfiles = TRUE;
6035 /* This file will contain the IL code for methods which don't have debug info */
6036 il_file = fopen ("xdb.il", "w");
6038 if (use_gdb_interface)
6042 xdebug_fp = fopen ("xdb.s", "w");
6044 w = img_writer_create (xdebug_fp, FALSE);
6046 img_writer_emit_start (w);
6048 xdebug_writer = mono_dwarf_writer_create (w, il_file, 0, TRUE);
6050 /* Emit something so the file has a text segment */
6051 img_writer_emit_section_change (w, ".text", 0);
6052 img_writer_emit_string (w, "");
6054 mono_dwarf_writer_emit_base_info (xdebug_writer, arch_get_cie_program ());
6058 xdebug_begin_emit (MonoImageWriter **out_w, MonoDwarfWriter **out_dw)
6061 MonoDwarfWriter *dw;
6063 w = img_writer_create (NULL, TRUE);
6065 img_writer_emit_start (w);
6067 /* This file will contain the IL code for methods which don't have debug info */
6069 il_file = fopen ("xdb.il", "w");
6071 dw = mono_dwarf_writer_create (w, il_file, il_file_line_index, FALSE);
6073 mono_dwarf_writer_emit_base_info (dw, arch_get_cie_program ());
6080 xdebug_end_emit (MonoImageWriter *w, MonoDwarfWriter *dw, MonoMethod *method)
6084 struct jit_code_entry *entry;
6086 il_file_line_index = mono_dwarf_writer_get_il_file_line_index (dw);
6087 mono_dwarf_writer_close (dw);
6089 img_writer_emit_writeout (w);
6091 img = img_writer_get_output (w, &img_size);
6093 img_writer_destroy (w);
6096 /* Save the symbol files to help debugging */
6099 static int file_counter;
6102 file_name = g_strdup_printf ("xdb-%d.o", file_counter);
6103 //printf ("%s -> %s\n", mono_method_full_name (method, TRUE), file_name);
6105 fp = fopen (file_name, "w");
6106 fwrite (img, img_size, 1, fp);
6111 /* Register the image with GDB */
6113 entry = g_malloc (sizeof (struct jit_code_entry));
6115 entry->symfile_addr = (const char*)img;
6116 entry->symfile_size = img_size;
6118 entry->next_entry = __jit_debug_descriptor.first_entry;
6119 if (__jit_debug_descriptor.first_entry)
6120 __jit_debug_descriptor.first_entry->prev_entry = entry;
6121 __jit_debug_descriptor.first_entry = entry;
6123 __jit_debug_descriptor.relevant_entry = entry;
6124 __jit_debug_descriptor.action_flag = JIT_REGISTER_FN;
6126 __jit_debug_register_code ();
6130 * mono_xdebug_flush:
6132 * This could be called from inside gdb to flush the debugging information not yet
6133 * registered with gdb.
6136 mono_xdebug_flush (void)
6139 xdebug_end_emit (xdebug_w, xdebug_writer, NULL);
6141 xdebug_begin_emit (&xdebug_w, &xdebug_writer);
6144 static int xdebug_method_count;
6147 * mono_save_xdebug_info:
6149 * Emit debugging info for METHOD into an assembly file which can be assembled
6150 * and loaded into gdb to provide debugging info for JITted code.
6151 * LOCKING: Acquires the loader lock.
6154 mono_save_xdebug_info (MonoCompile *cfg)
6156 if (use_gdb_interface) {
6157 mono_loader_lock ();
6160 xdebug_syms = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6163 * gdb is not designed to handle 1000s of symbol files (one per method). So we
6164 * group them into groups of 100.
6166 if ((xdebug_method_count % 100) == 0)
6167 mono_xdebug_flush ();
6169 xdebug_method_count ++;
6171 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 ()));
6175 * Emit a symbol for the code by emitting it at the beginning of the text
6176 * segment, and setting the text segment to have an absolute address.
6177 * This symbol can be used to set breakpoints in gdb.
6178 * FIXME: This doesn't work when multiple methods are emitted into the same file.
6180 sym = get_debug_sym (cfg->jit_info->method, "", xdebug_syms);
6181 img_writer_emit_section_change (w, ".text", 0);
6182 if (!xdebug_text_addr) {
6183 xdebug_text_addr = cfg->jit_info->code_start;
6184 img_writer_set_section_addr (w, (gssize)xdebug_text_addr);
6186 img_writer_emit_global_with_size (w, sym, cfg->jit_info->code_size, TRUE);
6187 img_writer_emit_label (w, sym);
6188 img_writer_emit_bytes (w, cfg->jit_info->code_start, cfg->jit_info->code_size);
6192 mono_loader_unlock ();
6197 mono_loader_lock ();
6198 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 ()));
6200 mono_loader_unlock ();
6205 * mono_save_trampoline_xdebug_info:
6207 * Same as mono_save_xdebug_info, but for trampolines.
6208 * LOCKING: Acquires the loader lock.
6211 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)
6213 if (use_gdb_interface) {
6215 MonoDwarfWriter *dw;
6217 mono_loader_lock ();
6219 xdebug_begin_emit (&w, &dw);
6221 mono_dwarf_writer_emit_trampoline (dw, tramp_name, NULL, NULL, code, code_size, unwind_info);
6223 xdebug_end_emit (w, dw, NULL);
6225 mono_loader_unlock ();
6230 mono_loader_lock ();
6231 mono_dwarf_writer_emit_trampoline (xdebug_writer, tramp_name, NULL, NULL, code, code_size, unwind_info);
6233 mono_loader_unlock ();
6242 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6248 mono_xdebug_init (char *options)
6253 mono_save_xdebug_info (MonoCompile *cfg)
6258 mono_save_trampoline_xdebug_info (const char *tramp_name, guint8 *code, guint32 code_size, GSList *unwind_info)