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-internal.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 #if defined(__linux__) || defined(__native_client_codegen__)
72 #define RODATA_SECT ".rodata"
74 #define RODATA_SECT ".text"
77 #define TV_DECLARE(name) gint64 name
78 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
79 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
82 #define SHARED_EXT ".dll"
83 #elif defined(__ppc__) && defined(__MACH__)
84 #define SHARED_EXT ".dylib"
85 #elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
86 #define SHARED_EXT ".dylib"
88 #define SHARED_EXT ".so"
91 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
92 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
93 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
95 typedef struct MonoAotOptions {
98 gboolean write_symbols;
99 gboolean metadata_only;
100 gboolean bind_to_runtime_version;
103 gboolean static_link;
110 int nrgctx_trampolines;
111 int nimt_trampolines;
112 gboolean print_skipped_methods;
119 typedef struct MonoAotStats {
120 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
121 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
122 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
123 int got_slots, offsets_size;
124 int got_slot_types [MONO_PATCH_INFO_NONE];
125 int jit_time, gen_time, link_time;
128 typedef struct MonoAotCompile {
131 GHashTable *method_indexes;
132 GHashTable *method_depth;
135 GHashTable *patch_to_plt_entry;
136 GHashTable *plt_offset_to_entry;
137 GHashTable *patch_to_got_offset;
138 GHashTable **patch_to_got_offset_by_type;
139 GPtrArray *got_patches;
140 GHashTable *image_hash;
141 GHashTable *method_to_cfg;
142 GHashTable *token_info_hash;
143 GPtrArray *extra_methods;
144 GPtrArray *image_table;
147 guint32 *plt_got_info_offsets;
148 guint32 got_offset, plt_offset, plt_got_offset_base;
149 guint32 final_got_size;
150 /* Number of GOT entries reserved for trampolines */
151 guint32 num_trampoline_got_entries;
153 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
154 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
155 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
157 MonoAotOptions aot_opts;
160 MonoMemPool *mempool;
163 char *static_linking_symbol;
164 CRITICAL_SECTION mutex;
165 gboolean use_bin_writer;
167 MonoDwarfWriter *dwarf;
171 GHashTable *unwind_info_offsets;
172 GPtrArray *unwind_ops;
173 guint32 unwind_info_offset;
174 char *got_symbol_base;
177 GHashTable *method_label_hash;
178 const char *temp_prefix;
179 const char *llvm_label_prefix;
180 guint32 label_generator;
182 MonoAotFileFlags flags;
183 MonoDynamicStream blob;
184 MonoClass **typespec_classes;
187 gboolean thumb_mixed;
192 char *symbol, *llvm_symbol, *debug_sym;
194 gboolean jit_used, llvm_used;
197 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
198 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
200 /* This points to the current acfg in LLVM mode */
201 static MonoAotCompile *llvm_acfg;
203 #ifdef HAVE_ARRAY_ELEM_INIT
204 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
205 #define MSGSTRFIELD1(line) str##line
206 static const struct msgstr_t {
207 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
208 #include "patch-info.h"
211 #define PATCH_INFO(a,b) b,
212 #include "patch-info.h"
215 static const gint16 opidx [] = {
216 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
217 #include "patch-info.h"
221 static G_GNUC_UNUSED const char*
222 get_patch_name (int info)
224 return (const char*)&opstr + opidx [info];
228 #define PATCH_INFO(a,b) b,
229 static const char* const
230 patch_types [MONO_PATCH_INFO_NUM + 1] = {
231 #include "patch-info.h"
235 static G_GNUC_UNUSED const char*
236 get_patch_name (int info)
238 return patch_types [info];
243 /* Wrappers around the image writer functions */
246 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
248 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
252 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
254 img_writer_emit_push_section (acfg->w, section_name, subsection);
258 emit_pop_section (MonoAotCompile *acfg)
260 img_writer_emit_pop_section (acfg->w);
264 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
266 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
270 emit_label (MonoAotCompile *acfg, const char *name)
272 img_writer_emit_label (acfg->w, name);
276 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
278 img_writer_emit_bytes (acfg->w, buf, size);
282 emit_string (MonoAotCompile *acfg, const char *value)
284 img_writer_emit_string (acfg->w, value);
288 emit_line (MonoAotCompile *acfg)
290 img_writer_emit_line (acfg->w);
294 emit_alignment (MonoAotCompile *acfg, int size)
296 img_writer_emit_alignment (acfg->w, size);
300 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
302 img_writer_emit_pointer_unaligned (acfg->w, target);
306 emit_pointer (MonoAotCompile *acfg, const char *target)
308 img_writer_emit_pointer (acfg->w, target);
312 emit_int16 (MonoAotCompile *acfg, int value)
314 img_writer_emit_int16 (acfg->w, value);
318 emit_int32 (MonoAotCompile *acfg, int value)
320 img_writer_emit_int32 (acfg->w, value);
324 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
326 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
330 emit_zero_bytes (MonoAotCompile *acfg, int num)
332 img_writer_emit_zero_bytes (acfg->w, num);
336 emit_byte (MonoAotCompile *acfg, guint8 val)
338 img_writer_emit_byte (acfg->w, val);
341 #ifdef __native_client_codegen__
343 emit_nacl_call_alignment (MonoAotCompile *acfg)
345 img_writer_emit_nacl_call_alignment (acfg->w);
349 static G_GNUC_UNUSED void
350 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
352 img_writer_emit_global (acfg->w, name, func);
356 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
358 if (acfg->aot_opts.no_dlsym) {
359 g_ptr_array_add (acfg->globals, g_strdup (name));
360 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
362 img_writer_emit_global (acfg->w, name, func);
367 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
369 img_writer_emit_symbol_size (acfg->w, name, end_label);
373 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
375 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
376 emit_global (acfg, name, FALSE);
377 img_writer_emit_label (acfg->w, name);
378 img_writer_emit_string (acfg->w, value);
382 emit_local_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
384 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
385 img_writer_emit_label (acfg->w, name);
386 img_writer_emit_string (acfg->w, value);
389 static G_GNUC_UNUSED void
390 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
393 guint8 b = value & 0x7f;
395 if (value != 0) /* more bytes to come */
401 static G_GNUC_UNUSED void
402 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
405 gboolean negative = (value < 0);
412 /* the following is unnecessary if the
413 * implementation of >>= uses an arithmetic rather
414 * than logical shift for a signed left operand
418 value |= - ((gint64)1 <<(size - 7));
419 /* sign bit of byte is second high order bit (0x40) */
420 if ((value == 0 && !(byte & 0x40)) ||
421 (value == -1 && (byte & 0x40)))
425 emit_byte (acfg, byte);
429 static G_GNUC_UNUSED void
430 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
435 guint8 b = value & 0x7f;
437 if (value != 0) /* more bytes to come */
445 static G_GNUC_UNUSED void
446 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
449 gboolean negative = (value < 0);
457 /* the following is unnecessary if the
458 * implementation of >>= uses an arithmetic rather
459 * than logical shift for a signed left operand
463 value |= - (1 <<(size - 7));
464 /* sign bit of byte is second high order bit (0x40) */
465 if ((value == 0 && !(byte & 0x40)) ||
466 (value == -1 && (byte & 0x40)))
476 /* ARCHITECTURE SPECIFIC CODE */
478 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
479 #define EMIT_DWARF_INFO 1
482 #if defined(TARGET_ARM)
483 #define AOT_FUNC_ALIGNMENT 4
485 #define AOT_FUNC_ALIGNMENT 16
487 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
488 #undef AOT_FUNC_ALIGNMENT
489 #define AOT_FUNC_ALIGNMENT 32
492 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
493 #define PPC_LD_OP "ld"
494 #define PPC_LDX_OP "ldx"
496 #define PPC_LD_OP "lwz"
497 #define PPC_LDX_OP "lwzx"
501 arch_init (MonoAotCompile *acfg)
503 acfg->llc_args = g_string_new ("");
504 acfg->as_args = g_string_new ("");
507 * The prefix LLVM likes to put in front of symbol names on darwin.
508 * The mach-os specs require this for globals, but LLVM puts them in front of all
509 * symbols. We need to handle this, since we need to refer to LLVM generated
512 acfg->llvm_label_prefix = "";
515 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
516 g_string_append (acfg->llc_args, "-mattr=+v6");
517 acfg->llvm_label_prefix = "_";
520 g_string_append (acfg->llc_args, " -mattr=+vfp2,+d16");
521 g_string_append (acfg->as_args, " -mfpu=vfp3");
523 g_string_append (acfg->llc_args, " -soft-float");
526 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
527 acfg->thumb_mixed = TRUE;
529 if (acfg->aot_opts.mtriple)
530 mono_arch_set_target (acfg->aot_opts.mtriple);
535 * arch_emit_direct_call:
537 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
541 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
543 #if defined(TARGET_X86) || defined(TARGET_AMD64)
544 /* Need to make sure this is exactly 5 bytes long */
545 emit_byte (acfg, '\xe8');
546 emit_symbol_diff (acfg, target, ".", -4);
548 #elif defined(TARGET_ARM)
549 if (acfg->use_bin_writer) {
556 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
557 emit_bytes (acfg, buf, 4);
559 img_writer_emit_unset_mode (acfg->w);
560 fprintf (acfg->fp, "bl %s\n", target);
563 #elif defined(TARGET_POWERPC)
564 if (acfg->use_bin_writer) {
565 g_assert_not_reached ();
567 img_writer_emit_unset_mode (acfg->w);
568 fprintf (acfg->fp, "bl %s\n", target);
572 g_assert_not_reached ();
578 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
580 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
581 * in in the 2. slot of every GOT, and require every method to place the GOT
582 * address in r30, even when it doesn't access the GOT otherwise. This way,
583 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
588 * PPC64 uses function descriptors which greatly complicate all code, since
589 * these are used very inconsistently in the runtime. Some functions like
590 * mono_compile_method () return ftn descriptors, while others like the
591 * trampoline creation functions do not.
592 * We assume that all GOT slots contain function descriptors, and create
593 * descriptors in aot-runtime.c when needed.
594 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
595 * from function descriptors, we could do the same, but it would require
596 * rewriting all the ppc/aot code to handle function descriptors properly.
597 * So instead, we use the same approach as on PPC32.
598 * This is a horrible mess, but fixing it would probably lead to an even bigger
604 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
607 #ifdef MONO_ARCH_AOT_SUPPORTED
609 * arch_emit_got_offset:
611 * The memory pointed to by CODE should hold native code for computing the GOT
612 * address. Emit this code while patching it with the offset between code and
613 * the GOT. CODE_SIZE is set to the number of bytes emitted.
616 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
618 #if defined(TARGET_POWERPC64)
619 g_assert (!acfg->use_bin_writer);
620 img_writer_emit_unset_mode (acfg->w);
622 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
623 * unsupported relocations. So we store the got address into the .Lgot_addr
624 * symbol which is in the text segment, compute its address, and load it.
626 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
627 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
628 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
629 fprintf (acfg->fp, "add 30, 30, 0\n");
630 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
631 acfg->label_generator ++;
633 #elif defined(TARGET_POWERPC)
634 g_assert (!acfg->use_bin_writer);
635 img_writer_emit_unset_mode (acfg->w);
636 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
637 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
638 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
639 acfg->label_generator ++;
642 guint32 offset = mono_arch_get_patch_offset (code);
643 emit_bytes (acfg, code, offset);
644 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
646 *code_size = offset + 4;
651 * arch_emit_got_access:
653 * The memory pointed to by CODE should hold native code for loading a GOT
654 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
655 * CODE_SIZE is set to the number of bytes emitted.
658 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
660 /* Emit beginning of instruction */
661 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
663 /* Emit the offset */
665 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
666 *code_size = mono_arch_get_patch_offset (code) + 4;
667 #elif defined(TARGET_X86)
668 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
669 *code_size = mono_arch_get_patch_offset (code) + 4;
670 #elif defined(TARGET_ARM)
671 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
672 *code_size = mono_arch_get_patch_offset (code) + 4;
673 #elif defined(TARGET_POWERPC)
679 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
680 g_assert (code - buf == 8);
681 emit_bytes (acfg, buf, code - buf);
682 *code_size = code - buf;
685 g_assert_not_reached ();
692 * arch_emit_plt_entry:
694 * Emit code for the PLT entry with index INDEX.
697 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
699 #if defined(TARGET_X86)
700 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
701 #if defined(__default_codegen__)
702 /* jmp *<offset>(%ebx) */
703 emit_byte (acfg, 0xff);
704 emit_byte (acfg, 0xa3);
705 emit_int32 (acfg, offset);
706 /* Used by mono_aot_get_plt_info_offset */
707 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
708 #elif defined(__native_client_codegen__)
709 const guint8 kSizeOfNaClJmp = 11;
710 guint8 bytes[kSizeOfNaClJmp];
711 guint8 *pbytes = &bytes[0];
713 x86_jump_membase32 (pbytes, X86_EBX, offset);
714 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
715 /* four bytes of data, used by mono_arch_patch_plt_entry */
716 /* For Native Client, make this work with data embedded in push. */
717 emit_byte (acfg, 0x68); /* hide data in a push */
718 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
719 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
720 #endif /*__native_client_codegen__*/
721 #elif defined(TARGET_AMD64)
722 #if defined(__default_codegen__)
724 * We can't emit jumps because they are 32 bits only so they can't be patched.
725 * So we make indirect calls through GOT entries which are patched by the AOT
726 * loader to point to .Lpd entries.
728 /* jmpq *<offset>(%rip) */
729 emit_byte (acfg, '\xff');
730 emit_byte (acfg, '\x25');
731 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
732 /* Used by mono_aot_get_plt_info_offset */
733 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
734 #elif defined(__native_client_codegen__)
736 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
737 guint8 *code = buf_aligned;
739 /* mov <OFFSET>(%rip), %r11d */
740 emit_byte (acfg, '\x45');
741 emit_byte (acfg, '\x8b');
742 emit_byte (acfg, '\x1d');
743 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
745 amd64_jump_reg (code, AMD64_R11);
746 /* This should be constant for the plt patch */
747 g_assert ((size_t)(code-buf_aligned) == 10);
748 emit_bytes (acfg, buf_aligned, code - buf_aligned);
750 /* Hide data in a push imm32 so it passes validation */
751 emit_byte (acfg, 0x68); /* push */
752 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
753 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
754 #endif /*__native_client_codegen__*/
755 #elif defined(TARGET_ARM)
760 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
761 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
762 emit_bytes (acfg, buf, code - buf);
763 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
764 /* Used by mono_aot_get_plt_info_offset */
765 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
766 #elif defined(TARGET_POWERPC)
767 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
769 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
770 g_assert (!acfg->use_bin_writer);
771 img_writer_emit_unset_mode (acfg->w);
772 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
773 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
774 fprintf (acfg->fp, "add 11, 11, 30\n");
775 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
776 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
777 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
778 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
780 fprintf (acfg->fp, "mtctr 11\n");
781 fprintf (acfg->fp, "bctr\n");
782 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
784 g_assert_not_reached ();
789 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
791 #if defined(TARGET_ARM)
793 /* LLVM calls the PLT entries using bl, so emit a stub */
794 /* FIXME: Too much overhead on every call */
795 fprintf (acfg->fp, ".thumb_func\n");
796 fprintf (acfg->fp, "bx pc\n");
797 fprintf (acfg->fp, "nop\n");
798 fprintf (acfg->fp, ".arm\n");
800 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
801 fprintf (acfg->fp, ".thumb_func\n");
802 /* The code below should be 12 bytes long */
803 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
804 /* thumb can't encode ld pc, [pc, ip] */
805 fprintf (acfg->fp, "add ip, pc, ip\n");
806 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
807 fprintf (acfg->fp, "bx ip\n");
808 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
809 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
811 g_assert_not_reached ();
816 * arch_emit_specific_trampoline:
818 * Emit code for a specific trampoline. OFFSET is the offset of the first of
819 * two GOT slots which contain the generic trampoline address and the trampoline
820 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
823 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
826 * The trampolines created here are variations of the specific
827 * trampolines created in mono_arch_create_specific_trampoline (). The
829 * - the generic trampoline address is taken from a got slot.
830 * - the offset of the got slot where the trampoline argument is stored
831 * is embedded in the instruction stream, and the generic trampoline
832 * can load the argument by loading the offset, adding it to the
833 * address of the trampoline to get the address of the got slot, and
834 * loading the argument from there.
835 * - all the trampolines should be of the same length.
837 #if defined(TARGET_AMD64)
838 #if defined(__default_codegen__)
839 /* This should be exactly 16 bytes long */
841 /* call *<offset>(%rip) */
842 emit_byte (acfg, '\x41');
843 emit_byte (acfg, '\xff');
844 emit_byte (acfg, '\x15');
845 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
846 /* This should be relative to the start of the trampoline */
847 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
848 emit_zero_bytes (acfg, 5);
849 #elif defined(__native_client_codegen__)
851 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
852 guint8 *code = buf_aligned;
857 /* Emit this call in 'code' so we can find out how long it is. */
858 amd64_call_reg (code, AMD64_R11);
859 call_start = mono_arch_nacl_skip_nops (buf_aligned);
860 call_len = code - call_start;
862 /* The tramp_size is twice the NaCl alignment because it starts with */
863 /* a call which needs to be aligned to the end of the boundary. */
864 *tramp_size = kNaClAlignment*2;
866 /* Emit nops to align call site below which is 7 bytes plus */
867 /* the length of the call sequence emitted above. */
868 /* Note: this requires the specific trampoline starts on a */
869 /* kNaclAlignedment aligned address, which it does because */
870 /* it's its own function that is aligned. */
872 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
873 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
874 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
876 /* The trampoline is stored at the offset'th pointer, the -4 is */
877 /* present because RIP relative addressing starts at the end of */
878 /* the current instruction, while the label "." is relative to */
879 /* the beginning of the current asm location, which in this case */
880 /* is not the mov instruction, but the offset itself, due to the */
881 /* way the bytes and ints are emitted here. */
882 got_offset = (offset * sizeof(gpointer)) - 4;
884 /* mov <OFFSET>(%rip), %r11d */
885 emit_byte (acfg, '\x45');
886 emit_byte (acfg, '\x8b');
887 emit_byte (acfg, '\x1d');
888 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
891 emit_bytes (acfg, call_start, call_len);
893 /* The arg is stored at the offset+1 pointer, relative to beginning */
894 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
895 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
897 /* We can't emit this data directly, hide in a "push imm32" */
898 emit_byte (acfg, '\x68'); /* push */
899 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
900 emit_alignment (acfg, kNaClAlignment);
901 #endif /*__native_client_codegen__*/
902 #elif defined(TARGET_ARM)
906 /* This should be exactly 20 bytes long */
909 ARM_PUSH (code, 0x5fff);
910 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
911 /* Load the value from the GOT */
912 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
914 ARM_BLX_REG (code, ARMREG_R1);
916 g_assert (code - buf == 16);
919 emit_bytes (acfg, buf, code - buf);
921 * Only one offset is needed, since the second one would be equal to the
924 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
925 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
926 #elif defined(TARGET_POWERPC)
933 g_assert (!acfg->use_bin_writer);
936 * PPC has no ip relative addressing, so we need to compute the address
937 * of the mscorlib got. That is slow and complex, so instead, we store it
938 * in the second got slot of every aot image. The caller already computed
939 * the address of its got and placed it into r30.
941 img_writer_emit_unset_mode (acfg->w);
942 /* Load mscorlib got address */
943 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
944 /* Load generic trampoline address */
945 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
946 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
947 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
948 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
949 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
951 fprintf (acfg->fp, "mtctr 11\n");
952 /* Load trampoline argument */
953 /* On ppc, we pass it normally to the generic trampoline */
954 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
955 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
956 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
957 /* Branch to generic trampoline */
958 fprintf (acfg->fp, "bctr\n");
960 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
961 *tramp_size = 10 * 4;
965 #elif defined(TARGET_X86)
969 /* Similar to the PPC code above */
971 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
973 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
974 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
975 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
979 /* Load mscorlib got address */
980 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
981 /* Push trampoline argument */
982 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
983 /* Load generic trampoline address */
984 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
985 /* Branch to generic trampoline */
986 x86_jump_reg (code, X86_ECX);
988 #ifdef __native_client_codegen__
990 /* emit nops to next 32 byte alignment */
991 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
992 while (code < (buf + a)) x86_nop(code);
995 emit_bytes (acfg, buf, code - buf);
997 *tramp_size = NACL_SIZE(17, kNaClAlignment);
998 g_assert (code - buf == *tramp_size);
1000 g_assert_not_reached ();
1005 * arch_emit_unbox_trampoline:
1007 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1008 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1011 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, const char *call_target)
1013 #if defined(TARGET_AMD64)
1018 this_reg = mono_arch_get_this_arg_reg (NULL);
1020 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1022 emit_bytes (acfg, buf, code - buf);
1024 emit_byte (acfg, '\xe9');
1025 emit_symbol_diff (acfg, call_target, ".", -4);
1026 #elif defined(TARGET_X86)
1033 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1035 emit_bytes (acfg, buf, code - buf);
1038 emit_byte (acfg, '\xe9');
1039 emit_symbol_diff (acfg, call_target, ".", -4);
1040 #elif defined(TARGET_ARM)
1046 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1048 emit_bytes (acfg, buf, code - buf);
1049 /* jump to method */
1050 if (acfg->use_bin_writer) {
1057 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1058 emit_bytes (acfg, buf, 4);
1060 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1062 #elif defined(TARGET_POWERPC)
1065 g_assert (!acfg->use_bin_writer);
1067 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1068 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1070 g_assert_not_reached ();
1075 * arch_emit_static_rgctx_trampoline:
1077 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1078 * two GOT slots which contain the rgctx argument, and the method to jump to.
1079 * TRAMP_SIZE is set to the size of the emitted trampoline.
1080 * These kinds of trampolines cannot be enumerated statically, since there could
1081 * be one trampoline per method instantiation, so we emit the same code for all
1082 * trampolines, and parameterize them using two GOT slots.
1085 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1087 #if defined(TARGET_AMD64)
1088 #if defined(__default_codegen__)
1089 /* This should be exactly 13 bytes long */
1092 /* mov <OFFSET>(%rip), %r10 */
1093 emit_byte (acfg, '\x4d');
1094 emit_byte (acfg, '\x8b');
1095 emit_byte (acfg, '\x15');
1096 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1098 /* jmp *<offset>(%rip) */
1099 emit_byte (acfg, '\xff');
1100 emit_byte (acfg, '\x25');
1101 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1102 #elif defined(__native_client_codegen__)
1104 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1105 guint8 *code = buf_aligned;
1107 /* mov <OFFSET>(%rip), %r10d */
1108 emit_byte (acfg, '\x45');
1109 emit_byte (acfg, '\x8b');
1110 emit_byte (acfg, '\x15');
1111 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1113 /* mov <OFFSET>(%rip), %r11d */
1114 emit_byte (acfg, '\x45');
1115 emit_byte (acfg, '\x8b');
1116 emit_byte (acfg, '\x1d');
1117 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1120 amd64_jump_reg (code, AMD64_R11);
1121 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1123 emit_alignment (acfg, kNaClAlignment);
1124 *tramp_size = kNaClAlignment;
1125 #endif /*__native_client_codegen__*/
1127 #elif defined(TARGET_ARM)
1131 /* This should be exactly 24 bytes long */
1134 /* Load rgctx value */
1135 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1136 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1137 /* Load branch addr + branch */
1138 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1139 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1141 g_assert (code - buf == 16);
1144 emit_bytes (acfg, buf, code - buf);
1145 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1146 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1147 #elif defined(TARGET_POWERPC)
1154 g_assert (!acfg->use_bin_writer);
1157 * PPC has no ip relative addressing, so we need to compute the address
1158 * of the mscorlib got. That is slow and complex, so instead, we store it
1159 * in the second got slot of every aot image. The caller already computed
1160 * the address of its got and placed it into r30.
1162 img_writer_emit_unset_mode (acfg->w);
1163 /* Load mscorlib got address */
1164 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1166 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1167 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1168 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1169 /* Load target address */
1170 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1171 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1172 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1173 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1174 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1175 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1177 fprintf (acfg->fp, "mtctr 11\n");
1178 /* Branch to the target address */
1179 fprintf (acfg->fp, "bctr\n");
1181 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1182 *tramp_size = 11 * 4;
1184 *tramp_size = 9 * 4;
1187 #elif defined(TARGET_X86)
1191 /* Similar to the PPC code above */
1193 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1196 /* Load mscorlib got address */
1197 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1199 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1200 /* Branch to the target address */
1201 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1203 #ifdef __native_client_codegen__
1205 /* emit nops to next 32 byte alignment */
1206 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1207 while (code < (buf + a)) x86_nop(code);
1211 emit_bytes (acfg, buf, code - buf);
1213 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1214 g_assert (code - buf == *tramp_size);
1216 g_assert_not_reached ();
1221 * arch_emit_imt_thunk:
1223 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1224 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1225 * key is the IMT key, and ptr holds the address of a memory location holding
1226 * the address to branch to if the IMT arg matches the key. The array is
1227 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1229 * TRAMP_SIZE is set to the size of the emitted trampoline.
1232 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1234 #if defined(TARGET_AMD64)
1236 #if defined(__native_client_codegen__)
1241 guint8 *mov_buf_ptr = mov_buf;
1243 const int kSizeOfMove = 7;
1244 #if defined(__default_codegen__)
1245 code = buf = g_malloc (256);
1246 #elif defined(__native_client_codegen__)
1247 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1248 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1249 /* The RIP relative move below is emitted first */
1254 /* FIXME: Optimize this, i.e. use binary search etc. */
1255 /* Maybe move the body into a separate function (slower, but much smaller) */
1257 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1260 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1262 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1265 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1267 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1270 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1271 amd64_jump_code (code, labels [0]);
1274 mono_amd64_patch (labels [2], code);
1275 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1276 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1280 mono_amd64_patch (labels [1], code);
1281 x86_breakpoint (code);
1283 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1284 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1285 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1286 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1287 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1288 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1290 emit_bytes (acfg, buf, code - buf);
1292 *tramp_size = code - buf + kSizeOfMove;
1293 #if defined(__native_client_codegen__)
1294 /* The tramp will be padded to the next kNaClAlignment bundle. */
1295 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1298 #if defined(__default_codegen__)
1300 #elif defined(__native_client_codegen__)
1304 #elif defined(TARGET_X86)
1306 #ifdef __native_client_codegen__
1311 #if defined(__default_codegen__)
1312 code = buf = g_malloc (256);
1313 #elif defined(__native_client_codegen__)
1314 buf_alloc = g_malloc (256 + kNaClAlignment);
1315 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1318 /* Allocate a temporary stack slot */
1319 x86_push_reg (code, X86_EAX);
1321 x86_push_reg (code, X86_EAX);
1323 /* Load mscorlib got address */
1324 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1326 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1329 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1331 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1334 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1336 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1339 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1340 x86_jump_code (code, labels [0]);
1343 mono_x86_patch (labels [2], code);
1344 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1345 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1346 /* Save the target address to the temporary stack location */
1347 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1349 x86_pop_reg (code, X86_EAX);
1350 /* Jump to the target address */
1355 mono_x86_patch (labels [1], code);
1356 x86_breakpoint (code);
1358 #ifdef __native_client_codegen__
1360 /* emit nops to next 32 byte alignment */
1361 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1362 while (code < (buf + a)) x86_nop(code);
1365 emit_bytes (acfg, buf, code - buf);
1367 *tramp_size = code - buf;
1369 #if defined(__default_codegen__)
1371 #elif defined(__native_client_codegen__)
1375 #elif defined(TARGET_ARM)
1377 guint8 *code, *code2, *labels [16];
1381 /* The IMT method is in v5 */
1383 /* Need at least two free registers, plus a slot for storing the pc */
1384 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1386 /* Load the parameter from the GOT */
1387 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1388 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1391 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1392 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1394 ARM_B_COND (code, ARMCOND_EQ, 0);
1396 /* End-of-loop check */
1397 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1399 ARM_B_COND (code, ARMCOND_EQ, 0);
1402 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1405 arm_patch (labels [4], labels [1]);
1408 arm_patch (labels [2], code);
1409 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1410 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1411 /* Save it to the third stack slot */
1412 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1413 /* Restore the registers and branch */
1414 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1417 arm_patch (labels [3], code);
1422 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1424 emit_bytes (acfg, buf, code - buf);
1425 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1427 *tramp_size = code - buf + 4;
1428 #elif defined(TARGET_POWERPC)
1430 guint8 *code, *labels [16];
1434 /* Load the mscorlib got address */
1435 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1436 /* Load the parameter from the GOT */
1437 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1438 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1440 /* Load and check key */
1442 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1443 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1445 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1447 /* End-of-loop check */
1448 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1450 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1453 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1456 mono_ppc_patch (labels [4], labels [1]);
1459 mono_ppc_patch (labels [2], code);
1460 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1461 /* r11 now contains the value of the vtable slot */
1462 /* this is not a function descriptor on ppc64 */
1463 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1464 ppc_mtctr (code, ppc_r11);
1465 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1468 mono_ppc_patch (labels [3], code);
1472 *tramp_size = code - buf;
1474 emit_bytes (acfg, buf, code - buf);
1476 g_assert_not_reached ();
1481 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1483 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1484 /* Based on code generated by gcc */
1485 img_writer_emit_unset_mode (acfg->w);
1488 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1489 ".section .ctors,\"aw\",@progbits\n"
1493 ".section .opd,\"aw\"\n"
1496 ".long .%s,.TOC.@tocbase32\n"
1499 ".type .%s,@function\n"
1501 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1503 ".section .ctors,\"aw\",@progbits\n"
1507 ".section .opd,\"aw\"\n"
1510 ".long .%1$s,.TOC.@tocbase32\n"
1511 ".size %1$s,.-%1$s\n"
1513 ".type .%1$s,@function\n"
1515 ".%1$s:\n", symbol);
1526 "lis 3, .Lglobals@h\n"
1527 "ori 3, 3, .Lglobals@l\n"
1528 "bl .mono_aot_register_module\n"
1536 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1538 ".size .%s,.-.%s\n", symbol, symbol);
1541 ".size .%1$s,.-.%1$s\n", symbol);
1547 /* END OF ARCH SPECIFIC CODE */
1550 mono_get_field_token (MonoClassField *field)
1552 MonoClass *klass = field->parent;
1555 for (i = 0; i < klass->field.count; ++i) {
1556 if (field == &klass->fields [i])
1557 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1560 g_assert_not_reached ();
1565 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1569 //printf ("ENCODE: %d 0x%x.\n", value, value);
1572 * Same encoding as the one used in the metadata, extended to handle values
1573 * greater than 0x1fffffff.
1575 if ((value >= 0) && (value <= 127))
1577 else if ((value >= 0) && (value <= 16383)) {
1578 p [0] = 0x80 | (value >> 8);
1579 p [1] = value & 0xff;
1581 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1582 p [0] = (value >> 24) | 0xc0;
1583 p [1] = (value >> 16) & 0xff;
1584 p [2] = (value >> 8) & 0xff;
1585 p [3] = value & 0xff;
1590 p [1] = (value >> 24) & 0xff;
1591 p [2] = (value >> 16) & 0xff;
1592 p [3] = (value >> 8) & 0xff;
1593 p [4] = value & 0xff;
1601 stream_init (MonoDynamicStream *sh)
1604 sh->alloc_size = 4096;
1605 sh->data = g_malloc (4096);
1607 /* So offsets are > 0 */
1613 make_room_in_stream (MonoDynamicStream *stream, int size)
1615 if (size <= stream->alloc_size)
1618 while (stream->alloc_size <= size) {
1619 if (stream->alloc_size < 4096)
1620 stream->alloc_size = 4096;
1622 stream->alloc_size *= 2;
1625 stream->data = g_realloc (stream->data, stream->alloc_size);
1629 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1633 make_room_in_stream (stream, stream->index + len);
1634 memcpy (stream->data + stream->index, data, len);
1635 idx = stream->index;
1636 stream->index += len;
1643 * Add data to the binary blob inside the aot image. Returns the offset inside the
1644 * blob where the data was stored.
1647 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1649 if (acfg->blob.alloc_size == 0)
1650 stream_init (&acfg->blob);
1652 return add_stream_data (&acfg->blob, (char*)data, data_len);
1656 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
1661 if (acfg->blob.alloc_size == 0)
1662 stream_init (&acfg->blob);
1664 count = acfg->blob.index % align;
1666 /* we assume the stream data will be aligned */
1668 add_stream_data (&acfg->blob, buf, 4 - count);
1670 return add_stream_data (&acfg->blob, (char*)data, data_len);
1674 * emit_offset_table:
1676 * Emit a table of increasing offsets in a compact form using differential encoding.
1677 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1678 * group size, the more compact the table becomes, but the slower it becomes to compute
1679 * a given entry. Returns the size of the table.
1682 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1684 gint32 current_offset;
1685 int i, buf_size, ngroups, index_entry_size;
1687 guint32 *index_offsets;
1689 ngroups = (noffsets + (group_size - 1)) / group_size;
1691 index_offsets = g_new0 (guint32, ngroups);
1693 buf_size = noffsets * 4;
1694 p = buf = g_malloc0 (buf_size);
1697 for (i = 0; i < noffsets; ++i) {
1698 //printf ("D: %d -> %d\n", i, offsets [i]);
1699 if ((i % group_size) == 0) {
1700 index_offsets [i / group_size] = p - buf;
1701 /* Emit the full value for these entries */
1702 encode_value (offsets [i], p, &p);
1704 /* The offsets are allowed to be non-increasing */
1705 //g_assert (offsets [i] >= current_offset);
1706 encode_value (offsets [i] - current_offset, p, &p);
1708 current_offset = offsets [i];
1711 if (ngroups && index_offsets [ngroups - 1] < 65000)
1712 index_entry_size = 2;
1714 index_entry_size = 4;
1716 /* Emit the header */
1717 emit_int32 (acfg, noffsets);
1718 emit_int32 (acfg, group_size);
1719 emit_int32 (acfg, ngroups);
1720 emit_int32 (acfg, index_entry_size);
1722 /* Emit the index */
1723 for (i = 0; i < ngroups; ++i) {
1724 if (index_entry_size == 2)
1725 emit_int16 (acfg, index_offsets [i]);
1727 emit_int32 (acfg, index_offsets [i]);
1731 emit_bytes (acfg, buf, p - buf);
1733 return (int)(p - buf) + (ngroups * 4);
1737 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1741 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1745 index = g_hash_table_size (cfg->image_hash);
1746 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1747 g_ptr_array_add (cfg->image_table, image);
1753 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1756 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
1758 /* FIXME: Search referenced images as well */
1759 if (!acfg->typespec_classes) {
1760 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
1761 for (i = 0; i < len; ++i) {
1762 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1765 for (i = 0; i < len; ++i) {
1766 if (acfg->typespec_classes [i] == klass)
1771 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1777 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1782 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1783 * standard metadata encoding.
1786 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1790 if (klass->generic_class) {
1792 g_assert (klass->type_token);
1794 /* Find a typespec for a class if possible */
1795 token = find_typespec_for_class (acfg, klass);
1797 encode_value (token, p, &p);
1798 encode_value (get_image_index (acfg, acfg->image), p, &p);
1800 MonoClass *gclass = klass->generic_class->container_class;
1801 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1804 /* Encode it ourselves */
1806 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1807 encode_value (MONO_TYPE_GENERICINST, p, &p);
1808 encode_klass_ref (acfg, gclass, p, &p);
1809 encode_value (inst->type_argc, p, &p);
1810 for (i = 0; i < inst->type_argc; ++i)
1811 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1813 } else if (klass->type_token) {
1814 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1815 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1816 encode_value (get_image_index (acfg, klass->image), p, &p);
1817 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1818 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1819 g_assert (container);
1822 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1823 encode_value (klass->byval_arg.type, p, &p);
1825 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1827 encode_value (container->is_method, p, &p);
1828 if (container->is_method)
1829 encode_method_ref (acfg, container->owner.method, p, &p);
1831 encode_klass_ref (acfg, container->owner.klass, p, &p);
1834 g_assert (klass->rank > 0);
1835 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1836 encode_value (get_image_index (acfg, klass->image), p, &p);
1837 encode_value (klass->rank, p, &p);
1838 encode_klass_ref (acfg, klass->element_class, p, &p);
1844 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1846 guint32 token = mono_get_field_token (field);
1849 encode_klass_ref (cfg, field->parent, p, &p);
1850 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1851 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1856 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1860 MonoGenericInst *inst;
1862 /* Encode the context */
1863 inst = context->class_inst;
1864 encode_value (inst ? 1 : 0, p, &p);
1866 encode_value (inst->type_argc, p, &p);
1867 for (i = 0; i < inst->type_argc; ++i)
1868 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1870 inst = context->method_inst;
1871 encode_value (inst ? 1 : 0, p, &p);
1873 encode_value (inst->type_argc, p, &p);
1874 for (i = 0; i < inst->type_argc; ++i)
1875 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1881 #define MAX_IMAGE_INDEX 250
1884 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1886 guint32 image_index = get_image_index (acfg, method->klass->image);
1887 guint32 token = method->token;
1888 MonoJumpInfoToken *ji;
1893 * The encoding for most methods is as follows:
1894 * - image index encoded as a leb128
1895 * - token index encoded as a leb128
1896 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1897 * types of method encodings.
1900 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1902 /* Mark methods which can't use aot trampolines because they need the further
1903 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1905 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1906 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1907 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1910 * Some wrapper methods are shared using their signature, encode their
1911 * stringified signature instead.
1912 * FIXME: Optimize disk usage
1915 if (method->wrapper_type) {
1916 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1917 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1918 if (strcmp (method->name, "runtime_invoke_dynamic")) {
1919 name = mono_aot_wrapper_name (method);
1920 } else if (mono_marshal_method_from_wrapper (method) != method) {
1921 /* Direct wrapper, encode it normally */
1923 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1926 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1927 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1928 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1930 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1931 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1932 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1934 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1935 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1936 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1942 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1943 strcpy ((char*)p, name);
1944 p += strlen (name) + 1;
1946 } else if (method->wrapper_type) {
1947 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1949 encode_value (method->wrapper_type, p, &p);
1951 switch (method->wrapper_type) {
1952 case MONO_WRAPPER_REMOTING_INVOKE:
1953 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1954 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1957 m = mono_marshal_method_from_wrapper (method);
1959 encode_method_ref (acfg, m, p, &p);
1962 case MONO_WRAPPER_PROXY_ISINST:
1963 case MONO_WRAPPER_LDFLD:
1964 case MONO_WRAPPER_LDFLDA:
1965 case MONO_WRAPPER_STFLD:
1966 case MONO_WRAPPER_ISINST: {
1967 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
1968 encode_klass_ref (acfg, proxy_class, p, &p);
1971 case MONO_WRAPPER_LDFLD_REMOTE:
1972 case MONO_WRAPPER_STFLD_REMOTE:
1974 case MONO_WRAPPER_ALLOC: {
1975 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1977 /* The GC name is saved once in MonoAotFileInfo */
1978 g_assert (info->alloc_type != -1);
1979 encode_value (info->alloc_type, p, &p);
1982 case MONO_WRAPPER_WRITE_BARRIER:
1984 case MONO_WRAPPER_STELEMREF: {
1985 MonoClass *klass = mono_marshal_get_wrapper_info (method);
1987 /* Make sure this is the 'normal' stelemref wrapper, not the virtual one */
1991 case MONO_WRAPPER_UNKNOWN:
1992 if (strcmp (method->name, "FastMonitorEnter") == 0) {
1993 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1994 } else if (strcmp (method->name, "FastMonitorExit") == 0) {
1995 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1996 } else if (strcmp (method->name, "PtrToStructure") == 0) {
1997 encode_value (MONO_AOT_WRAPPER_PTR_TO_STRUCTURE, p, &p);
1998 encode_klass_ref (acfg, method->klass, p, &p);
1999 } else if (strcmp (method->name, "StructureToPtr") == 0) {
2000 encode_value (MONO_AOT_WRAPPER_STRUCTURE_TO_PTR, p, &p);
2001 encode_klass_ref (acfg, method->klass, p, &p);
2003 g_assert_not_reached ();
2006 case MONO_WRAPPER_SYNCHRONIZED:
2007 case MONO_WRAPPER_MANAGED_TO_NATIVE:
2008 case MONO_WRAPPER_RUNTIME_INVOKE: {
2011 m = mono_marshal_method_from_wrapper (method);
2013 g_assert (m != method);
2014 encode_method_ref (acfg, m, p, &p);
2017 case MONO_WRAPPER_MANAGED_TO_MANAGED:
2018 if (!strcmp (method->name, "ElementAddr")) {
2019 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2022 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
2023 encode_value (info->rank, p, &p);
2024 encode_value (info->elem_size, p, &p);
2026 g_assert_not_reached ();
2030 g_assert_not_reached ();
2032 } else if (mono_method_signature (method)->is_inflated) {
2034 * This is a generic method, find the original token which referenced it and
2036 * Obtain the token from information recorded by the JIT.
2038 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2040 image_index = get_image_index (acfg, ji->image);
2041 g_assert (image_index < MAX_IMAGE_INDEX);
2044 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2045 encode_value (image_index, p, &p);
2046 encode_value (token, p, &p);
2048 MonoMethod *declaring;
2049 MonoGenericContext *context = mono_method_get_context (method);
2051 g_assert (method->is_inflated);
2052 declaring = ((MonoMethodInflated*)method)->declaring;
2055 * This might be a non-generic method of a generic instance, which
2056 * doesn't have a token since the reference is generated by the JIT
2057 * like Nullable:Box/Unbox, or by generic sharing.
2060 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2061 /* Encode the klass */
2062 encode_klass_ref (acfg, method->klass, p, &p);
2063 /* Encode the method */
2064 image_index = get_image_index (acfg, method->klass->image);
2065 g_assert (image_index < MAX_IMAGE_INDEX);
2066 g_assert (declaring->token);
2067 token = declaring->token;
2068 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2069 encode_value (image_index, p, &p);
2070 encode_value (token, p, &p);
2071 encode_generic_context (acfg, context, p, &p);
2073 } else if (token == 0) {
2074 /* This might be a method of a constructed type like int[,].Set */
2075 /* Obtain the token from information recorded by the JIT */
2076 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2078 image_index = get_image_index (acfg, ji->image);
2079 g_assert (image_index < MAX_IMAGE_INDEX);
2082 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2083 encode_value (image_index, p, &p);
2084 encode_value (token, p, &p);
2087 g_assert (method->klass->rank);
2089 /* Encode directly */
2090 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2091 encode_klass_ref (acfg, method->klass, p, &p);
2092 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2093 encode_value (0, p, &p);
2094 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2095 encode_value (1, p, &p);
2096 else if (!strcmp (method->name, "Get"))
2097 encode_value (2, p, &p);
2098 else if (!strcmp (method->name, "Address"))
2099 encode_value (3, p, &p);
2100 else if (!strcmp (method->name, "Set"))
2101 encode_value (4, p, &p);
2103 g_assert_not_reached ();
2106 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2107 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2113 compare_patches (gconstpointer a, gconstpointer b)
2117 i = (*(MonoJumpInfo**)a)->ip.i;
2118 j = (*(MonoJumpInfo**)b)->ip.i;
2129 static G_GNUC_UNUSED char*
2130 patch_to_string (MonoJumpInfo *patch_info)
2134 str = g_string_new ("");
2136 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2138 switch (patch_info->type) {
2139 case MONO_PATCH_INFO_VTABLE:
2140 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2145 g_string_append_printf (str, ")");
2146 return g_string_free (str, FALSE);
2152 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2155 static inline gboolean
2156 is_plt_patch (MonoJumpInfo *patch_info)
2158 switch (patch_info->type) {
2159 case MONO_PATCH_INFO_METHOD:
2160 case MONO_PATCH_INFO_INTERNAL_METHOD:
2161 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2162 case MONO_PATCH_INFO_ICALL_ADDR:
2163 case MONO_PATCH_INFO_CLASS_INIT:
2164 case MONO_PATCH_INFO_RGCTX_FETCH:
2165 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2166 case MONO_PATCH_INFO_MONITOR_ENTER:
2167 case MONO_PATCH_INFO_MONITOR_EXIT:
2168 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2178 * Return the symbol identifying the plt entry PLT_OFFSET.
2181 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2185 * The Apple linker reorganizes object files, so it doesn't like branches to local
2186 * labels, since those have no relocations.
2188 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2190 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2197 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2199 static MonoPltEntry*
2200 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2204 if (!is_plt_patch (patch_info))
2207 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2209 // FIXME: This breaks the calculation of final_got_size
2210 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2212 * Allocate a separate PLT slot for each such patch, since some plt
2213 * entries will refer to the method itself, and some will refer to the
2220 MonoJumpInfo *new_ji;
2222 g_assert (!acfg->final_got_size);
2224 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2226 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2227 res->plt_offset = acfg->plt_offset;
2229 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2230 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2232 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2234 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2236 acfg->plt_offset ++;
2245 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2246 * JI could be found if it exists, otherwise allocates a new one.
2249 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2253 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2255 return got_offset - 1;
2257 got_offset = acfg->got_offset;
2258 acfg->got_offset ++;
2260 if (acfg->final_got_size)
2261 g_assert (got_offset < acfg->final_got_size);
2263 acfg->stats.got_slots ++;
2264 acfg->stats.got_slot_types [ji->type] ++;
2266 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2267 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2268 g_ptr_array_add (acfg->got_patches, ji);
2273 /* Add a method to the list of methods which need to be emitted */
2275 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2278 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2279 g_ptr_array_add (acfg->methods, method);
2280 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2281 acfg->nmethods = acfg->methods->len + 1;
2284 if (method->wrapper_type || extra)
2285 g_ptr_array_add (acfg->extra_methods, method);
2289 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2291 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2299 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2303 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2307 index = acfg->method_index;
2308 add_method_with_index (acfg, method, index, extra);
2310 /* FIXME: Fix quadratic behavior */
2311 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
2313 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2315 acfg->method_index ++;
2321 add_method (MonoAotCompile *acfg, MonoMethod *method)
2323 return add_method_full (acfg, method, FALSE, 0);
2327 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2329 add_method_full (acfg, method, TRUE, 0);
2333 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2335 add_method_full (acfg, method, TRUE, depth);
2339 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2341 MonoAotCompile *acfg = user_data;
2342 MonoJitICallInfo *callinfo = value;
2343 MonoMethod *wrapper;
2349 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2350 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2353 add_method (acfg, wrapper);
2357 get_runtime_invoke_sig (MonoMethodSignature *sig)
2359 MonoMethodBuilder *mb;
2362 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2363 m = mono_mb_create_method (mb, sig, 16);
2364 return mono_marshal_get_runtime_invoke (m, FALSE);
2368 can_marshal_struct (MonoClass *klass)
2370 MonoClassField *field;
2371 gboolean can_marshal = TRUE;
2372 gpointer iter = NULL;
2374 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2377 /* Only allow a few field types to avoid asserts in the marshalling code */
2378 while ((field = mono_class_get_fields (klass, &iter))) {
2379 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2382 switch (field->type->type) {
2387 case MONO_TYPE_BOOLEAN:
2390 case MONO_TYPE_CHAR:
2398 case MONO_TYPE_STRING:
2400 case MONO_TYPE_VALUETYPE:
2401 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2402 can_marshal = FALSE;
2405 can_marshal = FALSE;
2411 /* Its hard to compute whenever these can be marshalled or not */
2412 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2419 add_wrappers (MonoAotCompile *acfg)
2421 MonoMethod *method, *m;
2423 MonoMethodSignature *sig, *csig;
2427 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2428 * so there is only one wrapper of a given type, or inlining their contents into their
2433 * FIXME: This depends on the fact that different wrappers have different
2437 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2439 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2440 gboolean skip = FALSE;
2442 method = mono_get_method (acfg->image, token, NULL);
2444 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2445 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2446 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2449 if (method->is_generic || method->klass->generic_container)
2452 /* Skip methods which can not be handled by get_runtime_invoke () */
2453 sig = mono_method_signature (method);
2456 if ((sig->ret->type == MONO_TYPE_PTR) ||
2457 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2460 for (j = 0; j < sig->param_count; j++) {
2461 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2465 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2466 if (!method->klass->contextbound) {
2467 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2468 gboolean has_nullable = FALSE;
2470 for (j = 0; j < sig->param_count; j++) {
2471 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2472 has_nullable = TRUE;
2475 if (info && !has_nullable) {
2476 /* Supported by the dynamic runtime-invoke wrapper */
2484 //printf ("%s\n", mono_method_full_name (method, TRUE));
2485 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2489 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2490 #ifdef MONO_ARCH_HAVE_TLS_GET
2491 MonoMethodDesc *desc;
2492 MonoMethod *orig_method;
2496 /* Runtime invoke wrappers */
2498 /* void runtime-invoke () [.cctor] */
2499 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2500 csig->ret = &mono_defaults.void_class->byval_arg;
2501 add_method (acfg, get_runtime_invoke_sig (csig));
2503 /* void runtime-invoke () [Finalize] */
2504 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2506 csig->ret = &mono_defaults.void_class->byval_arg;
2507 add_method (acfg, get_runtime_invoke_sig (csig));
2509 /* void runtime-invoke (string) [exception ctor] */
2510 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2512 csig->ret = &mono_defaults.void_class->byval_arg;
2513 csig->params [0] = &mono_defaults.string_class->byval_arg;
2514 add_method (acfg, get_runtime_invoke_sig (csig));
2516 /* void runtime-invoke (string, string) [exception ctor] */
2517 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2519 csig->ret = &mono_defaults.void_class->byval_arg;
2520 csig->params [0] = &mono_defaults.string_class->byval_arg;
2521 csig->params [1] = &mono_defaults.string_class->byval_arg;
2522 add_method (acfg, get_runtime_invoke_sig (csig));
2524 /* string runtime-invoke () [Exception.ToString ()] */
2525 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2527 csig->ret = &mono_defaults.string_class->byval_arg;
2528 add_method (acfg, get_runtime_invoke_sig (csig));
2530 /* void runtime-invoke (string, Exception) [exception ctor] */
2531 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2533 csig->ret = &mono_defaults.void_class->byval_arg;
2534 csig->params [0] = &mono_defaults.string_class->byval_arg;
2535 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2536 add_method (acfg, get_runtime_invoke_sig (csig));
2538 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2539 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2541 csig->ret = &(mono_class_from_name (
2542 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2543 csig->params [0] = &mono_defaults.string_class->byval_arg;
2544 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2545 add_method (acfg, get_runtime_invoke_sig (csig));
2547 /* runtime-invoke used by finalizers */
2548 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2550 /* This is used by mono_runtime_capture_context () */
2551 method = mono_get_context_capture_method ();
2553 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2555 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2556 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2559 /* JIT icall wrappers */
2560 /* FIXME: locking */
2561 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2564 add_method (acfg, mono_marshal_get_stelemref ());
2566 #ifdef MONO_ARCH_HAVE_TLS_GET
2567 /* Managed Allocators */
2568 nallocators = mono_gc_get_managed_allocator_types ();
2569 for (i = 0; i < nallocators; ++i) {
2570 m = mono_gc_get_managed_allocator_by_type (i);
2572 add_method (acfg, m);
2575 /* Monitor Enter/Exit */
2576 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2577 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2578 g_assert (orig_method);
2579 mono_method_desc_free (desc);
2580 method = mono_monitor_get_fast_path (orig_method);
2582 add_method (acfg, method);
2584 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2585 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2586 g_assert (orig_method);
2587 mono_method_desc_free (desc);
2588 method = mono_monitor_get_fast_path (orig_method);
2590 add_method (acfg, method);
2593 /* Stelemref wrappers */
2594 /* There is only a constant number of these, iterating over all types should handle them all */
2595 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2598 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2599 klass = mono_class_get (acfg->image, token);
2601 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2606 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2607 * we use the original method instead at runtime.
2608 * Since full-aot doesn't support remoting, this is not a problem.
2611 /* remoting-invoke wrappers */
2612 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2613 MonoMethodSignature *sig;
2615 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2616 method = mono_get_method (acfg->image, token, NULL);
2618 sig = mono_method_signature (method);
2620 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2621 m = mono_marshal_get_remoting_invoke_with_check (method);
2623 add_method (acfg, m);
2628 /* delegate-invoke wrappers */
2629 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2632 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2633 klass = mono_class_get (acfg->image, token);
2635 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2636 method = mono_get_delegate_invoke (klass);
2638 m = mono_marshal_get_delegate_invoke (method, NULL);
2640 add_method (acfg, m);
2642 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2643 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2645 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2646 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2650 /* Synchronized wrappers */
2651 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2652 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2653 method = mono_get_method (acfg->image, token, NULL);
2655 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2656 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2659 /* pinvoke wrappers */
2660 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2662 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2664 method = mono_get_method (acfg->image, token, NULL);
2666 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2667 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2668 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2672 /* native-to-managed wrappers */
2673 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2675 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2676 MonoCustomAttrInfo *cattr;
2679 method = mono_get_method (acfg->image, token, NULL);
2682 * Only generate native-to-managed wrappers for methods which have an
2683 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2684 * name to avoid defining a new assembly to contain it.
2686 cattr = mono_custom_attrs_from_method (method);
2689 for (j = 0; j < cattr->num_attrs; ++j)
2690 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2692 if (j < cattr->num_attrs) {
2693 MonoCustomAttrEntry *e = &cattr->attrs [j];
2694 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2695 const char *p = (const char*)e->data;
2701 g_assert (method->flags & METHOD_ATTRIBUTE_STATIC);
2703 g_assert (sig->param_count == 1);
2704 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2707 * Decode the cattr manually since we can't create objects
2708 * during aot compilation.
2714 /* From load_cattr_value () in reflection.c */
2715 slen = mono_metadata_decode_value (p, &p);
2716 n = g_memdup (p, slen + 1);
2718 t = mono_reflection_type_from_name (n, acfg->image);
2722 klass = mono_class_from_mono_type (t);
2723 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2725 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, 0));
2729 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2730 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2731 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2735 /* StructureToPtr/PtrToStructure wrappers */
2736 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2739 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2740 klass = mono_class_get (acfg->image, token);
2742 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2743 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2744 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2750 has_type_vars (MonoClass *klass)
2752 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2755 return has_type_vars (klass->element_class);
2756 if (klass->generic_class) {
2757 MonoGenericContext *context = &klass->generic_class->context;
2758 if (context->class_inst) {
2761 for (i = 0; i < context->class_inst->type_argc; ++i)
2762 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2770 method_has_type_vars (MonoMethod *method)
2772 if (has_type_vars (method->klass))
2775 if (method->is_inflated) {
2776 MonoGenericContext *context = mono_method_get_context (method);
2777 if (context->method_inst) {
2780 for (i = 0; i < context->method_inst->type_argc; ++i)
2781 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2788 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth);
2791 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force)
2793 /* This might lead to a huge code blowup so only do it if neccesary */
2794 if (!acfg->aot_opts.full_aot && !force)
2797 add_generic_class_with_depth (acfg, klass, 0);
2801 * add_generic_class:
2803 * Add all methods of a generic class.
2806 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
2811 mono_class_init (klass);
2813 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2816 if (has_type_vars (klass))
2819 if (!klass->generic_class && !klass->rank)
2823 while ((method = mono_class_get_methods (klass, &iter))) {
2824 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2828 if (method->is_generic)
2833 * FIXME: Instances which are referenced by these methods are not added,
2834 * for example Array.Resize<int> for List<int>.Add ().
2836 add_extra_method_with_depth (acfg, method, depth);
2839 if (klass->delegate) {
2840 method = mono_get_delegate_invoke (klass);
2842 method = mono_marshal_get_delegate_invoke (method, NULL);
2844 add_method (acfg, method);
2848 * For ICollection<T>, add instances of the helper methods
2849 * in Array, since a T[] could be cast to ICollection<T>.
2851 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2852 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2853 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2854 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2858 if (!strcmp (klass->name, "IEnumerator`1"))
2859 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2861 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2863 /* Add the T[]/InternalEnumerator class */
2864 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2868 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2869 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2873 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2874 add_generic_class (acfg, nclass, FALSE);
2878 while ((method = mono_class_get_methods (array_class, &iter))) {
2879 if (strstr (method->name, name_prefix)) {
2880 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2881 add_extra_method_with_depth (acfg, m, depth);
2885 g_free (name_prefix);
2888 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2889 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2890 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2891 MonoClass *icomparable, *gcomparer;
2892 MonoGenericContext ctx;
2893 MonoType *args [16];
2895 memset (&ctx, 0, sizeof (ctx));
2897 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2898 g_assert (icomparable);
2899 args [0] = &tclass->byval_arg;
2900 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2902 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2903 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2904 g_assert (gcomparer);
2905 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
2909 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
2910 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
2911 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2912 MonoClass *iface, *gcomparer;
2913 MonoGenericContext ctx;
2914 MonoType *args [16];
2916 memset (&ctx, 0, sizeof (ctx));
2918 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
2920 args [0] = &tclass->byval_arg;
2921 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2923 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
2924 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
2925 g_assert (gcomparer);
2926 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
2932 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
2935 MonoGenericContext ctx;
2936 MonoType *args [16];
2938 memset (&ctx, 0, sizeof (ctx));
2940 for (i = 0; i < ninsts; ++i) {
2941 args [0] = insts [i];
2942 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2943 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force);
2948 * add_generic_instances:
2950 * Add instances referenced by the METHODSPEC/TYPESPEC table.
2953 add_generic_instances (MonoAotCompile *acfg)
2958 MonoMethodHeader *header;
2959 MonoMethodSignature *sig;
2960 MonoGenericContext *context;
2962 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2963 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2964 method = mono_get_method (acfg->image, token, NULL);
2969 if (method->klass->image != acfg->image)
2972 context = mono_method_get_context (method);
2974 if (context && ((context->class_inst && context->class_inst->is_open)))
2978 * For open methods, create an instantiation which can be passed to the JIT.
2979 * FIXME: Handle class_inst as well.
2981 if (context && context->method_inst && context->method_inst->is_open) {
2982 MonoGenericContext shared_context;
2983 MonoGenericInst *inst;
2984 MonoType **type_argv;
2986 MonoMethod *declaring_method;
2987 gboolean supported = TRUE;
2989 /* Check that the context doesn't contain open constructed types */
2990 if (context->class_inst) {
2991 inst = context->class_inst;
2992 for (i = 0; i < inst->type_argc; ++i) {
2993 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
2995 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2999 if (context->method_inst) {
3000 inst = context->method_inst;
3001 for (i = 0; i < inst->type_argc; ++i) {
3002 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
3004 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3012 memset (&shared_context, 0, sizeof (MonoGenericContext));
3014 inst = context->class_inst;
3016 type_argv = g_new0 (MonoType*, inst->type_argc);
3017 for (i = 0; i < inst->type_argc; ++i) {
3018 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
3019 type_argv [i] = &mono_defaults.object_class->byval_arg;
3021 type_argv [i] = inst->type_argv [i];
3024 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3028 inst = context->method_inst;
3030 type_argv = g_new0 (MonoType*, inst->type_argc);
3031 for (i = 0; i < inst->type_argc; ++i) {
3032 if (MONO_TYPE_IS_REFERENCE (inst->type_argv [i]) || inst->type_argv [i]->type == MONO_TYPE_VAR || inst->type_argv [i]->type == MONO_TYPE_MVAR)
3033 type_argv [i] = &mono_defaults.object_class->byval_arg;
3035 type_argv [i] = inst->type_argv [i];
3038 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3042 if (method->is_generic || method->klass->generic_container)
3043 declaring_method = method;
3045 declaring_method = mono_method_get_declaring_generic_method (method);
3047 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3051 * If the method is fully sharable, it was already added in place of its
3052 * generic definition.
3054 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3058 * FIXME: Partially shared methods are not shared here, so we end up with
3059 * many identical methods.
3061 add_extra_method (acfg, method);
3064 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3067 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3069 klass = mono_class_get (acfg->image, token);
3070 if (!klass || klass->rank)
3073 add_generic_class (acfg, klass, FALSE);
3076 /* Add types of args/locals */
3077 for (i = 0; i < acfg->methods->len; ++i) {
3080 method = g_ptr_array_index (acfg->methods, i);
3082 sig = mono_method_signature (method);
3085 for (j = 0; j < sig->param_count; ++j)
3086 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3087 add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]), FALSE);
3090 header = mono_method_get_header (method);
3093 for (j = 0; j < header->num_locals; ++j)
3094 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3095 add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]), FALSE);
3099 if (acfg->image == mono_defaults.corlib) {
3101 MonoType *insts [256];
3104 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3105 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3106 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3107 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3108 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3109 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3110 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3111 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3112 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3113 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3114 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3115 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3117 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3118 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3120 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3121 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3123 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3125 /* Add instances of the array generic interfaces for primitive types */
3126 /* This will add instances of the InternalArray_ helper methods in Array too */
3127 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3129 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3130 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3132 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3133 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3135 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3138 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3139 * used for all instances of GetGenericValueImpl by the AOT runtime.
3142 MonoGenericContext ctx;
3143 MonoType *args [16];
3144 MonoMethod *get_method;
3145 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3147 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3150 memset (&ctx, 0, sizeof (ctx));
3151 args [0] = &mono_defaults.object_class->byval_arg;
3152 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3153 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3160 * is_direct_callable:
3162 * Return whenever the method identified by JI is directly callable without
3163 * going through the PLT.
3166 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3168 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3169 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3171 gboolean direct_callable = TRUE;
3173 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3174 direct_callable = FALSE;
3175 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3176 // FIXME: Maybe call the wrapper directly ?
3177 direct_callable = FALSE;
3179 if (direct_callable)
3188 * emit_and_reloc_code:
3190 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
3191 * is true, calls are made through the GOT too. This is used for emitting trampolines
3192 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3193 * since trampolines are needed to make PTL work.
3196 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3198 int i, pindex, start_index, method_index;
3200 MonoJumpInfo *patch_info;
3201 MonoMethodHeader *header;
3202 gboolean skip, direct_call;
3204 char direct_call_target [1024];
3207 header = mono_method_get_header (method);
3209 method_index = get_method_index (acfg, method);
3212 /* Collect and sort relocations */
3213 patches = g_ptr_array_new ();
3214 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3215 g_ptr_array_add (patches, patch_info);
3216 g_ptr_array_sort (patches, compare_patches);
3219 for (i = 0; i < code_len; i++) {
3221 for (pindex = start_index; pindex < patches->len; ++pindex) {
3222 patch_info = g_ptr_array_index (patches, pindex);
3223 if (patch_info->ip.i >= i)
3227 #ifdef MONO_ARCH_AOT_SUPPORTED
3229 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3230 start_index = pindex;
3232 switch (patch_info->type) {
3233 case MONO_PATCH_INFO_NONE:
3235 case MONO_PATCH_INFO_GOT_OFFSET: {
3238 arch_emit_got_offset (acfg, code + i, &code_size);
3241 patch_info->type = MONO_PATCH_INFO_NONE;
3246 * If this patch is a call, try emitting a direct call instead of
3247 * through a PLT entry. This is possible if the called method is in
3248 * the same assembly and requires no initialization.
3250 direct_call = FALSE;
3251 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3252 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3253 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3254 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3256 g_assert (strlen (callee_cfg->asm_symbol) < 1000);
3257 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3258 patch_info->type = MONO_PATCH_INFO_NONE;
3259 acfg->stats.direct_calls ++;
3262 acfg->stats.all_calls ++;
3265 if (!got_only && !direct_call) {
3266 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3268 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3270 sprintf (direct_call_target, "%s", plt_entry->symbol);
3272 /* Nullify the patch */
3273 patch_info->type = MONO_PATCH_INFO_NONE;
3274 plt_entry->jit_used = TRUE;
3281 arch_emit_direct_call (acfg, direct_call_target, &call_size);
3286 got_slot = get_got_offset (acfg, patch_info);
3288 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3295 #endif /* MONO_ARCH_AOT_SUPPORTED */
3298 /* Find next patch */
3300 for (pindex = start_index; pindex < patches->len; ++pindex) {
3301 patch_info = g_ptr_array_index (patches, pindex);
3302 if (patch_info->ip.i >= i)
3306 /* Try to emit multiple bytes at once */
3307 if (pindex < patches->len && patch_info->ip.i > i) {
3308 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3309 i = patch_info->ip.i - 1;
3311 emit_bytes (acfg, code + i, 1);
3320 * Modify SYMBOL so it only includes characters permissible in symbols.
3323 sanitize_symbol (char *symbol)
3325 int i, len = strlen (symbol);
3327 for (i = 0; i < len; ++i)
3328 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3333 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3335 char *name1, *name2, *cached;
3336 int i, j, len, count;
3338 name1 = mono_method_full_name (method, TRUE);
3339 len = strlen (name1);
3340 name2 = malloc (strlen (prefix) + len + 16);
3341 memcpy (name2, prefix, strlen (prefix));
3342 j = strlen (prefix);
3343 for (i = 0; i < len; ++i) {
3344 if (isalnum (name1 [i])) {
3345 name2 [j ++] = name1 [i];
3346 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3348 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3351 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3360 while (g_hash_table_lookup (cache, name2)) {
3361 sprintf (name2 + j, "_%d", count);
3365 cached = g_strdup (name2);
3366 g_hash_table_insert (cache, cached, cached);
3372 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3377 char *debug_sym = NULL;
3379 int func_alignment = AOT_FUNC_ALIGNMENT;
3380 MonoMethodHeader *header;
3382 method = cfg->orig_method;
3383 code = cfg->native_code;
3384 header = cfg->header;
3386 method_index = get_method_index (acfg, method);
3388 /* Make the labels local */
3389 sprintf (symbol, "%s", cfg->asm_symbol);
3391 emit_section_change (acfg, ".text", 0);
3392 emit_alignment (acfg, func_alignment);
3393 emit_label (acfg, symbol);
3395 if (acfg->aot_opts.write_symbols) {
3397 * Write a C style symbol for every method, this has two uses:
3398 * - it works on platforms where the dwarf debugging info is not
3400 * - it allows the setting of breakpoints of aot-ed methods.
3402 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3404 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3405 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3406 emit_label (acfg, debug_sym);
3409 if (cfg->verbose_level > 0)
3410 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3412 acfg->stats.code_size += cfg->code_len;
3414 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3416 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3420 if (acfg->aot_opts.write_symbols) {
3421 emit_symbol_size (acfg, debug_sym, ".");
3425 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3426 emit_label (acfg, symbol);
3432 * Encode PATCH_INFO into its disk representation.
3435 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3439 switch (patch_info->type) {
3440 case MONO_PATCH_INFO_NONE:
3442 case MONO_PATCH_INFO_IMAGE:
3443 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3445 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3446 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3448 case MONO_PATCH_INFO_METHOD_REL:
3449 encode_value ((gint)patch_info->data.offset, p, &p);
3451 case MONO_PATCH_INFO_SWITCH: {
3452 gpointer *table = (gpointer *)patch_info->data.table->table;
3455 encode_value (patch_info->data.table->table_size, p, &p);
3456 for (k = 0; k < patch_info->data.table->table_size; k++)
3457 encode_value ((int)(gssize)table [k], p, &p);
3460 case MONO_PATCH_INFO_METHODCONST:
3461 case MONO_PATCH_INFO_METHOD:
3462 case MONO_PATCH_INFO_METHOD_JUMP:
3463 case MONO_PATCH_INFO_ICALL_ADDR:
3464 case MONO_PATCH_INFO_METHOD_RGCTX:
3465 encode_method_ref (acfg, patch_info->data.method, p, &p);
3467 case MONO_PATCH_INFO_INTERNAL_METHOD:
3468 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3469 guint32 len = strlen (patch_info->data.name);
3471 encode_value (len, p, &p);
3473 memcpy (p, patch_info->data.name, len);
3478 case MONO_PATCH_INFO_LDSTR: {
3479 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3480 guint32 token = patch_info->data.token->token;
3481 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3482 encode_value (image_index, p, &p);
3483 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3486 case MONO_PATCH_INFO_RVA:
3487 case MONO_PATCH_INFO_DECLSEC:
3488 case MONO_PATCH_INFO_LDTOKEN:
3489 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3490 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3491 encode_value (patch_info->data.token->token, p, &p);
3492 encode_value (patch_info->data.token->has_context, p, &p);
3493 if (patch_info->data.token->has_context)
3494 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3496 case MONO_PATCH_INFO_EXC_NAME: {
3497 MonoClass *ex_class;
3500 mono_class_from_name (mono_defaults.exception_class->image,
3501 "System", patch_info->data.target);
3502 g_assert (ex_class);
3503 encode_klass_ref (acfg, ex_class, p, &p);
3506 case MONO_PATCH_INFO_R4:
3507 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3509 case MONO_PATCH_INFO_R8:
3510 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3511 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3513 case MONO_PATCH_INFO_VTABLE:
3514 case MONO_PATCH_INFO_CLASS:
3515 case MONO_PATCH_INFO_IID:
3516 case MONO_PATCH_INFO_ADJUSTED_IID:
3517 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3519 case MONO_PATCH_INFO_CLASS_INIT:
3520 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3521 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3523 case MONO_PATCH_INFO_FIELD:
3524 case MONO_PATCH_INFO_SFLDA:
3525 encode_field_info (acfg, patch_info->data.field, p, &p);
3527 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3529 case MONO_PATCH_INFO_RGCTX_FETCH: {
3530 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3532 encode_method_ref (acfg, entry->method, p, &p);
3533 encode_value (entry->in_mrgctx, p, &p);
3534 encode_value (entry->info_type, p, &p);
3535 encode_value (entry->data->type, p, &p);
3536 encode_patch (acfg, entry->data, p, &p);
3539 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3540 case MONO_PATCH_INFO_MONITOR_ENTER:
3541 case MONO_PATCH_INFO_MONITOR_EXIT:
3542 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3544 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3545 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3546 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3549 g_warning ("unable to handle jump info %d", patch_info->type);
3550 g_assert_not_reached ();
3557 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3560 guint32 pindex, offset;
3561 MonoJumpInfo *patch_info;
3563 encode_value (n_patches, p, &p);
3565 for (pindex = 0; pindex < patches->len; ++pindex) {
3566 patch_info = g_ptr_array_index (patches, pindex);
3568 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3572 offset = get_got_offset (acfg, patch_info);
3573 encode_value (offset, p, &p);
3580 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3584 int pindex, buf_size, n_patches;
3587 MonoJumpInfo *patch_info;
3588 MonoMethodHeader *header;
3589 guint32 method_index;
3591 guint32 first_got_offset;
3593 method = cfg->orig_method;
3594 code = cfg->native_code;
3595 header = mono_method_get_header (method);
3597 method_index = get_method_index (acfg, method);
3599 /* Sort relocations */
3600 patches = g_ptr_array_new ();
3601 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3602 g_ptr_array_add (patches, patch_info);
3603 g_ptr_array_sort (patches, compare_patches);
3605 first_got_offset = acfg->cfgs [method_index]->got_offset;
3607 /**********************/
3608 /* Encode method info */
3609 /**********************/
3611 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3612 p = buf = g_malloc (buf_size);
3614 if (mono_class_get_cctor (method->klass))
3615 encode_klass_ref (acfg, method->klass, p, &p);
3617 /* Not needed when loading the method */
3618 encode_value (0, p, &p);
3621 if (cfg->opt & MONO_OPT_SHARED) {
3622 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3623 for (l = cfg->ldstr_list; l; l = l->next) {
3624 encode_value ((long)l->data, p, &p);
3628 /* Used only in shared mode */
3629 g_assert (!cfg->ldstr_list);
3632 for (pindex = 0; pindex < patches->len; ++pindex) {
3633 patch_info = g_ptr_array_index (patches, pindex);
3635 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3636 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3637 patch_info->type = MONO_PATCH_INFO_NONE;
3642 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3643 /* Stored in a GOT slot initialized at module load time */
3644 patch_info->type = MONO_PATCH_INFO_NONE;
3648 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
3649 /* Stored in a GOT slot initialized at module load time */
3650 patch_info->type = MONO_PATCH_INFO_NONE;
3654 if (is_plt_patch (patch_info)) {
3655 /* Calls are made through the PLT */
3656 patch_info->type = MONO_PATCH_INFO_NONE;
3664 g_assert (cfg->has_got_slots);
3666 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3668 acfg->stats.info_size += p - buf;
3670 g_assert (p - buf < buf_size);
3672 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3677 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3679 guint32 cache_index;
3682 /* Reuse the unwind module to canonize and store unwind info entries */
3683 cache_index = mono_cache_unwind_info (encoded, encoded_len);
3685 /* Use +/- 1 to distinguish 0s from missing entries */
3686 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3694 * It would be easier to use assembler symbols, but the caller needs an
3697 offset = acfg->unwind_info_offset;
3698 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3699 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3702 encode_value (encoded_len, p, &p);
3704 acfg->unwind_info_offset += encoded_len + (p - buf);
3710 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3713 int i, k, buf_size, method_index;
3714 guint32 debug_info_size;
3716 MonoMethodHeader *header;
3717 guint8 *p, *buf, *debug_info;
3718 MonoJitInfo *jinfo = cfg->jit_info;
3720 gboolean use_unwind_ops = FALSE;
3721 MonoSeqPointInfo *seq_points;
3723 method = cfg->orig_method;
3724 code = cfg->native_code;
3725 header = cfg->header;
3727 method_index = get_method_index (acfg, method);
3729 if (!acfg->aot_opts.nodebug) {
3730 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3733 debug_info_size = 0;
3736 seq_points = cfg->seq_point_info;
3738 buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
3739 p = buf = g_malloc (buf_size);
3741 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3742 use_unwind_ops = cfg->unwind_ops != NULL;
3745 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points ? 8 : 0) | (cfg->compile_llvm ? 16 : 0) | (jinfo->has_try_block_holes ? 32 : 0) | (cfg->gc_map ? 64 : 0);
3747 encode_value (flags, p, &p);
3749 if (use_unwind_ops) {
3750 guint32 encoded_len;
3754 * This is a duplicate of the data in the .debug_frame section, but that
3755 * section cannot be accessed using the dl interface.
3757 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3758 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3761 encode_value (jinfo->used_regs, p, &p);
3764 /*Encode the number of holes before the number of clauses to make decoding easier*/
3765 if (jinfo->has_try_block_holes) {
3766 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3767 encode_value (table->num_holes, p, &p);
3770 /* Exception table */
3771 if (cfg->compile_llvm) {
3773 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
3774 * since the information is only available to llc. Instead, we let llc save the data
3775 * into the LSDA, and read it from there at runtime.
3777 /* The assembly might be CIL stripped so emit the data ourselves */
3778 if (header->num_clauses)
3779 encode_value (header->num_clauses, p, &p);
3781 for (k = 0; k < header->num_clauses; ++k) {
3782 MonoExceptionClause *clause;
3784 clause = &header->clauses [k];
3786 encode_value (clause->flags, p, &p);
3787 if (clause->data.catch_class) {
3788 encode_value (1, p, &p);
3789 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3791 encode_value (0, p, &p);
3794 /* Emit a list of nesting clauses */
3795 for (i = 0; i < header->num_clauses; ++i) {
3797 MonoExceptionClause *clause1 = &header->clauses [cindex1];
3799 MonoExceptionClause *clause2 = &header->clauses [cindex2];
3801 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
3802 encode_value (i, p, &p);
3804 encode_value (-1, p, &p);
3807 if (jinfo->num_clauses)
3808 encode_value (jinfo->num_clauses, p, &p);
3810 for (k = 0; k < jinfo->num_clauses; ++k) {
3811 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3813 encode_value (ei->flags, p, &p);
3814 encode_value (ei->exvar_offset, p, &p);
3816 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3817 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3819 if (ei->data.catch_class) {
3820 encode_value (1, p, &p);
3821 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3823 encode_value (0, p, &p);
3827 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3828 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3829 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3833 if (jinfo->has_generic_jit_info) {
3834 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3836 if (!cfg->compile_llvm) {
3837 encode_value (gi->has_this ? 1 : 0, p, &p);
3838 encode_value (gi->this_reg, p, &p);
3839 encode_value (gi->this_offset, p, &p);
3843 * Need to encode jinfo->method too, since it is not equal to 'method'
3844 * when using generic sharing.
3846 encode_method_ref (acfg, jinfo->method, p, &p);
3849 if (jinfo->has_try_block_holes) {
3850 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3851 for (i = 0; i < table->num_holes; ++i) {
3852 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3853 encode_value (hole->clause, p, &p);
3854 encode_value (hole->length, p, &p);
3855 encode_value (hole->offset, p, &p);
3860 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3862 encode_value (seq_points->len, p, &p);
3863 last_il_offset = last_native_offset = 0;
3864 for (i = 0; i < seq_points->len; ++i) {
3865 SeqPoint *sp = &seq_points->seq_points [i];
3866 il_offset = sp->il_offset;
3867 native_offset = sp->native_offset;
3868 encode_value (il_offset - last_il_offset, p, &p);
3869 encode_value (native_offset - last_native_offset, p, &p);
3870 last_il_offset = il_offset;
3871 last_native_offset = native_offset;
3873 encode_value (sp->next_len, p, &p);
3874 for (j = 0; j < sp->next_len; ++j)
3875 encode_value (sp->next [j], p, &p);
3879 g_assert (debug_info_size < buf_size);
3881 encode_value (debug_info_size, p, &p);
3882 if (debug_info_size) {
3883 memcpy (p, debug_info, debug_info_size);
3884 p += debug_info_size;
3885 g_free (debug_info);
3890 encode_value (cfg->gc_map_size, p, &p);
3891 /* The GC map requires 4 bytes of alignment */
3892 while ((gsize)p % 4)
3894 memcpy (p, cfg->gc_map, cfg->gc_map_size);
3895 p += cfg->gc_map_size;
3898 acfg->stats.ex_info_size += p - buf;
3900 g_assert (p - buf < buf_size);
3903 /* The GC Map requires 4 byte alignment */
3904 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
3909 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3911 MonoClass *klass = mono_class_get (acfg->image, token);
3913 int i, buf_size, res;
3914 gboolean no_special_static, cant_encode;
3915 gpointer iter = NULL;
3920 p = buf = g_malloc (buf_size);
3922 /* Mark as unusable */
3923 encode_value (-1, p, &p);
3925 res = add_to_blob (acfg, buf, p - buf);
3931 buf_size = 10240 + (klass->vtable_size * 16);
3932 p = buf = g_malloc (buf_size);
3936 mono_class_init (klass);
3938 mono_class_get_nested_types (klass, &iter);
3939 g_assert (klass->nested_classes_inited);
3941 mono_class_setup_vtable (klass);
3944 * Emit all the information which is required for creating vtables so
3945 * the runtime does not need to create the MonoMethod structures which
3946 * take up a lot of space.
3949 no_special_static = !mono_class_has_special_static_fields (klass);
3951 /* Check whenever we have enough info to encode the vtable */
3952 cant_encode = FALSE;
3953 for (i = 0; i < klass->vtable_size; ++i) {
3954 MonoMethod *cm = klass->vtable [i];
3956 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3960 if (klass->generic_container || cant_encode) {
3961 encode_value (-1, p, &p);
3963 encode_value (klass->vtable_size, p, &p);
3964 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);
3965 if (klass->has_cctor)
3966 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3967 if (klass->has_finalize)
3968 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3970 encode_value (klass->instance_size, p, &p);
3971 encode_value (mono_class_data_size (klass), p, &p);
3972 encode_value (klass->packing_size, p, &p);
3973 encode_value (klass->min_align, p, &p);
3975 for (i = 0; i < klass->vtable_size; ++i) {
3976 MonoMethod *cm = klass->vtable [i];
3979 encode_method_ref (acfg, cm, p, &p);
3981 encode_value (0, p, &p);
3985 acfg->stats.class_info_size += p - buf;
3987 g_assert (p - buf < buf_size);
3988 res = add_to_blob (acfg, buf, p - buf);
3995 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
4000 case MONO_PATCH_INFO_METHOD:
4001 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
4003 case MONO_PATCH_INFO_INTERNAL_METHOD:
4004 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4006 case MONO_PATCH_INFO_CLASS_INIT:
4007 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4008 sanitize_symbol (debug_sym);
4010 case MONO_PATCH_INFO_RGCTX_FETCH:
4011 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4013 case MONO_PATCH_INFO_ICALL_ADDR: {
4014 char *s = get_debug_sym (ji->data.method, "", cache);
4016 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4020 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4021 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4023 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4024 debug_sym = g_strdup_printf ("plt__generic_class_init");
4034 * Calls made from AOTed code are routed through a table of jumps similar to the
4035 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
4036 * control to the AOT runtime through a trampoline.
4039 emit_plt (MonoAotCompile *acfg)
4045 cache = g_hash_table_new (g_str_hash, g_str_equal);
4048 sprintf (symbol, "plt");
4050 emit_section_change (acfg, ".text", 0);
4051 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
4052 emit_label (acfg, symbol);
4053 emit_label (acfg, acfg->plt_symbol);
4055 for (i = 0; i < acfg->plt_offset; ++i) {
4056 char *debug_sym = NULL;
4057 MonoPltEntry *plt_entry = NULL;
4062 * The first plt entry is unused.
4066 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4071 * If the target is directly callable, alias the plt symbol to point to
4073 * FIXME: Use this to simplify emit_and_reloc_code ().
4074 * FIXME: Avoid the got slot.
4075 * FIXME: Add support to the binary writer.
4077 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
4078 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
4080 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
4081 /* LLVM calls the PLT entries using bl, so emit a stub */
4082 emit_label (acfg, plt_entry->llvm_symbol);
4083 fprintf (acfg->fp, ".thumb_func\n");
4084 fprintf (acfg->fp, "bx pc\n");
4085 fprintf (acfg->fp, "nop\n");
4086 fprintf (acfg->fp, ".arm\n");
4087 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
4089 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
4095 if (acfg->aot_opts.write_symbols)
4096 plt_entry->debug_sym = get_plt_entry_debug_sym (acfg, ji, cache);
4097 debug_sym = plt_entry->debug_sym;
4099 if (acfg->thumb_mixed && !plt_entry->jit_used)
4100 /* Emit only a thumb version */
4103 if (!acfg->thumb_mixed)
4104 emit_label (acfg, plt_entry->llvm_symbol);
4107 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4108 emit_label (acfg, debug_sym);
4111 emit_label (acfg, plt_entry->symbol);
4113 arch_emit_plt_entry (acfg, i);
4116 emit_symbol_size (acfg, debug_sym, ".");
4119 if (acfg->thumb_mixed) {
4121 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
4124 for (i = 0; i < acfg->plt_offset; ++i) {
4125 char *debug_sym = NULL;
4126 MonoPltEntry *plt_entry = NULL;
4132 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4135 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
4138 /* Skip plt entries not actually called by LLVM code */
4139 if (!plt_entry->llvm_used)
4142 if (acfg->aot_opts.write_symbols) {
4143 if (plt_entry->debug_sym)
4144 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
4148 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4149 emit_label (acfg, debug_sym);
4152 emit_label (acfg, plt_entry->llvm_symbol);
4154 arch_emit_llvm_plt_entry (acfg, i);
4157 emit_symbol_size (acfg, debug_sym, ".");
4163 emit_symbol_size (acfg, acfg->plt_symbol, ".");
4165 sprintf (symbol, "plt_end");
4166 emit_label (acfg, symbol);
4168 g_hash_table_destroy (cache);
4171 static G_GNUC_UNUSED void
4172 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4174 char start_symbol [256];
4176 guint32 buf_size, info_offset;
4177 MonoJumpInfo *patch_info;
4188 code_size = info->code_size;
4190 unwind_ops = info->unwind_ops;
4192 #ifdef __native_client_codegen__
4193 mono_nacl_fix_patches (code, ji);
4198 sprintf (start_symbol, "%s", name);
4200 emit_section_change (acfg, ".text", 0);
4201 emit_global (acfg, start_symbol, TRUE);
4202 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4203 emit_label (acfg, start_symbol);
4205 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4206 emit_label (acfg, symbol);
4209 * The code should access everything through the GOT, so we pass
4212 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4214 emit_symbol_size (acfg, start_symbol, ".");
4218 /* Sort relocations */
4219 patches = g_ptr_array_new ();
4220 for (patch_info = ji; patch_info; patch_info = patch_info->next)
4221 if (patch_info->type != MONO_PATCH_INFO_NONE)
4222 g_ptr_array_add (patches, patch_info);
4223 g_ptr_array_sort (patches, compare_patches);
4225 buf_size = patches->len * 128 + 128;
4226 buf = g_malloc (buf_size);
4229 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4230 g_assert (p - buf < buf_size);
4232 sprintf (symbol, "%s_p", name);
4234 info_offset = add_to_blob (acfg, buf, p - buf);
4236 emit_section_change (acfg, RODATA_SECT, 0);
4237 emit_global (acfg, symbol, FALSE);
4238 emit_label (acfg, symbol);
4240 emit_int32 (acfg, info_offset);
4242 /* Emit debug info */
4246 sprintf (symbol, "%s", name);
4247 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4250 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4255 emit_trampolines (MonoAotCompile *acfg)
4258 int i, tramp_got_offset;
4259 MonoAotTrampoline ntype;
4260 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4265 if (!acfg->aot_opts.full_aot)
4268 g_assert (acfg->image->assembly);
4270 /* Currently, we emit most trampolines into the mscorlib AOT image. */
4271 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4272 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4273 MonoTrampInfo *info;
4276 * Emit the generic trampolines.
4278 * We could save some code by treating the generic trampolines as a wrapper
4279 * method, but that approach has its own complexities, so we choose the simpler
4282 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4283 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4284 emit_trampoline (acfg, acfg->got_offset, info);
4287 mono_arch_get_nullified_class_init_trampoline (&info);
4288 emit_trampoline (acfg, acfg->got_offset, info);
4289 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4290 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4291 emit_trampoline (acfg, acfg->got_offset, info);
4292 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4293 emit_trampoline (acfg, acfg->got_offset, info);
4296 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4297 emit_trampoline (acfg, acfg->got_offset, info);
4299 /* Emit the exception related code pieces */
4300 code = mono_arch_get_restore_context (&info, TRUE);
4301 emit_trampoline (acfg, acfg->got_offset, info);
4302 code = mono_arch_get_call_filter (&info, TRUE);
4303 emit_trampoline (acfg, acfg->got_offset, info);
4304 code = mono_arch_get_throw_exception (&info, TRUE);
4305 emit_trampoline (acfg, acfg->got_offset, info);
4306 code = mono_arch_get_rethrow_exception (&info, TRUE);
4307 emit_trampoline (acfg, acfg->got_offset, info);
4308 code = mono_arch_get_throw_corlib_exception (&info, TRUE);
4309 emit_trampoline (acfg, acfg->got_offset, info);
4311 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4313 GSList *l = mono_arch_get_trampolines (TRUE);
4316 MonoTrampInfo *info = l->data;
4318 emit_trampoline (acfg, acfg->got_offset, info);
4324 for (i = 0; i < 128; ++i) {
4327 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4328 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4329 emit_trampoline (acfg, acfg->got_offset, info);
4331 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4332 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4333 emit_trampoline (acfg, acfg->got_offset, info);
4339 /* delegate_invoke_impl trampolines */
4340 l = mono_arch_get_delegate_invoke_impls ();
4342 MonoTrampInfo *info = l->data;
4344 emit_trampoline (acfg, acfg->got_offset, info);
4349 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4351 /* Emit trampolines which are numerous */
4354 * These include the following:
4355 * - specific trampolines
4356 * - static rgctx invoke trampolines
4358 * These trampolines have the same code, they are parameterized by GOT
4360 * They are defined in this file, in the arch_... routines instead of
4361 * in tramp-<ARCH>.c, since it is easier to do it this way.
4365 * When running in aot-only mode, we can't create specific trampolines at
4366 * runtime, so we create a few, and save them in the AOT file.
4367 * Normal trampolines embed their argument as a literal inside the
4368 * trampoline code, we can't do that here, so instead we embed an offset
4369 * which needs to be added to the trampoline address to get the address of
4370 * the GOT slot which contains the argument value.
4371 * The generated trampolines jump to the generic trampolines using another
4372 * GOT slot, which will be setup by the AOT loader to point to the
4373 * generic trampoline code of the given type.
4377 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4381 emit_section_change (acfg, ".text", 0);
4383 tramp_got_offset = acfg->got_offset;
4385 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4387 case MONO_AOT_TRAMP_SPECIFIC:
4388 sprintf (symbol, "specific_trampolines");
4390 case MONO_AOT_TRAMP_STATIC_RGCTX:
4391 sprintf (symbol, "static_rgctx_trampolines");
4393 case MONO_AOT_TRAMP_IMT_THUNK:
4394 sprintf (symbol, "imt_thunks");
4397 g_assert_not_reached ();
4400 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4401 emit_label (acfg, symbol);
4403 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4405 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4409 case MONO_AOT_TRAMP_SPECIFIC:
4410 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4411 tramp_got_offset += 2;
4413 case MONO_AOT_TRAMP_STATIC_RGCTX:
4414 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
4415 tramp_got_offset += 2;
4417 case MONO_AOT_TRAMP_IMT_THUNK:
4418 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4419 tramp_got_offset += 1;
4422 g_assert_not_reached ();
4424 #ifdef __native_client_codegen__
4425 /* align to avoid 32-byte boundary crossings */
4426 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4429 if (!acfg->trampoline_size [ntype]) {
4430 g_assert (tramp_size);
4431 acfg->trampoline_size [ntype] = tramp_size;
4436 /* Reserve some entries at the end of the GOT for our use */
4437 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4440 acfg->got_offset += acfg->num_trampoline_got_entries;
4444 str_begins_with (const char *str1, const char *str2)
4446 int len = strlen (str2);
4447 return strncmp (str1, str2, len) == 0;
4451 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
4453 gchar **args, **ptr;
4455 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
4456 for (ptr = args; ptr && *ptr; ptr ++) {
4457 const char *arg = *ptr;
4459 if (str_begins_with (arg, "outfile=")) {
4460 opts->outfile = g_strdup (arg + strlen ("outfile="));
4461 } else if (str_begins_with (arg, "save-temps")) {
4462 opts->save_temps = TRUE;
4463 } else if (str_begins_with (arg, "keep-temps")) {
4464 opts->save_temps = TRUE;
4465 } else if (str_begins_with (arg, "write-symbols")) {
4466 opts->write_symbols = TRUE;
4467 } else if (str_begins_with (arg, "metadata-only")) {
4468 opts->metadata_only = TRUE;
4469 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
4470 opts->bind_to_runtime_version = TRUE;
4471 } else if (str_begins_with (arg, "full")) {
4472 opts->full_aot = TRUE;
4473 } else if (str_begins_with (arg, "threads=")) {
4474 opts->nthreads = atoi (arg + strlen ("threads="));
4475 } else if (str_begins_with (arg, "static")) {
4476 opts->static_link = TRUE;
4477 opts->no_dlsym = TRUE;
4478 } else if (str_begins_with (arg, "asmonly")) {
4479 opts->asm_only = TRUE;
4480 } else if (str_begins_with (arg, "asmwriter")) {
4481 opts->asm_writer = TRUE;
4482 } else if (str_begins_with (arg, "nodebug")) {
4483 opts->nodebug = TRUE;
4484 } else if (str_begins_with (arg, "ntrampolines=")) {
4485 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
4486 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
4487 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
4488 } else if (str_begins_with (arg, "nimt-trampolines=")) {
4489 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
4490 } else if (str_begins_with (arg, "autoreg")) {
4491 opts->autoreg = TRUE;
4492 } else if (str_begins_with (arg, "tool-prefix=")) {
4493 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4494 } else if (str_begins_with (arg, "soft-debug")) {
4495 opts->soft_debug = TRUE;
4496 } else if (str_begins_with (arg, "print-skipped")) {
4497 opts->print_skipped_methods = TRUE;
4498 } else if (str_begins_with (arg, "stats")) {
4500 } else if (str_begins_with (arg, "mtriple=")) {
4501 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
4503 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4512 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4514 MonoMethod *method = (MonoMethod*)key;
4515 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4516 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4517 MonoAotCompile *acfg = user_data;
4519 new_ji->image = ji->image;
4520 new_ji->token = ji->token;
4521 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4525 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4527 if (klass->type_token)
4529 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4532 return can_encode_class (acfg, klass->element_class);
4537 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4539 switch (patch_info->type) {
4540 case MONO_PATCH_INFO_METHOD:
4541 case MONO_PATCH_INFO_METHODCONST: {
4542 MonoMethod *method = patch_info->data.method;
4544 if (method->wrapper_type) {
4545 switch (method->wrapper_type) {
4546 case MONO_WRAPPER_NONE:
4547 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4548 case MONO_WRAPPER_XDOMAIN_INVOKE:
4549 case MONO_WRAPPER_STFLD:
4550 case MONO_WRAPPER_LDFLD:
4551 case MONO_WRAPPER_LDFLDA:
4552 case MONO_WRAPPER_LDFLD_REMOTE:
4553 case MONO_WRAPPER_STFLD_REMOTE:
4554 case MONO_WRAPPER_STELEMREF:
4555 case MONO_WRAPPER_ISINST:
4556 case MONO_WRAPPER_PROXY_ISINST:
4557 case MONO_WRAPPER_ALLOC:
4558 case MONO_WRAPPER_REMOTING_INVOKE:
4559 case MONO_WRAPPER_UNKNOWN:
4560 case MONO_WRAPPER_WRITE_BARRIER:
4562 case MONO_WRAPPER_MANAGED_TO_MANAGED:
4563 if (!strcmp (method->name, "ElementAddr"))
4568 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4572 if (!method->token) {
4573 /* The method is part of a constructed type like Int[,].Set (). */
4574 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4575 if (method->klass->rank)
4583 case MONO_PATCH_INFO_VTABLE:
4584 case MONO_PATCH_INFO_CLASS_INIT:
4585 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4586 case MONO_PATCH_INFO_CLASS:
4587 case MONO_PATCH_INFO_IID:
4588 case MONO_PATCH_INFO_ADJUSTED_IID:
4589 if (!can_encode_class (acfg, patch_info->data.klass)) {
4590 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4594 case MONO_PATCH_INFO_RGCTX_FETCH: {
4595 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4597 if (!can_encode_patch (acfg, entry->data))
4611 * AOT compile a given method.
4612 * This function might be called by multiple threads, so it must be thread-safe.
4615 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4618 MonoJumpInfo *patch_info;
4621 MonoMethod *wrapped;
4623 if (acfg->aot_opts.metadata_only)
4626 mono_acfg_lock (acfg);
4627 index = get_method_index (acfg, method);
4628 mono_acfg_unlock (acfg);
4630 /* fixme: maybe we can also precompile wrapper methods */
4631 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4632 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4633 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4634 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4638 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4641 wrapped = mono_marshal_method_from_wrapper (method);
4642 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4643 // FIXME: The wrapper should be generic too, but it is not
4646 InterlockedIncrement (&acfg->stats.mcount);
4649 if (method->is_generic || method->klass->generic_container) {
4650 InterlockedIncrement (&acfg->stats.genericcount);
4655 //acfg->aot_opts.print_skipped_methods = TRUE;
4658 * Since these methods are the only ones which are compiled with
4659 * AOT support, and they are not used by runtime startup/shutdown code,
4660 * the runtime will not see AOT methods during AOT compilation,so it
4661 * does not need to support them by creating a fake GOT etc.
4663 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4664 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4665 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4666 InterlockedIncrement (&acfg->stats.genericcount);
4669 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4670 /* Let the exception happen at runtime */
4674 if (cfg->disable_aot) {
4675 if (acfg->aot_opts.print_skipped_methods)
4676 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4677 InterlockedIncrement (&acfg->stats.ocount);
4678 mono_destroy_compile (cfg);
4682 /* Nullify patches which need no aot processing */
4683 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4684 switch (patch_info->type) {
4685 case MONO_PATCH_INFO_LABEL:
4686 case MONO_PATCH_INFO_BB:
4687 patch_info->type = MONO_PATCH_INFO_NONE;
4694 /* Collect method->token associations from the cfg */
4695 mono_acfg_lock (acfg);
4696 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4697 mono_acfg_unlock (acfg);
4700 * Check for absolute addresses.
4703 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4704 switch (patch_info->type) {
4705 case MONO_PATCH_INFO_ABS:
4706 /* unable to handle this */
4715 if (acfg->aot_opts.print_skipped_methods)
4716 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4717 InterlockedIncrement (&acfg->stats.abscount);
4718 mono_destroy_compile (cfg);
4722 /* Lock for the rest of the code */
4723 mono_acfg_lock (acfg);
4726 * Check for methods/klasses we can't encode.
4729 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4730 if (!can_encode_patch (acfg, patch_info))
4735 if (acfg->aot_opts.print_skipped_methods)
4736 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4737 acfg->stats.ocount++;
4738 mono_destroy_compile (cfg);
4739 mono_acfg_unlock (acfg);
4743 /* Adds generic instances referenced by this method */
4745 * The depth is used to avoid infinite loops when generic virtual recursion is
4748 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4750 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4751 switch (patch_info->type) {
4752 case MONO_PATCH_INFO_METHOD: {
4753 MonoMethod *m = patch_info->data.method;
4754 if (m->is_inflated) {
4755 if (!(mono_class_generic_sharing_enabled (m->klass) &&
4756 mono_method_is_generic_sharable_impl (m, FALSE)) &&
4757 !method_has_type_vars (m)) {
4758 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4759 if (acfg->aot_opts.full_aot)
4760 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4762 add_extra_method_with_depth (acfg, m, depth + 1);
4765 add_generic_class_with_depth (acfg, m->klass, depth + 5);
4767 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4768 add_extra_method_with_depth (acfg, m, depth + 1);
4771 case MONO_PATCH_INFO_VTABLE: {
4772 MonoClass *klass = patch_info->data.klass;
4774 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4775 add_generic_class_with_depth (acfg, klass, depth + 5);
4784 /* Determine whenever the method has GOT slots */
4785 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4786 switch (patch_info->type) {
4787 case MONO_PATCH_INFO_GOT_OFFSET:
4788 case MONO_PATCH_INFO_NONE:
4789 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4791 case MONO_PATCH_INFO_IMAGE:
4792 /* The assembly is stored in GOT slot 0 */
4793 if (patch_info->data.image != acfg->image)
4794 cfg->has_got_slots = TRUE;
4797 if (!is_plt_patch (patch_info))
4798 cfg->has_got_slots = TRUE;
4803 if (!cfg->has_got_slots)
4804 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4807 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4809 /* Make a copy of the patch info which is in the mempool */
4811 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4813 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4814 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4817 patches = new_patch_info;
4819 patches_end->next = new_patch_info;
4820 patches_end = new_patch_info;
4822 cfg->patch_info = patches;
4824 /* Make a copy of the unwind info */
4826 GSList *l, *unwind_ops;
4830 for (l = cfg->unwind_ops; l; l = l->next) {
4831 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4832 memcpy (op, l->data, sizeof (MonoUnwindOp));
4833 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4835 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4837 /* Make a copy of the argument/local info */
4839 MonoInst **args, **locals;
4840 MonoMethodSignature *sig;
4841 MonoMethodHeader *header;
4844 sig = mono_method_signature (method);
4845 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4846 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4847 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4848 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4852 header = mono_method_get_header (method);
4853 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
4854 for (i = 0; i < header->num_locals; ++i) {
4855 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4856 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
4858 cfg->locals = locals;
4861 /* Free some fields used by cfg to conserve memory */
4862 mono_mempool_destroy (cfg->mempool);
4863 cfg->mempool = NULL;
4864 g_free (cfg->varinfo);
4865 cfg->varinfo = NULL;
4869 mono_regstate_free (cfg->rs);
4873 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
4875 while (index >= acfg->cfgs_size) {
4876 MonoCompile **new_cfgs;
4879 new_size = acfg->cfgs_size * 2;
4880 new_cfgs = g_new0 (MonoCompile*, new_size);
4881 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4882 g_free (acfg->cfgs);
4883 acfg->cfgs = new_cfgs;
4884 acfg->cfgs_size = new_size;
4886 acfg->cfgs [index] = cfg;
4888 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4891 if (cfg->orig_method->wrapper_type)
4892 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4895 mono_acfg_unlock (acfg);
4897 InterlockedIncrement (&acfg->stats.ccount);
4901 compile_thread_main (gpointer *user_data)
4903 MonoDomain *domain = user_data [0];
4904 MonoAotCompile *acfg = user_data [1];
4905 GPtrArray *methods = user_data [2];
4908 mono_thread_attach (domain);
4910 for (i = 0; i < methods->len; ++i)
4911 compile_method (acfg, g_ptr_array_index (methods, i));
4915 load_profile_files (MonoAotCompile *acfg)
4919 int file_index, res, method_index, i;
4926 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
4928 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4933 infile = fopen (tmp, "r");
4936 printf ("Using profile data file '%s'\n", tmp);
4941 res = fscanf (infile, "%32s\n", ver);
4942 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
4943 printf ("Profile file has wrong version or invalid.\n");
4950 MonoMethodDesc *desc;
4953 if (fgets (name, 1023, infile) == NULL)
4956 /* Kill the newline */
4957 if (strlen (name) > 0)
4958 name [strlen (name) - 1] = '\0';
4960 desc = mono_method_desc_new (name, TRUE);
4962 method = mono_method_desc_search_in_image (desc, acfg->image);
4964 if (method && mono_method_get_token (method)) {
4965 token = mono_method_get_token (method);
4966 method_index = mono_metadata_token_index (token) - 1;
4968 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index))) {
4969 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4972 //printf ("No method found matching '%s'.\n", name);
4978 /* Add missing methods */
4980 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4981 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4982 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4984 unordered = g_list_reverse (unordered);
4985 if (acfg->method_order)
4986 g_list_last (acfg->method_order)->next = unordered;
4988 acfg->method_order = unordered;
4991 /* Used by the LLVM backend */
4993 mono_aot_get_got_offset (MonoJumpInfo *ji)
4995 return get_got_offset (llvm_acfg, ji);
4999 mono_aot_get_method_name (MonoCompile *cfg)
5001 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
5005 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
5007 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
5008 MonoPltEntry *plt_entry;
5011 ji->data.target = data;
5013 if (!can_encode_patch (llvm_acfg, ji))
5016 plt_entry = get_plt_entry (llvm_acfg, ji);
5017 plt_entry->llvm_used = TRUE;
5019 return g_strdup_printf (plt_entry->llvm_symbol);
5023 mono_aot_patch_info_dup (MonoJumpInfo* ji)
5027 mono_acfg_lock (llvm_acfg);
5028 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
5029 mono_acfg_unlock (llvm_acfg);
5039 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
5043 emit_llvm_file (MonoAotCompile *acfg)
5045 char *command, *opts;
5047 MonoJumpInfo *patch_info;
5050 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
5054 /* Compute the final size of the got */
5055 for (i = 0; i < acfg->nmethods; ++i) {
5056 if (acfg->cfgs [i]) {
5057 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
5058 if (patch_info->type != MONO_PATCH_INFO_NONE) {
5059 if (!is_plt_patch (patch_info))
5060 get_got_offset (acfg, patch_info);
5062 get_plt_entry (acfg, patch_info);
5068 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
5070 if (acfg->aot_opts.full_aot) {
5074 * Need to add the got entries used by the trampolines.
5075 * This is only a conservative approximation.
5077 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5078 /* For the generic + rgctx trampolines */
5079 acfg->final_got_size += 200;
5080 /* For the specific trampolines */
5081 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
5082 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
5087 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
5090 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
5091 * a lot of time, and doesn't seem to save much space.
5092 * The following optimizations cannot be enabled:
5094 * - 'jump-threading' changes our blockaddress references to int constants.
5095 * The opt list below was produced by taking the output of:
5096 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
5097 * then removing tailcallelim + the global opts, and adding a second gvn.
5099 opts = g_strdup ("-instcombine -simplifycfg");
5100 opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -basiccg -prune-eh -inline -functionattrs -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loopsimplify -domfrontier -loopsimplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loopsimplify -lcssa -iv-users -indvars -loop-deletion -loopsimplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -gvn -simplifycfg -preverify -domtree -verify");
5102 command = g_strdup_printf ("opt -f %s -o temp.opt.bc temp.bc", opts);
5103 printf ("Executing opt: %s\n", command);
5104 if (system (command) != 0) {
5110 if (!acfg->llc_args)
5111 acfg->llc_args = g_string_new ("");
5113 /* Verbose asm slows down llc greatly */
5114 g_string_append (acfg->llc_args, " -asm-verbose=false");
5116 if (acfg->aot_opts.mtriple)
5117 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5119 unlink (acfg->tmpfname);
5121 command = g_strdup_printf ("llc %s -relocation-model=pic -unwind-tables -disable-gnu-eh-frame -enable-mono-eh-frame -o %s temp.opt.bc", acfg->llc_args->str, acfg->tmpfname);
5123 printf ("Executing llc: %s\n", command);
5125 if (system (command) != 0) {
5132 emit_code (MonoAotCompile *acfg)
5136 char end_symbol [256];
5139 #if defined(TARGET_POWERPC64)
5140 sprintf (symbol, ".Lgot_addr");
5141 emit_section_change (acfg, ".text", 0);
5142 emit_alignment (acfg, 8);
5143 emit_label (acfg, symbol);
5144 emit_pointer (acfg, acfg->got_symbol);
5148 * This global symbol is used to compute the address of each method using the
5149 * code_offsets array. It is also used to compute the memory ranges occupied by
5150 * AOT code, so it must be equal to the address of the first emitted method.
5152 sprintf (symbol, "methods");
5153 emit_section_change (acfg, ".text", 0);
5154 emit_alignment (acfg, 8);
5156 for (i = 0; i < acfg->nmethods; ++i) {
5157 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
5158 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
5162 if (i == acfg->nmethods)
5163 /* No LLVM compiled methods */
5164 emit_label (acfg, symbol);
5166 emit_label (acfg, symbol);
5170 * Emit some padding so the local symbol for the first method doesn't have the
5171 * same address as 'methods'.
5173 #if defined(__default_codegen__)
5174 emit_zero_bytes (acfg, 16);
5175 #elif defined(__native_client_codegen__)
5177 const int kPaddingSize = 16;
5178 guint8 pad_buffer[kPaddingSize];
5179 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
5180 emit_bytes (acfg, pad_buffer, kPaddingSize);
5185 for (l = acfg->method_order; l != NULL; l = l->next) {
5189 i = GPOINTER_TO_UINT (l->data);
5191 cfg = acfg->cfgs [i];
5196 method = cfg->orig_method;
5198 /* Emit unbox trampoline */
5199 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
5200 char call_target [256];
5202 if (!method->wrapper_type && !method->is_inflated) {
5203 g_assert (method->token);
5204 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
5206 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
5209 emit_section_change (acfg, ".text", 0);
5210 #ifdef __native_client_codegen__
5211 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5213 emit_global (acfg, symbol, TRUE);
5214 emit_label (acfg, symbol);
5216 sprintf (call_target, "%s", cfg->asm_symbol);
5218 arch_emit_unbox_trampoline (acfg, cfg->orig_method, call_target);
5221 if (cfg->compile_llvm)
5222 acfg->stats.llvm_count ++;
5224 emit_method_code (acfg, cfg);
5227 sprintf (symbol, "methods_end");
5228 emit_section_change (acfg, ".text", 0);
5229 emit_alignment (acfg, 8);
5230 emit_label (acfg, symbol);
5232 sprintf (symbol, "code_offsets");
5233 emit_section_change (acfg, RODATA_SECT, 1);
5234 emit_alignment (acfg, 8);
5235 emit_label (acfg, symbol);
5237 acfg->stats.offsets_size += acfg->nmethods * 4;
5239 sprintf (end_symbol, "methods");
5240 for (i = 0; i < acfg->nmethods; ++i) {
5241 if (acfg->cfgs [i]) {
5242 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
5244 emit_int32 (acfg, 0xffffffff);
5251 emit_info (MonoAotCompile *acfg)
5258 offsets = g_new0 (gint32, acfg->nmethods);
5260 for (l = acfg->method_order; l != NULL; l = l->next) {
5261 i = GPOINTER_TO_UINT (l->data);
5263 if (acfg->cfgs [i]) {
5264 emit_method_info (acfg, acfg->cfgs [i]);
5265 offsets [i] = acfg->cfgs [i]->method_info_offset;
5271 sprintf (symbol, "method_info_offsets");
5272 emit_section_change (acfg, RODATA_SECT, 1);
5273 emit_alignment (acfg, 8);
5274 emit_label (acfg, symbol);
5276 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5281 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
5283 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
5284 #define mix(a,b,c) { \
5285 a -= c; a ^= rot(c, 4); c += b; \
5286 b -= a; b ^= rot(a, 6); a += c; \
5287 c -= b; c ^= rot(b, 8); b += a; \
5288 a -= c; a ^= rot(c,16); c += b; \
5289 b -= a; b ^= rot(a,19); a += c; \
5290 c -= b; c ^= rot(b, 4); b += a; \
5292 #define final(a,b,c) { \
5293 c ^= b; c -= rot(b,14); \
5294 a ^= c; a -= rot(c,11); \
5295 b ^= a; b -= rot(a,25); \
5296 c ^= b; c -= rot(b,16); \
5297 a ^= c; a -= rot(c,4); \
5298 b ^= a; b -= rot(a,14); \
5299 c ^= b; c -= rot(b,24); \
5303 mono_aot_type_hash (MonoType *t1)
5305 guint hash = t1->type;
5307 hash |= t1->byref << 6; /* do not collide with t1->type values */
5309 case MONO_TYPE_VALUETYPE:
5310 case MONO_TYPE_CLASS:
5311 case MONO_TYPE_SZARRAY:
5312 /* check if the distribution is good enough */
5313 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
5315 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
5316 case MONO_TYPE_ARRAY:
5317 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
5318 case MONO_TYPE_GENERICINST:
5319 return ((hash << 5) - hash) ^ 0;
5325 * mono_aot_method_hash:
5327 * Return a hash code for methods which only depends on metadata.
5330 mono_aot_method_hash (MonoMethod *method)
5332 MonoMethodSignature *sig;
5336 guint32 *hashes_start, *hashes;
5338 MonoGenericInst *ginst = NULL;
5340 /* Similar to the hash in mono_method_get_imt_slot () */
5342 sig = mono_method_signature (method);
5344 if (method->is_inflated)
5345 ginst = ((MonoMethodInflated*)method)->context.method_inst;
5347 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
5348 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
5349 hashes = hashes_start;
5351 /* Some wrappers are assigned to random classes */
5352 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
5353 klass = method->klass;
5355 klass = mono_defaults.object_class;
5357 if (!method->wrapper_type) {
5358 char *full_name = mono_type_full_name (&klass->byval_arg);
5360 hashes [0] = mono_metadata_str_hash (full_name);
5364 hashes [0] = mono_metadata_str_hash (klass->name);
5365 hashes [1] = mono_metadata_str_hash (klass->name_space);
5367 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
5368 /* The method name includes a stringified pointer */
5371 hashes [2] = mono_metadata_str_hash (method->name);
5372 hashes [3] = method->wrapper_type;
5373 hashes [4] = mono_aot_type_hash (sig->ret);
5375 for (i = 0; i < sig->param_count; i++) {
5376 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
5379 for (i = 0; i < ginst->type_argc; ++i)
5380 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
5382 g_assert (hindex == hashes_count);
5384 /* Setup internal state */
5385 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
5387 /* Handle most of the hashes */
5388 while (hashes_count > 3) {
5397 /* Handle the last 3 hashes (all the case statements fall through) */
5398 switch (hashes_count) {
5399 case 3 : c += hashes [2];
5400 case 2 : b += hashes [1];
5401 case 1 : a += hashes [0];
5403 case 0: /* nothing left to add */
5407 free (hashes_start);
5416 * mono_aot_wrapper_name:
5418 * Return a string which uniqely identifies the given wrapper method.
5421 mono_aot_wrapper_name (MonoMethod *method)
5423 char *name, *tmpsig, *klass_desc;
5425 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
5427 switch (method->wrapper_type) {
5428 case MONO_WRAPPER_RUNTIME_INVOKE:
5429 if (!strcmp (method->name, "runtime_invoke_dynamic"))
5430 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
5432 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
5435 klass_desc = mono_type_full_name (&method->klass->byval_arg);
5436 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
5437 g_free (klass_desc);
5447 * mono_aot_get_array_helper_from_wrapper;
5449 * Get the helper method in Array called by an array wrapper method.
5452 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
5456 MonoGenericContext ctx;
5457 MonoType *args [16];
5458 char *mname, *iname, *s, *s2, *helper_name = NULL;
5460 prefix = "System.Collections.Generic";
5461 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
5462 s2 = strstr (s, "`1.");
5468 //printf ("X: %s %s\n", iname, mname);
5470 if (!strcmp (iname, "IList"))
5471 helper_name = g_strdup_printf ("InternalArray__%s", mname);
5473 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
5474 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
5476 g_free (helper_name);
5479 if (m->is_generic) {
5480 memset (&ctx, 0, sizeof (ctx));
5481 args [0] = &method->klass->element_class->byval_arg;
5482 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5483 m = mono_class_inflate_generic_method (m, &ctx);
5489 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
5491 typedef struct HashEntry {
5492 guint32 key, value, index;
5493 struct HashEntry *next;
5497 * emit_extra_methods:
5499 * Emit methods which are not in the METHOD table, like wrappers.
5502 emit_extra_methods (MonoAotCompile *acfg)
5504 int i, table_size, buf_size;
5507 guint32 *info_offsets;
5510 HashEntry *entry, *new_entry;
5511 int nmethods, max_chain_length;
5514 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5516 /* Emit method info */
5518 for (i = 0; i < acfg->extra_methods->len; ++i) {
5519 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5520 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5527 p = buf = g_malloc (buf_size);
5531 method = cfg->method_to_register;
5534 if (method->wrapper_type) {
5535 gboolean encode_ref = FALSE;
5538 * We encode some wrappers using their name, since encoding them
5539 * directly would be difficult. This works because at runtime, we only need to
5540 * check whenever a method ref matches an existing MonoMethod. The downside is
5541 * that the method names are large, so we use the binary encoding if possible.
5543 switch (method->wrapper_type) {
5544 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5545 case MONO_WRAPPER_SYNCHRONIZED:
5548 case MONO_WRAPPER_MANAGED_TO_NATIVE:
5549 /* Skip JIT icall wrappers */
5550 if (!strstr (method->name, "__icall_wrapper"))
5553 case MONO_WRAPPER_UNKNOWN:
5554 if (!strcmp (method->name, "PtrToStructure") || !strcmp (method->name, "StructureToPtr"))
5557 case MONO_WRAPPER_RUNTIME_INVOKE:
5558 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5559 /* Direct wrapper, encode normally */
5567 name = mono_aot_wrapper_name (method);
5571 encode_value (1, p, &p);
5572 encode_value (method->wrapper_type, p, &p);
5573 strcpy ((char*)p, name);
5574 p += strlen (name ) + 1;
5577 encode_value (0, p, &p);
5578 encode_method_ref (acfg, method, p, &p);
5581 g_assert ((p - buf) < buf_size);
5583 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5588 * Construct a chained hash table for mapping indexes in extra_method_info to
5591 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5592 table = g_ptr_array_sized_new (table_size);
5593 for (i = 0; i < table_size; ++i)
5594 g_ptr_array_add (table, NULL);
5595 chain_lengths = g_new0 (int, table_size);
5596 max_chain_length = 0;
5597 for (i = 0; i < acfg->extra_methods->len; ++i) {
5598 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5599 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5605 key = info_offsets [i];
5606 value = get_method_index (acfg, method);
5608 hash = mono_aot_method_hash (method) % table_size;
5610 chain_lengths [hash] ++;
5611 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5613 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5614 new_entry->key = key;
5615 new_entry->value = value;
5617 entry = g_ptr_array_index (table, hash);
5618 if (entry == NULL) {
5619 new_entry->index = hash;
5620 g_ptr_array_index (table, hash) = new_entry;
5623 entry = entry->next;
5625 entry->next = new_entry;
5626 new_entry->index = table->len;
5627 g_ptr_array_add (table, new_entry);
5631 //printf ("MAX: %d\n", max_chain_length);
5633 /* Emit the table */
5634 sprintf (symbol, "extra_method_table");
5635 emit_section_change (acfg, RODATA_SECT, 0);
5636 emit_alignment (acfg, 8);
5637 emit_label (acfg, symbol);
5639 emit_int32 (acfg, table_size);
5640 for (i = 0; i < table->len; ++i) {
5641 HashEntry *entry = g_ptr_array_index (table, i);
5643 if (entry == NULL) {
5644 emit_int32 (acfg, 0);
5645 emit_int32 (acfg, 0);
5646 emit_int32 (acfg, 0);
5648 //g_assert (entry->key > 0);
5649 emit_int32 (acfg, entry->key);
5650 emit_int32 (acfg, entry->value);
5652 emit_int32 (acfg, entry->next->index);
5654 emit_int32 (acfg, 0);
5659 * Emit a table reverse mapping method indexes to their index in extra_method_info.
5660 * This is used by mono_aot_find_jit_info ().
5662 sprintf (symbol, "extra_method_info_offsets");
5663 emit_section_change (acfg, RODATA_SECT, 0);
5664 emit_alignment (acfg, 8);
5665 emit_label (acfg, symbol);
5667 emit_int32 (acfg, acfg->extra_methods->len);
5668 for (i = 0; i < acfg->extra_methods->len; ++i) {
5669 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5671 emit_int32 (acfg, get_method_index (acfg, method));
5672 emit_int32 (acfg, info_offsets [i]);
5677 emit_exception_info (MonoAotCompile *acfg)
5683 offsets = g_new0 (gint32, acfg->nmethods);
5684 for (i = 0; i < acfg->nmethods; ++i) {
5685 if (acfg->cfgs [i]) {
5686 emit_exception_debug_info (acfg, acfg->cfgs [i]);
5687 offsets [i] = acfg->cfgs [i]->ex_info_offset;
5693 sprintf (symbol, "ex_info_offsets");
5694 emit_section_change (acfg, RODATA_SECT, 1);
5695 emit_alignment (acfg, 8);
5696 emit_label (acfg, symbol);
5698 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5703 emit_unwind_info (MonoAotCompile *acfg)
5709 * The unwind info contains a lot of duplicates so we emit each unique
5710 * entry once, and only store the offset from the start of the table in the
5714 sprintf (symbol, "unwind_info");
5715 emit_section_change (acfg, RODATA_SECT, 1);
5716 emit_alignment (acfg, 8);
5717 emit_label (acfg, symbol);
5719 for (i = 0; i < acfg->unwind_ops->len; ++i) {
5720 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5721 guint8 *unwind_info;
5722 guint32 unwind_info_len;
5726 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5729 encode_value (unwind_info_len, p, &p);
5730 emit_bytes (acfg, buf, p - buf);
5731 emit_bytes (acfg, unwind_info, unwind_info_len);
5733 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5738 emit_class_info (MonoAotCompile *acfg)
5744 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5745 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5746 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5748 sprintf (symbol, "class_info_offsets");
5749 emit_section_change (acfg, RODATA_SECT, 1);
5750 emit_alignment (acfg, 8);
5751 emit_label (acfg, symbol);
5753 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5757 typedef struct ClassNameTableEntry {
5758 guint32 token, index;
5759 struct ClassNameTableEntry *next;
5760 } ClassNameTableEntry;
5763 emit_class_name_table (MonoAotCompile *acfg)
5766 guint32 token, hash;
5771 ClassNameTableEntry *entry, *new_entry;
5774 * Construct a chained hash table for mapping class names to typedef tokens.
5776 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
5777 table = g_ptr_array_sized_new (table_size);
5778 for (i = 0; i < table_size; ++i)
5779 g_ptr_array_add (table, NULL);
5780 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
5781 token = MONO_TOKEN_TYPE_DEF | (i + 1);
5782 klass = mono_class_get (acfg->image, token);
5785 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
5786 hash = mono_metadata_str_hash (full_name) % table_size;
5789 /* FIXME: Allocate from the mempool */
5790 new_entry = g_new0 (ClassNameTableEntry, 1);
5791 new_entry->token = token;
5793 entry = g_ptr_array_index (table, hash);
5794 if (entry == NULL) {
5795 new_entry->index = hash;
5796 g_ptr_array_index (table, hash) = new_entry;
5799 entry = entry->next;
5801 entry->next = new_entry;
5802 new_entry->index = table->len;
5803 g_ptr_array_add (table, new_entry);
5807 /* Emit the table */
5808 sprintf (symbol, "class_name_table");
5809 emit_section_change (acfg, RODATA_SECT, 0);
5810 emit_alignment (acfg, 8);
5811 emit_label (acfg, symbol);
5813 /* FIXME: Optimize memory usage */
5814 g_assert (table_size < 65000);
5815 emit_int16 (acfg, table_size);
5816 g_assert (table->len < 65000);
5817 for (i = 0; i < table->len; ++i) {
5818 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
5820 if (entry == NULL) {
5821 emit_int16 (acfg, 0);
5822 emit_int16 (acfg, 0);
5824 emit_int16 (acfg, mono_metadata_token_index (entry->token));
5826 emit_int16 (acfg, entry->next->index);
5828 emit_int16 (acfg, 0);
5834 emit_image_table (MonoAotCompile *acfg)
5840 * The image table is small but referenced in a lot of places.
5841 * So we emit it at once, and reference its elements by an index.
5844 sprintf (symbol, "image_table");
5845 emit_section_change (acfg, RODATA_SECT, 1);
5846 emit_alignment (acfg, 8);
5847 emit_label (acfg, symbol);
5849 emit_int32 (acfg, acfg->image_table->len);
5850 for (i = 0; i < acfg->image_table->len; i++) {
5851 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
5852 MonoAssemblyName *aname = &image->assembly->aname;
5854 /* FIXME: Support multi-module assemblies */
5855 g_assert (image->assembly->image == image);
5857 emit_string (acfg, image->assembly_name);
5858 emit_string (acfg, image->guid);
5859 emit_string (acfg, aname->culture ? aname->culture : "");
5860 emit_string (acfg, (const char*)aname->public_key_token);
5862 emit_alignment (acfg, 8);
5863 emit_int32 (acfg, aname->flags);
5864 emit_int32 (acfg, aname->major);
5865 emit_int32 (acfg, aname->minor);
5866 emit_int32 (acfg, aname->build);
5867 emit_int32 (acfg, aname->revision);
5872 emit_got_info (MonoAotCompile *acfg)
5875 int i, first_plt_got_patch, buf_size;
5877 guint32 *got_info_offsets;
5879 /* Add the patches needed by the PLT to the GOT */
5880 acfg->plt_got_offset_base = acfg->got_offset;
5881 first_plt_got_patch = acfg->got_patches->len;
5882 for (i = 1; i < acfg->plt_offset; ++i) {
5883 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5885 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
5888 acfg->got_offset += acfg->plt_offset;
5892 * - optimize offsets table.
5893 * - reduce number of exported symbols.
5894 * - emit info for a klass only once.
5895 * - determine when a method uses a GOT slot which is guaranteed to be already
5897 * - clean up and document the code.
5898 * - use String.Empty in class libs.
5901 /* Encode info required to decode shared GOT entries */
5902 buf_size = acfg->got_patches->len * 128;
5903 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
5904 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
5905 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
5907 if (acfg->plt_offset)
5908 acfg->plt_got_info_offsets [0] = 0;
5909 for (i = 0; i < acfg->got_patches->len; ++i) {
5910 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
5914 encode_value (ji->type, p, &p);
5915 encode_patch (acfg, ji, p, &p);
5917 g_assert (p - buf <= buf_size);
5918 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5920 if (i >= first_plt_got_patch)
5921 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
5922 acfg->stats.got_info_size += p - buf;
5925 /* Emit got_info_offsets table */
5926 sprintf (symbol, "got_info_offsets");
5927 emit_section_change (acfg, RODATA_SECT, 1);
5928 emit_alignment (acfg, 8);
5929 emit_label (acfg, symbol);
5931 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
5932 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
5936 emit_got (MonoAotCompile *acfg)
5941 /* Don't make GOT global so accesses to it don't need relocations */
5942 sprintf (symbol, "%s", acfg->got_symbol);
5943 emit_section_change (acfg, ".bss", 0);
5944 emit_alignment (acfg, 8);
5945 emit_local_symbol (acfg, symbol, "got_end", FALSE);
5946 emit_label (acfg, symbol);
5947 if (acfg->got_offset > 0)
5948 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5950 sprintf (symbol, "got_end");
5951 emit_label (acfg, symbol);
5955 typedef struct GlobalsTableEntry {
5956 guint32 value, index;
5957 struct GlobalsTableEntry *next;
5958 } GlobalsTableEntry;
5961 emit_globals_table (MonoAotCompile *acfg)
5967 GlobalsTableEntry *entry, *new_entry;
5970 * Construct a chained hash table for mapping global names to their index in
5971 * the globals table.
5973 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
5974 table = g_ptr_array_sized_new (table_size);
5975 for (i = 0; i < table_size; ++i)
5976 g_ptr_array_add (table, NULL);
5977 for (i = 0; i < acfg->globals->len; ++i) {
5978 char *name = g_ptr_array_index (acfg->globals, i);
5980 hash = mono_metadata_str_hash (name) % table_size;
5982 /* FIXME: Allocate from the mempool */
5983 new_entry = g_new0 (GlobalsTableEntry, 1);
5984 new_entry->value = i;
5986 entry = g_ptr_array_index (table, hash);
5987 if (entry == NULL) {
5988 new_entry->index = hash;
5989 g_ptr_array_index (table, hash) = new_entry;
5992 entry = entry->next;
5994 entry->next = new_entry;
5995 new_entry->index = table->len;
5996 g_ptr_array_add (table, new_entry);
6000 /* Emit the table */
6001 sprintf (symbol, ".Lglobals_hash");
6002 emit_section_change (acfg, RODATA_SECT, 0);
6003 emit_alignment (acfg, 8);
6004 emit_label (acfg, symbol);
6006 /* FIXME: Optimize memory usage */
6007 g_assert (table_size < 65000);
6008 emit_int16 (acfg, table_size);
6009 for (i = 0; i < table->len; ++i) {
6010 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
6012 if (entry == NULL) {
6013 emit_int16 (acfg, 0);
6014 emit_int16 (acfg, 0);
6016 emit_int16 (acfg, entry->value + 1);
6018 emit_int16 (acfg, entry->next->index);
6020 emit_int16 (acfg, 0);
6024 /* Emit the names */
6025 for (i = 0; i < acfg->globals->len; ++i) {
6026 char *name = g_ptr_array_index (acfg->globals, i);
6028 sprintf (symbol, "name_%d", i);
6029 emit_section_change (acfg, RODATA_SECT, 1);
6030 emit_label (acfg, symbol);
6031 emit_string (acfg, name);
6034 /* Emit the globals table */
6035 sprintf (symbol, ".Lglobals");
6036 emit_section_change (acfg, ".data", 0);
6037 /* This is not a global, since it is accessed by the init function */
6038 emit_alignment (acfg, 8);
6039 emit_label (acfg, symbol);
6041 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
6042 emit_pointer (acfg, symbol);
6044 for (i = 0; i < acfg->globals->len; ++i) {
6045 char *name = g_ptr_array_index (acfg->globals, i);
6047 sprintf (symbol, "name_%d", i);
6048 emit_pointer (acfg, symbol);
6050 sprintf (symbol, "%s", name);
6051 emit_pointer (acfg, symbol);
6053 /* Null terminate the table */
6054 emit_int32 (acfg, 0);
6055 emit_int32 (acfg, 0);
6059 emit_globals (MonoAotCompile *acfg)
6063 emit_local_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
6065 if (acfg->aot_opts.bind_to_runtime_version) {
6066 build_info = mono_get_runtime_build_info ();
6067 emit_local_string_symbol (acfg, "runtime_version", build_info);
6068 g_free (build_info);
6070 emit_local_string_symbol (acfg, "runtime_version", "");
6074 * When static linking, we emit a global which will point to the symbol table.
6076 if (acfg->aot_opts.static_link) {
6080 /* Emit a string holding the assembly name */
6081 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
6083 emit_globals_table (acfg);
6086 * Emit a global symbol which can be passed by an embedding app to
6087 * mono_aot_register_module ().
6089 #if defined(__MACH__) && !defined(__native_client_codegen__)
6090 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6092 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6095 /* Get rid of characters which cannot occur in symbols */
6097 for (p = symbol; *p; ++p) {
6098 if (!(isalnum (*p) || *p == '_'))
6101 acfg->static_linking_symbol = g_strdup (symbol);
6102 emit_global_inner (acfg, symbol, FALSE);
6103 emit_alignment (acfg, 8);
6104 emit_label (acfg, symbol);
6105 sprintf (symbol, "%sglobals", acfg->temp_prefix);
6106 emit_pointer (acfg, symbol);
6111 emit_autoreg (MonoAotCompile *acfg)
6116 * Emit a function into the .ctor section which will be called by the ELF
6117 * loader to register this module with the runtime.
6119 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6122 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6124 arch_emit_autoreg (acfg, symbol);
6130 emit_mem_end (MonoAotCompile *acfg)
6134 sprintf (symbol, "mem_end");
6135 emit_section_change (acfg, ".text", 1);
6136 emit_alignment (acfg, 8);
6137 emit_label (acfg, symbol);
6141 * Emit a structure containing all the information not stored elsewhere.
6144 emit_file_info (MonoAotCompile *acfg)
6149 const char *gc_name;
6152 * The managed allocators are GC specific, so can't use an AOT image created by one GC
6155 gc_name = mono_gc_get_gc_name ();
6156 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
6158 sprintf (symbol, "mono_aot_file_info");
6159 emit_section_change (acfg, ".data", 0);
6160 emit_alignment (acfg, 8);
6161 emit_label (acfg, symbol);
6162 emit_global (acfg, symbol, FALSE);
6164 /* The data emitted here must match MonoAotFileInfo. */
6166 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
6167 emit_int32 (acfg, 0);
6170 * We emit pointers to our data structures instead of emitting global symbols which
6171 * point to them, to reduce the number of globals, and because using globals leads to
6172 * various problems (i.e. arm/thumb).
6174 emit_pointer (acfg, acfg->got_symbol);
6175 emit_pointer (acfg, "methods");
6178 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
6180 emit_pointer (acfg, "mono_eh_frame");
6182 emit_pointer (acfg, NULL);
6184 emit_pointer (acfg, "blob");
6185 emit_pointer (acfg, "class_name_table");
6186 emit_pointer (acfg, "class_info_offsets");
6187 emit_pointer (acfg, "method_info_offsets");
6188 emit_pointer (acfg, "ex_info_offsets");
6189 emit_pointer (acfg, "code_offsets");
6190 emit_pointer (acfg, "extra_method_info_offsets");
6191 emit_pointer (acfg, "extra_method_table");
6192 emit_pointer (acfg, "got_info_offsets");
6193 emit_pointer (acfg, "methods_end");
6194 emit_pointer (acfg, "unwind_info");
6195 emit_pointer (acfg, "mem_end");
6196 emit_pointer (acfg, "image_table");
6197 emit_pointer (acfg, "plt");
6198 emit_pointer (acfg, "plt_end");
6199 emit_pointer (acfg, "assembly_guid");
6200 emit_pointer (acfg, "runtime_version");
6201 if (acfg->num_trampoline_got_entries) {
6202 emit_pointer (acfg, "specific_trampolines");
6203 emit_pointer (acfg, "static_rgctx_trampolines");
6204 emit_pointer (acfg, "imt_thunks");
6206 emit_pointer (acfg, NULL);
6207 emit_pointer (acfg, NULL);
6208 emit_pointer (acfg, NULL);
6210 if (acfg->thumb_mixed) {
6211 emit_pointer (acfg, "thumb_end");
6213 emit_pointer (acfg, NULL);
6216 emit_int32 (acfg, acfg->plt_got_offset_base);
6217 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6218 emit_int32 (acfg, acfg->plt_offset);
6219 emit_int32 (acfg, acfg->nmethods);
6220 emit_int32 (acfg, acfg->flags);
6221 emit_int32 (acfg, acfg->opts);
6222 emit_int32 (acfg, gc_name_offset);
6224 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6225 emit_int32 (acfg, acfg->num_trampolines [i]);
6226 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6227 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
6228 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6229 emit_int32 (acfg, acfg->trampoline_size [i]);
6233 emit_blob (MonoAotCompile *acfg)
6237 sprintf (symbol, "blob");
6238 emit_section_change (acfg, RODATA_SECT, 1);
6239 emit_alignment (acfg, 8);
6240 emit_label (acfg, symbol);
6242 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
6246 emit_dwarf_info (MonoAotCompile *acfg)
6248 #ifdef EMIT_DWARF_INFO
6250 char symbol [128], symbol2 [128];
6252 /* DIEs for methods */
6253 for (i = 0; i < acfg->nmethods; ++i) {
6254 MonoCompile *cfg = acfg->cfgs [i];
6259 // FIXME: LLVM doesn't define .Lme_...
6260 if (cfg->compile_llvm)
6263 sprintf (symbol, "%s", cfg->asm_symbol);
6264 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
6266 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 ()));
6272 collect_methods (MonoAotCompile *acfg)
6275 MonoImage *image = acfg->image;
6277 /* Collect methods */
6278 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
6280 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
6282 method = mono_get_method (acfg->image, token, NULL);
6285 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
6289 /* Load all methods eagerly to skip the slower lazy loading code */
6290 mono_class_setup_methods (method->klass);
6292 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6293 /* Compile the wrapper instead */
6294 /* We do this here instead of add_wrappers () because it is easy to do it here */
6295 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
6299 /* FIXME: Some mscorlib methods don't have debug info */
6301 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
6302 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6303 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6304 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
6305 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
6306 if (!mono_debug_lookup_method (method)) {
6307 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
6314 /* Since we add the normal methods first, their index will be equal to their zero based token index */
6315 add_method_with_index (acfg, method, i, FALSE);
6316 acfg->method_index ++;
6319 add_generic_instances (acfg);
6321 if (acfg->aot_opts.full_aot)
6322 add_wrappers (acfg);
6326 compile_methods (MonoAotCompile *acfg)
6330 if (acfg->aot_opts.nthreads > 0) {
6335 gpointer *user_data;
6336 MonoMethod **methods;
6338 methods_len = acfg->methods->len;
6340 len = acfg->methods->len / acfg->aot_opts.nthreads;
6343 * Partition the list of methods into fragments, and hand it to threads to
6346 threads = g_ptr_array_new ();
6347 /* Make a copy since acfg->methods is modified by compile_method () */
6348 methods = g_new0 (MonoMethod*, methods_len);
6349 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
6350 for (i = 0; i < methods_len; ++i)
6351 methods [i] = g_ptr_array_index (acfg->methods, i);
6353 while (i < methods_len) {
6354 frag = g_ptr_array_new ();
6355 for (j = 0; j < len; ++j) {
6356 if (i < methods_len) {
6357 g_ptr_array_add (frag, methods [i]);
6362 user_data = g_new0 (gpointer, 3);
6363 user_data [0] = mono_domain_get ();
6364 user_data [1] = acfg;
6365 user_data [2] = frag;
6367 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
6368 g_ptr_array_add (threads, handle);
6372 for (i = 0; i < threads->len; ++i) {
6373 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
6379 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
6380 for (i = methods_len; i < acfg->methods->len; ++i) {
6381 /* This can new methods to acfg->methods */
6382 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
6387 compile_asm (MonoAotCompile *acfg)
6389 char *command, *objfile;
6390 char *outfile_name, *tmp_outfile_name;
6391 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
6393 #if defined(TARGET_AMD64)
6394 #define AS_OPTIONS "--64"
6395 #elif defined(TARGET_POWERPC64)
6396 #define AS_OPTIONS "-a64 -mppc64"
6397 #define LD_OPTIONS "-m elf64ppc"
6398 #elif defined(sparc) && SIZEOF_VOID_P == 8
6399 #define AS_OPTIONS "-xarch=v9"
6400 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6401 #define AS_OPTIONS "-arch i386 -W"
6403 #define AS_OPTIONS ""
6406 #ifdef __native_client_codegen__
6407 #if defined(TARGET_AMD64)
6408 #define AS_NAME "nacl64-as"
6410 #define AS_NAME "nacl-as"
6413 #define AS_NAME "as"
6417 #define LD_OPTIONS ""
6420 #define EH_LD_OPTIONS ""
6422 if (acfg->aot_opts.asm_only) {
6423 printf ("Output file: '%s'.\n", acfg->tmpfname);
6424 if (acfg->aot_opts.static_link)
6425 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6429 if (acfg->aot_opts.static_link) {
6430 if (acfg->aot_opts.outfile)
6431 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6433 objfile = g_strdup_printf ("%s.o", acfg->image->name);
6435 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
6437 command = g_strdup_printf ("%s%s %s %s -o %s %s", tool_prefix, AS_NAME, AS_OPTIONS, acfg->as_args ? acfg->as_args->str : "", objfile, acfg->tmpfname);
6438 printf ("Executing the native assembler: %s\n", command);
6439 if (system (command) != 0) {
6447 if (acfg->aot_opts.static_link) {
6448 printf ("Output file: '%s'.\n", objfile);
6449 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6454 if (acfg->aot_opts.outfile)
6455 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6457 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6459 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6462 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6463 #elif defined(__ppc__) && defined(__MACH__)
6464 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6465 #elif defined(HOST_WIN32)
6466 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6467 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6468 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6470 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
6472 printf ("Executing the native linker: %s\n", command);
6473 if (system (command) != 0) {
6474 g_free (tmp_outfile_name);
6475 g_free (outfile_name);
6483 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
6484 printf ("Stripping the binary: %s\n", com);
6488 #if defined(TARGET_ARM) && !defined(__MACH__)
6490 * gas generates 'mapping symbols' each time code and data is mixed, which
6491 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
6493 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
6494 printf ("Stripping the binary: %s\n", command);
6495 if (system (command) != 0) {
6496 g_free (tmp_outfile_name);
6497 g_free (outfile_name);
6504 rename (tmp_outfile_name, outfile_name);
6506 g_free (tmp_outfile_name);
6507 g_free (outfile_name);
6510 if (acfg->aot_opts.save_temps)
6511 printf ("Retained input file.\n");
6513 unlink (acfg->tmpfname);
6518 static MonoAotCompile*
6519 acfg_create (MonoAssembly *ass, guint32 opts)
6521 MonoImage *image = ass->image;
6522 MonoAotCompile *acfg;
6525 acfg = g_new0 (MonoAotCompile, 1);
6526 acfg->methods = g_ptr_array_new ();
6527 acfg->method_indexes = g_hash_table_new (NULL, NULL);
6528 acfg->method_depth = g_hash_table_new (NULL, NULL);
6529 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
6530 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6531 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6532 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
6533 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6534 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6535 acfg->got_patches = g_ptr_array_new ();
6536 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
6537 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6538 acfg->image_hash = g_hash_table_new (NULL, NULL);
6539 acfg->image_table = g_ptr_array_new ();
6540 acfg->globals = g_ptr_array_new ();
6541 acfg->image = image;
6543 acfg->mempool = mono_mempool_new ();
6544 acfg->extra_methods = g_ptr_array_new ();
6545 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
6546 acfg->unwind_ops = g_ptr_array_new ();
6547 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6548 InitializeCriticalSection (&acfg->mutex);
6554 acfg_free (MonoAotCompile *acfg)
6558 img_writer_destroy (acfg->w);
6559 for (i = 0; i < acfg->nmethods; ++i)
6561 g_free (acfg->cfgs [i]);
6562 g_free (acfg->cfgs);
6563 g_free (acfg->static_linking_symbol);
6564 g_free (acfg->got_symbol);
6565 g_free (acfg->plt_symbol);
6566 g_ptr_array_free (acfg->methods, TRUE);
6567 g_ptr_array_free (acfg->got_patches, TRUE);
6568 g_ptr_array_free (acfg->image_table, TRUE);
6569 g_ptr_array_free (acfg->globals, TRUE);
6570 g_ptr_array_free (acfg->unwind_ops, TRUE);
6571 g_hash_table_destroy (acfg->method_indexes);
6572 g_hash_table_destroy (acfg->method_depth);
6573 g_hash_table_destroy (acfg->plt_offset_to_entry);
6574 g_hash_table_destroy (acfg->patch_to_plt_entry);
6575 g_hash_table_destroy (acfg->patch_to_got_offset);
6576 g_hash_table_destroy (acfg->method_to_cfg);
6577 g_hash_table_destroy (acfg->token_info_hash);
6578 g_hash_table_destroy (acfg->image_hash);
6579 g_hash_table_destroy (acfg->unwind_info_offsets);
6580 g_hash_table_destroy (acfg->method_label_hash);
6581 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6582 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6583 g_free (acfg->patch_to_got_offset_by_type);
6584 mono_mempool_destroy (acfg->mempool);
6589 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6591 MonoImage *image = ass->image;
6593 MonoAotCompile *acfg;
6594 char *outfile_name, *tmp_outfile_name, *p;
6598 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6600 acfg = acfg_create (ass, opts);
6602 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6603 acfg->aot_opts.write_symbols = TRUE;
6604 acfg->aot_opts.ntrampolines = 1024;
6605 acfg->aot_opts.nrgctx_trampolines = 1024;
6606 acfg->aot_opts.nimt_trampolines = 128;
6608 mono_aot_parse_options (aot_options, &acfg->aot_opts);
6610 if (acfg->aot_opts.static_link)
6611 acfg->aot_opts.autoreg = TRUE;
6613 //acfg->aot_opts.print_skipped_methods = TRUE;
6615 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6616 if (acfg->aot_opts.full_aot) {
6617 printf ("--aot=full is not supported on this platform.\n");
6622 if (acfg->aot_opts.static_link)
6623 acfg->aot_opts.asm_writer = TRUE;
6625 if (acfg->aot_opts.soft_debug) {
6626 MonoDebugOptions *opt = mini_get_debug_options ();
6628 opt->mdb_optimizations = TRUE;
6629 opt->gen_seq_points = TRUE;
6631 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6632 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6635 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
6638 if (mono_use_llvm) {
6640 acfg->aot_opts.asm_writer = TRUE;
6641 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6644 if (acfg->aot_opts.full_aot)
6645 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6647 load_profile_files (acfg);
6649 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6650 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6651 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6653 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6655 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6659 acfg->got_symbol_base = g_strdup_printf ("%smono_aot_%s_got", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
6660 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
6662 /* Get rid of characters which cannot occur in symbols */
6663 for (p = acfg->got_symbol_base; *p; ++p) {
6664 if (!(isalnum (*p) || *p == '_'))
6667 for (p = acfg->plt_symbol; *p; ++p) {
6668 if (!(isalnum (*p) || *p == '_'))
6672 acfg->method_index = 1;
6674 collect_methods (acfg);
6676 acfg->cfgs_size = acfg->methods->len + 32;
6677 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6679 /* PLT offset 0 is reserved for the PLT trampoline */
6680 acfg->plt_offset = 1;
6685 mono_llvm_create_aot_module (acfg->got_symbol_base);
6689 /* GOT offset 0 is reserved for the address of the current assembly */
6693 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6694 ji->type = MONO_PATCH_INFO_IMAGE;
6695 ji->data.image = acfg->image;
6697 get_got_offset (acfg, ji);
6699 /* Slot 1 is reserved for the mscorlib got addr */
6700 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6701 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6702 get_got_offset (acfg, ji);
6704 /* This is very common */
6705 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6706 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
6707 get_got_offset (acfg, ji);
6712 compile_methods (acfg);
6716 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6722 if (acfg->aot_opts.asm_only) {
6723 if (acfg->aot_opts.outfile)
6724 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6726 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6728 acfg->tmpfname = g_strdup ("temp.s");
6731 emit_llvm_file (acfg);
6735 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
6736 if (acfg->aot_opts.outfile)
6737 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6739 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6742 * Can't use g_file_open_tmp () as it will be deleted at exit, and
6743 * it might be in another file system so the rename () won't work.
6745 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6747 acfg->fp = fopen (tmp_outfile_name, "w");
6749 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
6753 acfg->w = img_writer_create (acfg->fp, TRUE);
6754 acfg->use_bin_writer = TRUE;
6757 /* Append to the .s file created by llvm */
6758 /* FIXME: Use multiple files instead */
6759 acfg->fp = fopen (acfg->tmpfname, "a+");
6761 if (acfg->aot_opts.asm_only) {
6762 if (acfg->aot_opts.outfile)
6763 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6765 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6766 acfg->fp = fopen (acfg->tmpfname, "w+");
6768 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
6769 acfg->fp = fdopen (i, "w+");
6771 g_assert (acfg->fp);
6773 acfg->w = img_writer_create (acfg->fp, FALSE);
6775 tmp_outfile_name = NULL;
6776 outfile_name = NULL;
6779 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
6781 /* Compute symbols for methods */
6782 for (i = 0; i < acfg->nmethods; ++i) {
6783 if (acfg->cfgs [i]) {
6784 MonoCompile *cfg = acfg->cfgs [i];
6785 int method_index = get_method_index (acfg, cfg->orig_method);
6787 if (COMPILE_LLVM (cfg))
6788 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
6790 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
6794 if (!acfg->aot_opts.nodebug)
6795 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
6797 img_writer_emit_start (acfg->w);
6800 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
6802 if (acfg->thumb_mixed) {
6805 * This global symbol marks the end of THUMB code, and the beginning of ARM
6806 * code generated by our JIT.
6808 sprintf (symbol, "thumb_end");
6809 emit_section_change (acfg, ".text", 0);
6810 emit_label (acfg, symbol);
6811 fprintf (acfg->fp, ".skip 16\n");
6813 fprintf (acfg->fp, ".arm\n");
6820 emit_extra_methods (acfg);
6822 emit_trampolines (acfg);
6824 emit_class_name_table (acfg);
6826 emit_got_info (acfg);
6828 emit_exception_info (acfg);
6830 emit_unwind_info (acfg);
6832 emit_class_info (acfg);
6836 emit_image_table (acfg);
6840 emit_file_info (acfg);
6844 emit_globals (acfg);
6846 emit_autoreg (acfg);
6849 emit_dwarf_info (acfg);
6850 mono_dwarf_writer_close (acfg->dwarf);
6853 emit_mem_end (acfg);
6857 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
6860 g_assert (acfg->got_offset <= acfg->final_got_size);
6862 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);
6865 res = img_writer_emit_writeout (acfg->w);
6870 if (acfg->use_bin_writer) {
6871 int err = rename (tmp_outfile_name, outfile_name);
6874 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
6878 res = compile_asm (acfg);
6885 acfg->stats.link_time = TV_ELAPSED (atv, btv);
6887 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);
6888 if (acfg->stats.genericcount)
6889 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
6890 if (acfg->stats.abscount)
6891 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
6892 if (acfg->stats.lmfcount)
6893 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
6894 if (acfg->stats.ocount)
6895 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
6897 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
6898 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);
6899 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
6901 if (acfg->aot_opts.stats) {
6904 printf ("GOT slot distribution:\n");
6905 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
6906 if (acfg->stats.got_slot_types [i])
6907 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
6910 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);
6922 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)