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;
195 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
196 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
198 /* This points to the current acfg in LLVM mode */
199 static MonoAotCompile *llvm_acfg;
201 #ifdef HAVE_ARRAY_ELEM_INIT
202 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
203 #define MSGSTRFIELD1(line) str##line
204 static const struct msgstr_t {
205 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
206 #include "patch-info.h"
209 #define PATCH_INFO(a,b) b,
210 #include "patch-info.h"
213 static const gint16 opidx [] = {
214 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
215 #include "patch-info.h"
219 static G_GNUC_UNUSED const char*
220 get_patch_name (int info)
222 return (const char*)&opstr + opidx [info];
226 #define PATCH_INFO(a,b) b,
227 static const char* const
228 patch_types [MONO_PATCH_INFO_NUM + 1] = {
229 #include "patch-info.h"
233 static G_GNUC_UNUSED const char*
234 get_patch_name (int info)
236 return patch_types [info];
241 /* Wrappers around the image writer functions */
244 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
246 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
250 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
252 img_writer_emit_push_section (acfg->w, section_name, subsection);
256 emit_pop_section (MonoAotCompile *acfg)
258 img_writer_emit_pop_section (acfg->w);
262 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
264 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
268 emit_label (MonoAotCompile *acfg, const char *name)
270 img_writer_emit_label (acfg->w, name);
274 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
276 img_writer_emit_bytes (acfg->w, buf, size);
280 emit_string (MonoAotCompile *acfg, const char *value)
282 img_writer_emit_string (acfg->w, value);
286 emit_line (MonoAotCompile *acfg)
288 img_writer_emit_line (acfg->w);
292 emit_alignment (MonoAotCompile *acfg, int size)
294 img_writer_emit_alignment (acfg->w, size);
298 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
300 img_writer_emit_pointer_unaligned (acfg->w, target);
304 emit_pointer (MonoAotCompile *acfg, const char *target)
306 img_writer_emit_pointer (acfg->w, target);
310 emit_int16 (MonoAotCompile *acfg, int value)
312 img_writer_emit_int16 (acfg->w, value);
316 emit_int32 (MonoAotCompile *acfg, int value)
318 img_writer_emit_int32 (acfg->w, value);
322 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
324 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
328 emit_zero_bytes (MonoAotCompile *acfg, int num)
330 img_writer_emit_zero_bytes (acfg->w, num);
334 emit_byte (MonoAotCompile *acfg, guint8 val)
336 img_writer_emit_byte (acfg->w, val);
339 #ifdef __native_client_codegen__
341 emit_nacl_call_alignment (MonoAotCompile *acfg)
343 img_writer_emit_nacl_call_alignment (acfg->w);
347 static G_GNUC_UNUSED void
348 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
350 img_writer_emit_global (acfg->w, name, func);
354 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
356 if (acfg->aot_opts.no_dlsym) {
357 g_ptr_array_add (acfg->globals, g_strdup (name));
358 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
360 img_writer_emit_global (acfg->w, name, func);
365 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
367 img_writer_emit_symbol_size (acfg->w, name, end_label);
371 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
373 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
374 emit_global (acfg, name, FALSE);
375 img_writer_emit_label (acfg->w, name);
376 img_writer_emit_string (acfg->w, value);
379 static G_GNUC_UNUSED void
380 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
383 guint8 b = value & 0x7f;
385 if (value != 0) /* more bytes to come */
391 static G_GNUC_UNUSED void
392 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
395 gboolean negative = (value < 0);
402 /* the following is unnecessary if the
403 * implementation of >>= uses an arithmetic rather
404 * than logical shift for a signed left operand
408 value |= - ((gint64)1 <<(size - 7));
409 /* sign bit of byte is second high order bit (0x40) */
410 if ((value == 0 && !(byte & 0x40)) ||
411 (value == -1 && (byte & 0x40)))
415 emit_byte (acfg, byte);
419 static G_GNUC_UNUSED void
420 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
425 guint8 b = value & 0x7f;
427 if (value != 0) /* more bytes to come */
435 static G_GNUC_UNUSED void
436 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
439 gboolean negative = (value < 0);
447 /* the following is unnecessary if the
448 * implementation of >>= uses an arithmetic rather
449 * than logical shift for a signed left operand
453 value |= - (1 <<(size - 7));
454 /* sign bit of byte is second high order bit (0x40) */
455 if ((value == 0 && !(byte & 0x40)) ||
456 (value == -1 && (byte & 0x40)))
466 /* ARCHITECTURE SPECIFIC CODE */
468 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
469 #define EMIT_DWARF_INFO 1
472 #if defined(TARGET_ARM)
473 #define AOT_FUNC_ALIGNMENT 4
475 #define AOT_FUNC_ALIGNMENT 16
477 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
478 #undef AOT_FUNC_ALIGNMENT
479 #define AOT_FUNC_ALIGNMENT 32
482 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
483 #define PPC_LD_OP "ld"
484 #define PPC_LDX_OP "ldx"
486 #define PPC_LD_OP "lwz"
487 #define PPC_LDX_OP "lwzx"
491 arch_init (MonoAotCompile *acfg)
493 acfg->llc_args = g_string_new ("");
494 acfg->as_args = g_string_new ("");
497 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
498 g_string_append (acfg->llc_args, "-mattr=+v6");
499 acfg->llvm_label_prefix = "_";
502 g_string_append (acfg->llc_args, " -mattr=+vfp2,+d16");
503 g_string_append (acfg->as_args, " -mfpu=vfp3");
505 g_string_append (acfg->llc_args, " -soft-float");
509 if (acfg->aot_opts.mtriple)
510 mono_arch_set_target (acfg->aot_opts.mtriple);
515 * arch_emit_direct_call:
517 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
521 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
523 #if defined(TARGET_X86) || defined(TARGET_AMD64)
524 /* Need to make sure this is exactly 5 bytes long */
525 emit_byte (acfg, '\xe8');
526 emit_symbol_diff (acfg, target, ".", -4);
528 #elif defined(TARGET_ARM)
529 if (acfg->use_bin_writer) {
536 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
537 emit_bytes (acfg, buf, 4);
539 img_writer_emit_unset_mode (acfg->w);
540 fprintf (acfg->fp, "bl %s\n", target);
543 #elif defined(TARGET_POWERPC)
544 if (acfg->use_bin_writer) {
545 g_assert_not_reached ();
547 img_writer_emit_unset_mode (acfg->w);
548 fprintf (acfg->fp, "bl %s\n", target);
552 g_assert_not_reached ();
558 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
560 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
561 * in in the 2. slot of every GOT, and require every method to place the GOT
562 * address in r30, even when it doesn't access the GOT otherwise. This way,
563 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
568 * PPC64 uses function descriptors which greatly complicate all code, since
569 * these are used very inconsistently in the runtime. Some functions like
570 * mono_compile_method () return ftn descriptors, while others like the
571 * trampoline creation functions do not.
572 * We assume that all GOT slots contain function descriptors, and create
573 * descriptors in aot-runtime.c when needed.
574 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
575 * from function descriptors, we could do the same, but it would require
576 * rewriting all the ppc/aot code to handle function descriptors properly.
577 * So instead, we use the same approach as on PPC32.
578 * This is a horrible mess, but fixing it would probably lead to an even bigger
584 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
587 #ifdef MONO_ARCH_AOT_SUPPORTED
589 * arch_emit_got_offset:
591 * The memory pointed to by CODE should hold native code for computing the GOT
592 * address. Emit this code while patching it with the offset between code and
593 * the GOT. CODE_SIZE is set to the number of bytes emitted.
596 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
598 #if defined(TARGET_POWERPC64)
599 g_assert (!acfg->use_bin_writer);
600 img_writer_emit_unset_mode (acfg->w);
602 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
603 * unsupported relocations. So we store the got address into the .Lgot_addr
604 * symbol which is in the text segment, compute its address, and load it.
606 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
607 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
608 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
609 fprintf (acfg->fp, "add 30, 30, 0\n");
610 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
611 acfg->label_generator ++;
613 #elif defined(TARGET_POWERPC)
614 g_assert (!acfg->use_bin_writer);
615 img_writer_emit_unset_mode (acfg->w);
616 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
617 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
618 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
619 acfg->label_generator ++;
622 guint32 offset = mono_arch_get_patch_offset (code);
623 emit_bytes (acfg, code, offset);
624 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
626 *code_size = offset + 4;
631 * arch_emit_got_access:
633 * The memory pointed to by CODE should hold native code for loading a GOT
634 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
635 * CODE_SIZE is set to the number of bytes emitted.
638 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
640 /* Emit beginning of instruction */
641 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
643 /* Emit the offset */
645 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
646 *code_size = mono_arch_get_patch_offset (code) + 4;
647 #elif defined(TARGET_X86)
648 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
649 *code_size = mono_arch_get_patch_offset (code) + 4;
650 #elif defined(TARGET_ARM)
651 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
652 *code_size = mono_arch_get_patch_offset (code) + 4;
653 #elif defined(TARGET_POWERPC)
659 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
660 g_assert (code - buf == 8);
661 emit_bytes (acfg, buf, code - buf);
662 *code_size = code - buf;
665 g_assert_not_reached ();
672 * arch_emit_plt_entry:
674 * Emit code for the PLT entry with index INDEX.
677 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
679 #if defined(TARGET_X86)
680 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
681 #if defined(__default_codegen__)
682 /* jmp *<offset>(%ebx) */
683 emit_byte (acfg, 0xff);
684 emit_byte (acfg, 0xa3);
685 emit_int32 (acfg, offset);
686 /* Used by mono_aot_get_plt_info_offset */
687 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
688 #elif defined(__native_client_codegen__)
689 const guint8 kSizeOfNaClJmp = 11;
690 guint8 bytes[kSizeOfNaClJmp];
691 guint8 *pbytes = &bytes[0];
693 x86_jump_membase32 (pbytes, X86_EBX, offset);
694 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
695 /* four bytes of data, used by mono_arch_patch_plt_entry */
696 /* For Native Client, make this work with data embedded in push. */
697 emit_byte (acfg, 0x68); /* hide data in a push */
698 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
699 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
700 #endif /*__native_client_codegen__*/
701 #elif defined(TARGET_AMD64)
702 #if defined(__default_codegen__)
704 * We can't emit jumps because they are 32 bits only so they can't be patched.
705 * So we make indirect calls through GOT entries which are patched by the AOT
706 * loader to point to .Lpd entries.
708 /* jmpq *<offset>(%rip) */
709 emit_byte (acfg, '\xff');
710 emit_byte (acfg, '\x25');
711 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
712 /* Used by mono_aot_get_plt_info_offset */
713 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
714 #elif defined(__native_client_codegen__)
716 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
717 guint8 *code = buf_aligned;
719 /* mov <OFFSET>(%rip), %r11d */
720 emit_byte (acfg, '\x45');
721 emit_byte (acfg, '\x8b');
722 emit_byte (acfg, '\x1d');
723 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
725 amd64_jump_reg (code, AMD64_R11);
726 /* This should be constant for the plt patch */
727 g_assert ((size_t)(code-buf_aligned) == 10);
728 emit_bytes (acfg, buf_aligned, code - buf_aligned);
730 /* Hide data in a push imm32 so it passes validation */
731 emit_byte (acfg, 0x68); /* push */
732 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
733 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
734 #endif /*__native_client_codegen__*/
735 #elif defined(TARGET_ARM)
740 * - optimize OP_AOTCONST implementation
741 * - optimize the PLT entries
742 * - optimize SWITCH AOT implementation
745 if (acfg->use_bin_writer && FALSE) {
746 /* FIXME: mono_arch_patch_plt_entry () needs to decode this */
747 /* We only emit 1 relocation since we implement it ourselves anyway */
748 img_writer_emit_reloc (acfg->w, R_ARM_ALU_PC_G0_NC, acfg->got_symbol, ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 8);
749 /* FIXME: A 2 instruction encoding is sufficient in most cases */
750 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_PC, 0, 0);
751 ARM_ADD_REG_IMM (code, ARMREG_IP, ARMREG_IP, 0, 0);
752 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, 0);
753 emit_bytes (acfg, buf, code - buf);
754 /* Used by mono_aot_get_plt_info_offset */
755 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
757 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
758 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
759 emit_bytes (acfg, buf, code - buf);
760 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
761 /* Used by mono_aot_get_plt_info_offset */
762 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
765 * The plt_got_info_offset is computed automatically by
766 * mono_aot_get_plt_info_offset (), so no need to save it here.
768 #elif defined(TARGET_POWERPC)
769 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
771 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
772 g_assert (!acfg->use_bin_writer);
773 img_writer_emit_unset_mode (acfg->w);
774 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
775 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
776 fprintf (acfg->fp, "add 11, 11, 30\n");
777 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
778 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
779 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
780 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
782 fprintf (acfg->fp, "mtctr 11\n");
783 fprintf (acfg->fp, "bctr\n");
784 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
786 g_assert_not_reached ();
791 * arch_emit_specific_trampoline:
793 * Emit code for a specific trampoline. OFFSET is the offset of the first of
794 * two GOT slots which contain the generic trampoline address and the trampoline
795 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
798 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
801 * The trampolines created here are variations of the specific
802 * trampolines created in mono_arch_create_specific_trampoline (). The
804 * - the generic trampoline address is taken from a got slot.
805 * - the offset of the got slot where the trampoline argument is stored
806 * is embedded in the instruction stream, and the generic trampoline
807 * can load the argument by loading the offset, adding it to the
808 * address of the trampoline to get the address of the got slot, and
809 * loading the argument from there.
810 * - all the trampolines should be of the same length.
812 #if defined(TARGET_AMD64)
813 #if defined(__default_codegen__)
814 /* This should be exactly 16 bytes long */
816 /* call *<offset>(%rip) */
817 emit_byte (acfg, '\x41');
818 emit_byte (acfg, '\xff');
819 emit_byte (acfg, '\x15');
820 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
821 /* This should be relative to the start of the trampoline */
822 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
823 emit_zero_bytes (acfg, 5);
824 #elif defined(__native_client_codegen__)
826 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
827 guint8 *code = buf_aligned;
832 /* Emit this call in 'code' so we can find out how long it is. */
833 amd64_call_reg (code, AMD64_R11);
834 call_start = mono_arch_nacl_skip_nops (buf_aligned);
835 call_len = code - call_start;
837 /* The tramp_size is twice the NaCl alignment because it starts with */
838 /* a call which needs to be aligned to the end of the boundary. */
839 *tramp_size = kNaClAlignment*2;
841 /* Emit nops to align call site below which is 7 bytes plus */
842 /* the length of the call sequence emitted above. */
843 /* Note: this requires the specific trampoline starts on a */
844 /* kNaclAlignedment aligned address, which it does because */
845 /* it's its own function that is aligned. */
847 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
848 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
849 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
851 /* The trampoline is stored at the offset'th pointer, the -4 is */
852 /* present because RIP relative addressing starts at the end of */
853 /* the current instruction, while the label "." is relative to */
854 /* the beginning of the current asm location, which in this case */
855 /* is not the mov instruction, but the offset itself, due to the */
856 /* way the bytes and ints are emitted here. */
857 got_offset = (offset * sizeof(gpointer)) - 4;
859 /* mov <OFFSET>(%rip), %r11d */
860 emit_byte (acfg, '\x45');
861 emit_byte (acfg, '\x8b');
862 emit_byte (acfg, '\x1d');
863 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
866 emit_bytes (acfg, call_start, call_len);
868 /* The arg is stored at the offset+1 pointer, relative to beginning */
869 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
870 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
872 /* We can't emit this data directly, hide in a "push imm32" */
873 emit_byte (acfg, '\x68'); /* push */
874 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
875 emit_alignment (acfg, kNaClAlignment);
876 #endif /*__native_client_codegen__*/
877 #elif defined(TARGET_ARM)
881 /* This should be exactly 20 bytes long */
884 ARM_PUSH (code, 0x5fff);
885 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
886 /* Load the value from the GOT */
887 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
889 ARM_BLX_REG (code, ARMREG_R1);
891 g_assert (code - buf == 16);
894 emit_bytes (acfg, buf, code - buf);
896 * Only one offset is needed, since the second one would be equal to the
899 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
900 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
901 #elif defined(TARGET_POWERPC)
908 g_assert (!acfg->use_bin_writer);
911 * PPC has no ip relative addressing, so we need to compute the address
912 * of the mscorlib got. That is slow and complex, so instead, we store it
913 * in the second got slot of every aot image. The caller already computed
914 * the address of its got and placed it into r30.
916 img_writer_emit_unset_mode (acfg->w);
917 /* Load mscorlib got address */
918 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
919 /* Load generic trampoline address */
920 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
921 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
922 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
923 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
924 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
926 fprintf (acfg->fp, "mtctr 11\n");
927 /* Load trampoline argument */
928 /* On ppc, we pass it normally to the generic trampoline */
929 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
930 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
931 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
932 /* Branch to generic trampoline */
933 fprintf (acfg->fp, "bctr\n");
935 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
936 *tramp_size = 10 * 4;
940 #elif defined(TARGET_X86)
944 /* Similar to the PPC code above */
946 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
948 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
949 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
950 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
954 /* Load mscorlib got address */
955 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
956 /* Push trampoline argument */
957 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
958 /* Load generic trampoline address */
959 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
960 /* Branch to generic trampoline */
961 x86_jump_reg (code, X86_ECX);
963 #ifdef __native_client_codegen__
965 /* emit nops to next 32 byte alignment */
966 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
967 while (code < (buf + a)) x86_nop(code);
970 emit_bytes (acfg, buf, code - buf);
972 *tramp_size = NACL_SIZE(17, kNaClAlignment);
973 g_assert (code - buf == *tramp_size);
975 g_assert_not_reached ();
980 * arch_emit_unbox_trampoline:
982 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
983 * CALL_TARGET is the symbol pointing to the native code of METHOD.
986 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoMethod *method, const char *call_target)
988 #if defined(TARGET_AMD64)
993 this_reg = mono_arch_get_this_arg_reg (NULL);
995 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
997 emit_bytes (acfg, buf, code - buf);
999 emit_byte (acfg, '\xe9');
1000 emit_symbol_diff (acfg, call_target, ".", -4);
1001 #elif defined(TARGET_X86)
1008 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1010 emit_bytes (acfg, buf, code - buf);
1013 emit_byte (acfg, '\xe9');
1014 emit_symbol_diff (acfg, call_target, ".", -4);
1015 #elif defined(TARGET_ARM)
1021 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1023 emit_bytes (acfg, buf, code - buf);
1024 /* jump to method */
1025 if (acfg->use_bin_writer) {
1032 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1033 emit_bytes (acfg, buf, 4);
1035 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1037 #elif defined(TARGET_POWERPC)
1040 g_assert (!acfg->use_bin_writer);
1042 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1043 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1045 g_assert_not_reached ();
1050 * arch_emit_static_rgctx_trampoline:
1052 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1053 * two GOT slots which contain the rgctx argument, and the method to jump to.
1054 * TRAMP_SIZE is set to the size of the emitted trampoline.
1055 * These kinds of trampolines cannot be enumerated statically, since there could
1056 * be one trampoline per method instantiation, so we emit the same code for all
1057 * trampolines, and parameterize them using two GOT slots.
1060 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1062 #if defined(TARGET_AMD64)
1063 #if defined(__default_codegen__)
1064 /* This should be exactly 13 bytes long */
1067 /* mov <OFFSET>(%rip), %r10 */
1068 emit_byte (acfg, '\x4d');
1069 emit_byte (acfg, '\x8b');
1070 emit_byte (acfg, '\x15');
1071 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1073 /* jmp *<offset>(%rip) */
1074 emit_byte (acfg, '\xff');
1075 emit_byte (acfg, '\x25');
1076 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1077 #elif defined(__native_client_codegen__)
1079 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1080 guint8 *code = buf_aligned;
1082 /* mov <OFFSET>(%rip), %r10d */
1083 emit_byte (acfg, '\x45');
1084 emit_byte (acfg, '\x8b');
1085 emit_byte (acfg, '\x15');
1086 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1088 /* mov <OFFSET>(%rip), %r11d */
1089 emit_byte (acfg, '\x45');
1090 emit_byte (acfg, '\x8b');
1091 emit_byte (acfg, '\x1d');
1092 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1095 amd64_jump_reg (code, AMD64_R11);
1096 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1098 emit_alignment (acfg, kNaClAlignment);
1099 *tramp_size = kNaClAlignment;
1100 #endif /*__native_client_codegen__*/
1102 #elif defined(TARGET_ARM)
1106 /* This should be exactly 24 bytes long */
1109 /* Load rgctx value */
1110 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1111 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1112 /* Load branch addr + branch */
1113 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1114 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1116 g_assert (code - buf == 16);
1119 emit_bytes (acfg, buf, code - buf);
1120 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1121 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1122 #elif defined(TARGET_POWERPC)
1129 g_assert (!acfg->use_bin_writer);
1132 * PPC has no ip relative addressing, so we need to compute the address
1133 * of the mscorlib got. That is slow and complex, so instead, we store it
1134 * in the second got slot of every aot image. The caller already computed
1135 * the address of its got and placed it into r30.
1137 img_writer_emit_unset_mode (acfg->w);
1138 /* Load mscorlib got address */
1139 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1141 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1142 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1143 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1144 /* Load target address */
1145 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1146 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1147 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1148 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1149 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1150 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1152 fprintf (acfg->fp, "mtctr 11\n");
1153 /* Branch to the target address */
1154 fprintf (acfg->fp, "bctr\n");
1156 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1157 *tramp_size = 11 * 4;
1159 *tramp_size = 9 * 4;
1162 #elif defined(TARGET_X86)
1166 /* Similar to the PPC code above */
1168 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1171 /* Load mscorlib got address */
1172 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1174 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1175 /* Branch to the target address */
1176 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1178 #ifdef __native_client_codegen__
1180 /* emit nops to next 32 byte alignment */
1181 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1182 while (code < (buf + a)) x86_nop(code);
1186 emit_bytes (acfg, buf, code - buf);
1188 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1189 g_assert (code - buf == *tramp_size);
1191 g_assert_not_reached ();
1196 * arch_emit_imt_thunk:
1198 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1199 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1200 * key is the IMT key, and ptr holds the address of a memory location holding
1201 * the address to branch to if the IMT arg matches the key. The array is
1202 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1204 * TRAMP_SIZE is set to the size of the emitted trampoline.
1207 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1209 #if defined(TARGET_AMD64)
1211 #if defined(__native_client_codegen__)
1216 guint8 *mov_buf_ptr = mov_buf;
1218 const int kSizeOfMove = 7;
1219 #if defined(__default_codegen__)
1220 code = buf = g_malloc (256);
1221 #elif defined(__native_client_codegen__)
1222 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1223 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1224 /* The RIP relative move below is emitted first */
1229 /* FIXME: Optimize this, i.e. use binary search etc. */
1230 /* Maybe move the body into a separate function (slower, but much smaller) */
1232 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1235 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1237 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1240 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1242 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1245 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1246 amd64_jump_code (code, labels [0]);
1249 mono_amd64_patch (labels [2], code);
1250 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1251 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1255 mono_amd64_patch (labels [1], code);
1256 x86_breakpoint (code);
1258 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1259 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1260 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1261 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1262 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1263 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1265 emit_bytes (acfg, buf, code - buf);
1267 *tramp_size = code - buf + kSizeOfMove;
1268 #if defined(__native_client_codegen__)
1269 /* The tramp will be padded to the next kNaClAlignment bundle. */
1270 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1273 #if defined(__default_codegen__)
1275 #elif defined(__native_client_codegen__)
1279 #elif defined(TARGET_X86)
1281 #ifdef __native_client_codegen__
1286 #if defined(__default_codegen__)
1287 code = buf = g_malloc (256);
1288 #elif defined(__native_client_codegen__)
1289 buf_alloc = g_malloc (256 + kNaClAlignment);
1290 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1293 /* Allocate a temporary stack slot */
1294 x86_push_reg (code, X86_EAX);
1296 x86_push_reg (code, X86_EAX);
1298 /* Load mscorlib got address */
1299 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1301 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1304 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1306 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1309 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1311 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1314 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1315 x86_jump_code (code, labels [0]);
1318 mono_x86_patch (labels [2], code);
1319 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1320 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1321 /* Save the target address to the temporary stack location */
1322 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1324 x86_pop_reg (code, X86_EAX);
1325 /* Jump to the target address */
1330 mono_x86_patch (labels [1], code);
1331 x86_breakpoint (code);
1333 #ifdef __native_client_codegen__
1335 /* emit nops to next 32 byte alignment */
1336 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1337 while (code < (buf + a)) x86_nop(code);
1340 emit_bytes (acfg, buf, code - buf);
1342 *tramp_size = code - buf;
1344 #if defined(__default_codegen__)
1346 #elif defined(__native_client_codegen__)
1350 #elif defined(TARGET_ARM)
1352 guint8 *code, *code2, *labels [16];
1356 /* The IMT method is in v5 */
1358 /* Need at least two free registers, plus a slot for storing the pc */
1359 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1361 /* Load the parameter from the GOT */
1362 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1363 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1366 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1367 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1369 ARM_B_COND (code, ARMCOND_EQ, 0);
1371 /* End-of-loop check */
1372 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1374 ARM_B_COND (code, ARMCOND_EQ, 0);
1377 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1380 arm_patch (labels [4], labels [1]);
1383 arm_patch (labels [2], code);
1384 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1385 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1386 /* Save it to the third stack slot */
1387 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1388 /* Restore the registers and branch */
1389 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1392 arm_patch (labels [3], code);
1397 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1399 emit_bytes (acfg, buf, code - buf);
1400 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1402 *tramp_size = code - buf + 4;
1403 #elif defined(TARGET_POWERPC)
1405 guint8 *code, *labels [16];
1409 /* Load the mscorlib got address */
1410 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1411 /* Load the parameter from the GOT */
1412 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1413 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1415 /* Load and check key */
1417 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1418 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1420 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1422 /* End-of-loop check */
1423 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1425 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1428 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1431 mono_ppc_patch (labels [4], labels [1]);
1434 mono_ppc_patch (labels [2], code);
1435 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1436 /* r11 now contains the value of the vtable slot */
1437 /* this is not a function descriptor on ppc64 */
1438 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1439 ppc_mtctr (code, ppc_r11);
1440 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1443 mono_ppc_patch (labels [3], code);
1447 *tramp_size = code - buf;
1449 emit_bytes (acfg, buf, code - buf);
1451 g_assert_not_reached ();
1456 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1458 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1459 /* Based on code generated by gcc */
1460 img_writer_emit_unset_mode (acfg->w);
1463 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1464 ".section .ctors,\"aw\",@progbits\n"
1468 ".section .opd,\"aw\"\n"
1471 ".long .%s,.TOC.@tocbase32\n"
1474 ".type .%s,@function\n"
1476 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1478 ".section .ctors,\"aw\",@progbits\n"
1482 ".section .opd,\"aw\"\n"
1485 ".long .%1$s,.TOC.@tocbase32\n"
1486 ".size %1$s,.-%1$s\n"
1488 ".type .%1$s,@function\n"
1490 ".%1$s:\n", symbol);
1501 "lis 3, .Lglobals@h\n"
1502 "ori 3, 3, .Lglobals@l\n"
1503 "bl .mono_aot_register_module\n"
1511 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1513 ".size .%s,.-.%s\n", symbol, symbol);
1516 ".size .%1$s,.-.%1$s\n", symbol);
1522 /* END OF ARCH SPECIFIC CODE */
1525 mono_get_field_token (MonoClassField *field)
1527 MonoClass *klass = field->parent;
1530 for (i = 0; i < klass->field.count; ++i) {
1531 if (field == &klass->fields [i])
1532 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1535 g_assert_not_reached ();
1540 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1544 //printf ("ENCODE: %d 0x%x.\n", value, value);
1547 * Same encoding as the one used in the metadata, extended to handle values
1548 * greater than 0x1fffffff.
1550 if ((value >= 0) && (value <= 127))
1552 else if ((value >= 0) && (value <= 16383)) {
1553 p [0] = 0x80 | (value >> 8);
1554 p [1] = value & 0xff;
1556 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1557 p [0] = (value >> 24) | 0xc0;
1558 p [1] = (value >> 16) & 0xff;
1559 p [2] = (value >> 8) & 0xff;
1560 p [3] = value & 0xff;
1565 p [1] = (value >> 24) & 0xff;
1566 p [2] = (value >> 16) & 0xff;
1567 p [3] = (value >> 8) & 0xff;
1568 p [4] = value & 0xff;
1576 stream_init (MonoDynamicStream *sh)
1579 sh->alloc_size = 4096;
1580 sh->data = g_malloc (4096);
1582 /* So offsets are > 0 */
1588 make_room_in_stream (MonoDynamicStream *stream, int size)
1590 if (size <= stream->alloc_size)
1593 while (stream->alloc_size <= size) {
1594 if (stream->alloc_size < 4096)
1595 stream->alloc_size = 4096;
1597 stream->alloc_size *= 2;
1600 stream->data = g_realloc (stream->data, stream->alloc_size);
1604 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1608 make_room_in_stream (stream, stream->index + len);
1609 memcpy (stream->data + stream->index, data, len);
1610 idx = stream->index;
1611 stream->index += len;
1618 * Add data to the binary blob inside the aot image. Returns the offset inside the
1619 * blob where the data was stored.
1622 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1624 if (acfg->blob.alloc_size == 0)
1625 stream_init (&acfg->blob);
1627 return add_stream_data (&acfg->blob, (char*)data, data_len);
1631 * emit_offset_table:
1633 * Emit a table of increasing offsets in a compact form using differential encoding.
1634 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1635 * group size, the more compact the table becomes, but the slower it becomes to compute
1636 * a given entry. Returns the size of the table.
1639 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1641 gint32 current_offset;
1642 int i, buf_size, ngroups, index_entry_size;
1644 guint32 *index_offsets;
1646 ngroups = (noffsets + (group_size - 1)) / group_size;
1648 index_offsets = g_new0 (guint32, ngroups);
1650 buf_size = noffsets * 4;
1651 p = buf = g_malloc0 (buf_size);
1654 for (i = 0; i < noffsets; ++i) {
1655 //printf ("D: %d -> %d\n", i, offsets [i]);
1656 if ((i % group_size) == 0) {
1657 index_offsets [i / group_size] = p - buf;
1658 /* Emit the full value for these entries */
1659 encode_value (offsets [i], p, &p);
1661 /* The offsets are allowed to be non-increasing */
1662 //g_assert (offsets [i] >= current_offset);
1663 encode_value (offsets [i] - current_offset, p, &p);
1665 current_offset = offsets [i];
1668 if (ngroups && index_offsets [ngroups - 1] < 65000)
1669 index_entry_size = 2;
1671 index_entry_size = 4;
1673 /* Emit the header */
1674 emit_int32 (acfg, noffsets);
1675 emit_int32 (acfg, group_size);
1676 emit_int32 (acfg, ngroups);
1677 emit_int32 (acfg, index_entry_size);
1679 /* Emit the index */
1680 for (i = 0; i < ngroups; ++i) {
1681 if (index_entry_size == 2)
1682 emit_int16 (acfg, index_offsets [i]);
1684 emit_int32 (acfg, index_offsets [i]);
1688 emit_bytes (acfg, buf, p - buf);
1690 return (int)(p - buf) + (ngroups * 4);
1694 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1698 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1702 index = g_hash_table_size (cfg->image_hash);
1703 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1704 g_ptr_array_add (cfg->image_table, image);
1710 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1713 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
1715 /* FIXME: Search referenced images as well */
1716 if (!acfg->typespec_classes) {
1717 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
1718 for (i = 0; i < len; ++i) {
1719 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1722 for (i = 0; i < len; ++i) {
1723 if (acfg->typespec_classes [i] == klass)
1728 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1734 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1739 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1740 * standard metadata encoding.
1743 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1747 if (klass->generic_class) {
1749 g_assert (klass->type_token);
1751 /* Find a typespec for a class if possible */
1752 token = find_typespec_for_class (acfg, klass);
1754 encode_value (token, p, &p);
1755 encode_value (get_image_index (acfg, acfg->image), p, &p);
1757 MonoClass *gclass = klass->generic_class->container_class;
1758 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1761 /* Encode it ourselves */
1763 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1764 encode_value (MONO_TYPE_GENERICINST, p, &p);
1765 encode_klass_ref (acfg, gclass, p, &p);
1766 encode_value (inst->type_argc, p, &p);
1767 for (i = 0; i < inst->type_argc; ++i)
1768 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1770 } else if (klass->type_token) {
1771 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1772 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1773 encode_value (get_image_index (acfg, klass->image), p, &p);
1774 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1775 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1776 g_assert (container);
1779 encode_value (MONO_TOKEN_TYPE_SPEC, p, &p);
1780 encode_value (klass->byval_arg.type, p, &p);
1782 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1784 encode_value (container->is_method, p, &p);
1785 if (container->is_method)
1786 encode_method_ref (acfg, container->owner.method, p, &p);
1788 encode_klass_ref (acfg, container->owner.klass, p, &p);
1791 g_assert (klass->rank > 0);
1792 encode_value (MONO_TOKEN_TYPE_DEF, p, &p);
1793 encode_value (get_image_index (acfg, klass->image), p, &p);
1794 encode_value (klass->rank, p, &p);
1795 encode_klass_ref (acfg, klass->element_class, p, &p);
1801 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
1803 guint32 token = mono_get_field_token (field);
1806 encode_klass_ref (cfg, field->parent, p, &p);
1807 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
1808 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
1813 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
1817 MonoGenericInst *inst;
1819 /* Encode the context */
1820 inst = context->class_inst;
1821 encode_value (inst ? 1 : 0, p, &p);
1823 encode_value (inst->type_argc, p, &p);
1824 for (i = 0; i < inst->type_argc; ++i)
1825 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1827 inst = context->method_inst;
1828 encode_value (inst ? 1 : 0, p, &p);
1830 encode_value (inst->type_argc, p, &p);
1831 for (i = 0; i < inst->type_argc; ++i)
1832 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
1838 #define MAX_IMAGE_INDEX 250
1841 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
1843 guint32 image_index = get_image_index (acfg, method->klass->image);
1844 guint32 token = method->token;
1845 MonoJumpInfoToken *ji;
1850 * The encoding for most methods is as follows:
1851 * - image index encoded as a leb128
1852 * - token index encoded as a leb128
1853 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
1854 * types of method encodings.
1857 g_assert (image_index < MONO_AOT_METHODREF_MIN);
1859 /* Mark methods which can't use aot trampolines because they need the further
1860 * processing in mono_magic_trampoline () which requires a MonoMethod*.
1862 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
1863 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
1864 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
1867 * Some wrapper methods are shared using their signature, encode their
1868 * stringified signature instead.
1869 * FIXME: Optimize disk usage
1872 if (method->wrapper_type) {
1873 if (method->wrapper_type == MONO_WRAPPER_RUNTIME_INVOKE) {
1874 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1875 if (strcmp (method->name, "runtime_invoke_dynamic")) {
1876 name = mono_aot_wrapper_name (method);
1877 } else if (mono_marshal_method_from_wrapper (method) != method) {
1878 /* Direct wrapper, encode it normally */
1880 name = g_strdup_printf ("(wrapper runtime-invoke):%s (%s)", method->name, tmpsig);
1883 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_INVOKE) {
1884 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1885 name = g_strdup_printf ("(wrapper delegate-invoke):%s (%s)", method->name, tmpsig);
1887 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_BEGIN_INVOKE) {
1888 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1889 name = g_strdup_printf ("(wrapper delegate-begin-invoke):%s (%s)", method->name, tmpsig);
1891 } else if (method->wrapper_type == MONO_WRAPPER_DELEGATE_END_INVOKE) {
1892 char *tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
1893 name = g_strdup_printf ("(wrapper delegate-end-invoke):%s (%s)", method->name, tmpsig);
1899 encode_value ((MONO_AOT_METHODREF_WRAPPER_NAME << 24), p, &p);
1900 strcpy ((char*)p, name);
1901 p += strlen (name) + 1;
1903 } else if (method->wrapper_type) {
1904 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
1906 encode_value (method->wrapper_type, p, &p);
1908 switch (method->wrapper_type) {
1909 case MONO_WRAPPER_REMOTING_INVOKE:
1910 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
1911 case MONO_WRAPPER_XDOMAIN_INVOKE: {
1914 m = mono_marshal_method_from_wrapper (method);
1916 encode_method_ref (acfg, m, p, &p);
1919 case MONO_WRAPPER_PROXY_ISINST:
1920 case MONO_WRAPPER_LDFLD:
1921 case MONO_WRAPPER_LDFLDA:
1922 case MONO_WRAPPER_STFLD:
1923 case MONO_WRAPPER_ISINST: {
1924 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
1925 encode_klass_ref (acfg, proxy_class, p, &p);
1928 case MONO_WRAPPER_LDFLD_REMOTE:
1929 case MONO_WRAPPER_STFLD_REMOTE:
1931 case MONO_WRAPPER_ALLOC: {
1932 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1934 /* The GC name is saved once in MonoAotFileInfo */
1935 g_assert (info->alloc_type != -1);
1936 encode_value (info->alloc_type, p, &p);
1939 case MONO_WRAPPER_WRITE_BARRIER:
1941 case MONO_WRAPPER_STELEMREF: {
1942 MonoClass *klass = mono_marshal_get_wrapper_info (method);
1944 /* Make sure this is the 'normal' stelemref wrapper, not the virtual one */
1948 case MONO_WRAPPER_UNKNOWN:
1949 if (strcmp (method->name, "FastMonitorEnter") == 0)
1950 encode_value (MONO_AOT_WRAPPER_MONO_ENTER, p, &p);
1951 else if (strcmp (method->name, "FastMonitorExit") == 0)
1952 encode_value (MONO_AOT_WRAPPER_MONO_EXIT, p, &p);
1954 g_assert_not_reached ();
1956 case MONO_WRAPPER_SYNCHRONIZED:
1957 case MONO_WRAPPER_MANAGED_TO_NATIVE:
1958 case MONO_WRAPPER_RUNTIME_INVOKE: {
1961 m = mono_marshal_method_from_wrapper (method);
1963 g_assert (m != method);
1964 encode_method_ref (acfg, m, p, &p);
1967 case MONO_WRAPPER_MANAGED_TO_MANAGED:
1968 if (!strcmp (method->name, "ElementAddr")) {
1969 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
1972 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
1973 encode_value (info->rank, p, &p);
1974 encode_value (info->elem_size, p, &p);
1976 g_assert_not_reached ();
1980 g_assert_not_reached ();
1982 } else if (mono_method_signature (method)->is_inflated) {
1984 * This is a generic method, find the original token which referenced it and
1986 * Obtain the token from information recorded by the JIT.
1988 ji = g_hash_table_lookup (acfg->token_info_hash, method);
1990 image_index = get_image_index (acfg, ji->image);
1991 g_assert (image_index < MAX_IMAGE_INDEX);
1994 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
1995 encode_value (image_index, p, &p);
1996 encode_value (token, p, &p);
1998 MonoMethod *declaring;
1999 MonoGenericContext *context = mono_method_get_context (method);
2001 g_assert (method->is_inflated);
2002 declaring = ((MonoMethodInflated*)method)->declaring;
2005 * This might be a non-generic method of a generic instance, which
2006 * doesn't have a token since the reference is generated by the JIT
2007 * like Nullable:Box/Unbox, or by generic sharing.
2010 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2011 /* Encode the klass */
2012 encode_klass_ref (acfg, method->klass, p, &p);
2013 /* Encode the method */
2014 image_index = get_image_index (acfg, method->klass->image);
2015 g_assert (image_index < MAX_IMAGE_INDEX);
2016 g_assert (declaring->token);
2017 token = declaring->token;
2018 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2019 encode_value (image_index, p, &p);
2020 encode_value (token, p, &p);
2021 encode_generic_context (acfg, context, p, &p);
2023 } else if (token == 0) {
2024 /* This might be a method of a constructed type like int[,].Set */
2025 /* Obtain the token from information recorded by the JIT */
2026 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2028 image_index = get_image_index (acfg, ji->image);
2029 g_assert (image_index < MAX_IMAGE_INDEX);
2032 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2033 encode_value (image_index, p, &p);
2034 encode_value (token, p, &p);
2037 g_assert (method->klass->rank);
2039 /* Encode directly */
2040 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2041 encode_klass_ref (acfg, method->klass, p, &p);
2042 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2043 encode_value (0, p, &p);
2044 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2045 encode_value (1, p, &p);
2046 else if (!strcmp (method->name, "Get"))
2047 encode_value (2, p, &p);
2048 else if (!strcmp (method->name, "Address"))
2049 encode_value (3, p, &p);
2050 else if (!strcmp (method->name, "Set"))
2051 encode_value (4, p, &p);
2053 g_assert_not_reached ();
2056 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2057 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2063 compare_patches (gconstpointer a, gconstpointer b)
2067 i = (*(MonoJumpInfo**)a)->ip.i;
2068 j = (*(MonoJumpInfo**)b)->ip.i;
2079 static G_GNUC_UNUSED char*
2080 patch_to_string (MonoJumpInfo *patch_info)
2084 str = g_string_new ("");
2086 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2088 switch (patch_info->type) {
2089 case MONO_PATCH_INFO_VTABLE:
2090 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2095 g_string_append_printf (str, ")");
2096 return g_string_free (str, FALSE);
2102 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2105 static inline gboolean
2106 is_plt_patch (MonoJumpInfo *patch_info)
2108 switch (patch_info->type) {
2109 case MONO_PATCH_INFO_METHOD:
2110 case MONO_PATCH_INFO_INTERNAL_METHOD:
2111 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2112 case MONO_PATCH_INFO_ICALL_ADDR:
2113 case MONO_PATCH_INFO_CLASS_INIT:
2114 case MONO_PATCH_INFO_RGCTX_FETCH:
2115 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2116 case MONO_PATCH_INFO_MONITOR_ENTER:
2117 case MONO_PATCH_INFO_MONITOR_EXIT:
2118 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2128 * Return the symbol identifying the plt entry PLT_OFFSET.
2131 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2135 * The Apple linker reorganizes object files, so it doesn't like branches to local
2136 * labels, since those have no relocations.
2138 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2140 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2147 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2149 static MonoPltEntry*
2150 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2154 if (!is_plt_patch (patch_info))
2157 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2159 // FIXME: This breaks the calculation of final_got_size
2160 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2162 * Allocate a separate PLT slot for each such patch, since some plt
2163 * entries will refer to the method itself, and some will refer to the
2170 MonoJumpInfo *new_ji;
2172 g_assert (!acfg->final_got_size);
2174 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2176 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2177 res->plt_offset = acfg->plt_offset;
2179 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2181 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2183 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2185 acfg->plt_offset ++;
2194 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2195 * JI could be found if it exists, otherwise allocates a new one.
2198 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2202 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2204 return got_offset - 1;
2206 got_offset = acfg->got_offset;
2207 acfg->got_offset ++;
2209 if (acfg->final_got_size)
2210 g_assert (got_offset < acfg->final_got_size);
2212 acfg->stats.got_slots ++;
2213 acfg->stats.got_slot_types [ji->type] ++;
2215 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2216 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2217 g_ptr_array_add (acfg->got_patches, ji);
2222 /* Add a method to the list of methods which need to be emitted */
2224 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2227 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2228 g_ptr_array_add (acfg->methods, method);
2229 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2230 acfg->nmethods = acfg->methods->len + 1;
2233 if (method->wrapper_type || extra)
2234 g_ptr_array_add (acfg->extra_methods, method);
2238 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2240 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2248 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2252 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2256 index = acfg->method_index;
2257 add_method_with_index (acfg, method, index, extra);
2259 /* FIXME: Fix quadratic behavior */
2260 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (index));
2262 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2264 acfg->method_index ++;
2270 add_method (MonoAotCompile *acfg, MonoMethod *method)
2272 return add_method_full (acfg, method, FALSE, 0);
2276 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2278 add_method_full (acfg, method, TRUE, 0);
2282 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2284 add_method_full (acfg, method, TRUE, depth);
2288 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2290 MonoAotCompile *acfg = user_data;
2291 MonoJitICallInfo *callinfo = value;
2292 MonoMethod *wrapper;
2298 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2299 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2302 add_method (acfg, wrapper);
2306 get_runtime_invoke_sig (MonoMethodSignature *sig)
2308 MonoMethodBuilder *mb;
2311 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2312 m = mono_mb_create_method (mb, sig, 16);
2313 return mono_marshal_get_runtime_invoke (m, FALSE);
2317 can_marshal_struct (MonoClass *klass)
2319 MonoClassField *field;
2320 gboolean can_marshal = TRUE;
2321 gpointer iter = NULL;
2323 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2326 /* Only allow a few field types to avoid asserts in the marshalling code */
2327 while ((field = mono_class_get_fields (klass, &iter))) {
2328 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2331 switch (field->type->type) {
2336 case MONO_TYPE_BOOLEAN:
2339 case MONO_TYPE_CHAR:
2347 case MONO_TYPE_STRING:
2349 case MONO_TYPE_VALUETYPE:
2350 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2351 can_marshal = FALSE;
2354 can_marshal = FALSE;
2360 /* Its hard to compute whenever these can be marshalled or not */
2361 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2368 add_wrappers (MonoAotCompile *acfg)
2370 MonoMethod *method, *m;
2372 MonoMethodSignature *sig, *csig;
2376 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2377 * so there is only one wrapper of a given type, or inlining their contents into their
2382 * FIXME: This depends on the fact that different wrappers have different
2386 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2388 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2389 gboolean skip = FALSE;
2391 method = mono_get_method (acfg->image, token, NULL);
2393 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2394 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2395 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2398 if (method->is_generic || method->klass->generic_container)
2401 /* Skip methods which can not be handled by get_runtime_invoke () */
2402 sig = mono_method_signature (method);
2405 if ((sig->ret->type == MONO_TYPE_PTR) ||
2406 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2409 for (j = 0; j < sig->param_count; j++) {
2410 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2414 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2415 if (!method->klass->contextbound) {
2416 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2417 gboolean has_nullable = FALSE;
2419 for (j = 0; j < sig->param_count; j++) {
2420 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2421 has_nullable = TRUE;
2424 if (info && !has_nullable) {
2425 /* Supported by the dynamic runtime-invoke wrapper */
2433 //printf ("%s\n", mono_method_full_name (method, TRUE));
2434 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2438 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2439 #ifdef MONO_ARCH_HAVE_TLS_GET
2440 MonoMethodDesc *desc;
2441 MonoMethod *orig_method;
2445 /* Runtime invoke wrappers */
2447 /* void runtime-invoke () [.cctor] */
2448 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2449 csig->ret = &mono_defaults.void_class->byval_arg;
2450 add_method (acfg, get_runtime_invoke_sig (csig));
2452 /* void runtime-invoke () [Finalize] */
2453 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2455 csig->ret = &mono_defaults.void_class->byval_arg;
2456 add_method (acfg, get_runtime_invoke_sig (csig));
2458 /* void runtime-invoke (string) [exception ctor] */
2459 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2461 csig->ret = &mono_defaults.void_class->byval_arg;
2462 csig->params [0] = &mono_defaults.string_class->byval_arg;
2463 add_method (acfg, get_runtime_invoke_sig (csig));
2465 /* void runtime-invoke (string, string) [exception ctor] */
2466 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2468 csig->ret = &mono_defaults.void_class->byval_arg;
2469 csig->params [0] = &mono_defaults.string_class->byval_arg;
2470 csig->params [1] = &mono_defaults.string_class->byval_arg;
2471 add_method (acfg, get_runtime_invoke_sig (csig));
2473 /* string runtime-invoke () [Exception.ToString ()] */
2474 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2476 csig->ret = &mono_defaults.string_class->byval_arg;
2477 add_method (acfg, get_runtime_invoke_sig (csig));
2479 /* void runtime-invoke (string, Exception) [exception ctor] */
2480 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2482 csig->ret = &mono_defaults.void_class->byval_arg;
2483 csig->params [0] = &mono_defaults.string_class->byval_arg;
2484 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2485 add_method (acfg, get_runtime_invoke_sig (csig));
2487 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2488 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2490 csig->ret = &(mono_class_from_name (
2491 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2492 csig->params [0] = &mono_defaults.string_class->byval_arg;
2493 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2494 add_method (acfg, get_runtime_invoke_sig (csig));
2496 /* runtime-invoke used by finalizers */
2497 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2499 /* This is used by mono_runtime_capture_context () */
2500 method = mono_get_context_capture_method ();
2502 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2504 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2505 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2508 /* JIT icall wrappers */
2509 /* FIXME: locking */
2510 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2513 add_method (acfg, mono_marshal_get_stelemref ());
2515 #ifdef MONO_ARCH_HAVE_TLS_GET
2516 /* Managed Allocators */
2517 nallocators = mono_gc_get_managed_allocator_types ();
2518 for (i = 0; i < nallocators; ++i) {
2519 m = mono_gc_get_managed_allocator_by_type (i);
2521 add_method (acfg, m);
2524 /* Monitor Enter/Exit */
2525 desc = mono_method_desc_new ("Monitor:Enter", FALSE);
2526 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2527 g_assert (orig_method);
2528 mono_method_desc_free (desc);
2529 method = mono_monitor_get_fast_path (orig_method);
2531 add_method (acfg, method);
2533 desc = mono_method_desc_new ("Monitor:Exit", FALSE);
2534 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2535 g_assert (orig_method);
2536 mono_method_desc_free (desc);
2537 method = mono_monitor_get_fast_path (orig_method);
2539 add_method (acfg, method);
2542 /* Stelemref wrappers */
2543 /* There is only a constant number of these, iterating over all types should handle them all */
2544 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2547 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2548 klass = mono_class_get (acfg->image, token);
2550 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2555 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2556 * we use the original method instead at runtime.
2557 * Since full-aot doesn't support remoting, this is not a problem.
2560 /* remoting-invoke wrappers */
2561 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2562 MonoMethodSignature *sig;
2564 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2565 method = mono_get_method (acfg->image, token, NULL);
2567 sig = mono_method_signature (method);
2569 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2570 m = mono_marshal_get_remoting_invoke_with_check (method);
2572 add_method (acfg, m);
2577 /* delegate-invoke wrappers */
2578 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2581 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2582 klass = mono_class_get (acfg->image, token);
2584 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2585 method = mono_get_delegate_invoke (klass);
2587 m = mono_marshal_get_delegate_invoke (method, NULL);
2589 add_method (acfg, m);
2591 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
2592 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
2594 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
2595 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
2599 /* Synchronized wrappers */
2600 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2601 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2602 method = mono_get_method (acfg->image, token, NULL);
2604 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
2605 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
2608 /* pinvoke wrappers */
2609 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2611 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2613 method = mono_get_method (acfg->image, token, NULL);
2615 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2616 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2617 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2621 /* native-to-managed wrappers */
2622 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2624 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2625 MonoCustomAttrInfo *cattr;
2628 method = mono_get_method (acfg->image, token, NULL);
2631 * Only generate native-to-managed wrappers for methods which have an
2632 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
2633 * name to avoid defining a new assembly to contain it.
2635 cattr = mono_custom_attrs_from_method (method);
2638 for (j = 0; j < cattr->num_attrs; ++j)
2639 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
2641 if (j < cattr->num_attrs) {
2642 MonoCustomAttrEntry *e = &cattr->attrs [j];
2643 MonoMethodSignature *sig = mono_method_signature (e->ctor);
2644 const char *p = (const char*)e->data;
2650 g_assert (method->flags & METHOD_ATTRIBUTE_STATIC);
2652 g_assert (sig->param_count == 1);
2653 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
2656 * Decode the cattr manually since we can't create objects
2657 * during aot compilation.
2663 /* From load_cattr_value () in reflection.c */
2664 slen = mono_metadata_decode_value (p, &p);
2665 n = g_memdup (p, slen + 1);
2667 t = mono_reflection_type_from_name (n, acfg->image);
2671 klass = mono_class_from_mono_type (t);
2672 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
2674 add_method (acfg, mono_marshal_get_managed_wrapper (method, klass, 0));
2678 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2679 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
2680 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
2684 /* StructureToPtr/PtrToStructure wrappers */
2685 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2688 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2689 klass = mono_class_get (acfg->image, token);
2691 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
2692 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
2693 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
2699 has_type_vars (MonoClass *klass)
2701 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
2704 return has_type_vars (klass->element_class);
2705 if (klass->generic_class) {
2706 MonoGenericContext *context = &klass->generic_class->context;
2707 if (context->class_inst) {
2710 for (i = 0; i < context->class_inst->type_argc; ++i)
2711 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
2719 method_has_type_vars (MonoMethod *method)
2721 if (has_type_vars (method->klass))
2724 if (method->is_inflated) {
2725 MonoGenericContext *context = mono_method_get_context (method);
2726 if (context->method_inst) {
2729 for (i = 0; i < context->method_inst->type_argc; ++i)
2730 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
2737 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth);
2740 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force)
2742 /* This might lead to a huge code blowup so only do it if neccesary */
2743 if (!acfg->aot_opts.full_aot && !force)
2746 add_generic_class_with_depth (acfg, klass, 0);
2750 * add_generic_class:
2752 * Add all methods of a generic class.
2755 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
2760 mono_class_init (klass);
2762 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
2765 if (has_type_vars (klass))
2768 if (!klass->generic_class && !klass->rank)
2772 while ((method = mono_class_get_methods (klass, &iter))) {
2773 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
2777 if (method->is_generic)
2782 * FIXME: Instances which are referenced by these methods are not added,
2783 * for example Array.Resize<int> for List<int>.Add ().
2785 add_extra_method_with_depth (acfg, method, depth);
2788 if (klass->delegate) {
2789 method = mono_get_delegate_invoke (klass);
2791 method = mono_marshal_get_delegate_invoke (method, NULL);
2793 add_method (acfg, method);
2797 * For ICollection<T>, add instances of the helper methods
2798 * in Array, since a T[] could be cast to ICollection<T>.
2800 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
2801 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
2802 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2803 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
2807 if (!strcmp (klass->name, "IEnumerator`1"))
2808 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
2810 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
2812 /* Add the T[]/InternalEnumerator class */
2813 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
2817 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
2818 if (!strcmp (nclass->name, "InternalEnumerator`1"))
2822 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
2823 add_generic_class (acfg, nclass, FALSE);
2827 while ((method = mono_class_get_methods (array_class, &iter))) {
2828 if (strstr (method->name, name_prefix)) {
2829 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
2830 add_extra_method_with_depth (acfg, m, depth);
2834 g_free (name_prefix);
2837 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
2838 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
2839 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2840 MonoClass *icomparable, *gcomparer;
2841 MonoGenericContext ctx;
2842 MonoType *args [16];
2844 memset (&ctx, 0, sizeof (ctx));
2846 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
2847 g_assert (icomparable);
2848 args [0] = &tclass->byval_arg;
2849 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2851 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
2852 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
2853 g_assert (gcomparer);
2854 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
2858 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
2859 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
2860 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
2861 MonoClass *iface, *gcomparer;
2862 MonoGenericContext ctx;
2863 MonoType *args [16];
2865 memset (&ctx, 0, sizeof (ctx));
2867 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
2869 args [0] = &tclass->byval_arg;
2870 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2872 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
2873 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
2874 g_assert (gcomparer);
2875 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
2881 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
2884 MonoGenericContext ctx;
2885 MonoType *args [16];
2887 memset (&ctx, 0, sizeof (ctx));
2889 for (i = 0; i < ninsts; ++i) {
2890 args [0] = insts [i];
2891 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
2892 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force);
2897 * add_generic_instances:
2899 * Add instances referenced by the METHODSPEC/TYPESPEC table.
2902 add_generic_instances (MonoAotCompile *acfg)
2907 MonoMethodHeader *header;
2908 MonoMethodSignature *sig;
2909 MonoGenericContext *context;
2911 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
2912 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
2913 method = mono_get_method (acfg->image, token, NULL);
2918 if (method->klass->image != acfg->image)
2921 context = mono_method_get_context (method);
2923 if (context && ((context->class_inst && context->class_inst->is_open)))
2927 * For open methods, create an instantiation which can be passed to the JIT.
2928 * FIXME: Handle class_inst as well.
2930 if (context && context->method_inst && context->method_inst->is_open) {
2931 MonoGenericContext shared_context;
2932 MonoGenericInst *inst;
2933 MonoType **type_argv;
2935 MonoMethod *declaring_method;
2936 gboolean supported = TRUE;
2938 /* Check that the context doesn't contain open constructed types */
2939 if (context->class_inst) {
2940 inst = context->class_inst;
2941 for (i = 0; i < inst->type_argc; ++i) {
2942 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)
2944 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2948 if (context->method_inst) {
2949 inst = context->method_inst;
2950 for (i = 0; i < inst->type_argc; ++i) {
2951 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)
2953 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
2961 memset (&shared_context, 0, sizeof (MonoGenericContext));
2963 inst = context->class_inst;
2965 type_argv = g_new0 (MonoType*, inst->type_argc);
2966 for (i = 0; i < inst->type_argc; ++i) {
2967 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)
2968 type_argv [i] = &mono_defaults.object_class->byval_arg;
2970 type_argv [i] = inst->type_argv [i];
2973 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
2977 inst = context->method_inst;
2979 type_argv = g_new0 (MonoType*, inst->type_argc);
2980 for (i = 0; i < inst->type_argc; ++i) {
2981 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)
2982 type_argv [i] = &mono_defaults.object_class->byval_arg;
2984 type_argv [i] = inst->type_argv [i];
2987 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
2991 if (method->is_generic || method->klass->generic_container)
2992 declaring_method = method;
2994 declaring_method = mono_method_get_declaring_generic_method (method);
2996 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3000 * If the method is fully sharable, it was already added in place of its
3001 * generic definition.
3003 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3007 * FIXME: Partially shared methods are not shared here, so we end up with
3008 * many identical methods.
3010 add_extra_method (acfg, method);
3013 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3016 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3018 klass = mono_class_get (acfg->image, token);
3019 if (!klass || klass->rank)
3022 add_generic_class (acfg, klass, FALSE);
3025 /* Add types of args/locals */
3026 for (i = 0; i < acfg->methods->len; ++i) {
3029 method = g_ptr_array_index (acfg->methods, i);
3031 sig = mono_method_signature (method);
3034 for (j = 0; j < sig->param_count; ++j)
3035 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3036 add_generic_class (acfg, mono_class_from_mono_type (sig->params [j]), FALSE);
3039 header = mono_method_get_header (method);
3042 for (j = 0; j < header->num_locals; ++j)
3043 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3044 add_generic_class (acfg, mono_class_from_mono_type (header->locals [j]), FALSE);
3048 if (acfg->image == mono_defaults.corlib) {
3050 MonoType *insts [256];
3053 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3054 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3055 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3056 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3057 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3058 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3059 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3060 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3061 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3062 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3063 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3064 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3066 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3067 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3069 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3070 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3072 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3074 /* Add instances of the array generic interfaces for primitive types */
3075 /* This will add instances of the InternalArray_ helper methods in Array too */
3076 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3078 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3079 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3081 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3082 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3084 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3087 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3088 * used for all instances of GetGenericValueImpl by the AOT runtime.
3091 MonoGenericContext ctx;
3092 MonoType *args [16];
3093 MonoMethod *get_method;
3094 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3096 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3099 memset (&ctx, 0, sizeof (ctx));
3100 args [0] = &mono_defaults.object_class->byval_arg;
3101 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3102 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3109 * is_direct_callable:
3111 * Return whenever the method identified by JI is directly callable without
3112 * going through the PLT.
3115 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3117 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3118 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3120 gboolean direct_callable = TRUE;
3122 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3123 direct_callable = FALSE;
3124 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3125 // FIXME: Maybe call the wrapper directly ?
3126 direct_callable = FALSE;
3128 if (direct_callable)
3137 * emit_and_reloc_code:
3139 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
3140 * is true, calls are made through the GOT too. This is used for emitting trampolines
3141 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3142 * since trampolines are needed to make PTL work.
3145 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3147 int i, pindex, start_index, method_index;
3149 MonoJumpInfo *patch_info;
3150 MonoMethodHeader *header;
3151 gboolean skip, direct_call;
3153 char direct_call_target [128];
3156 header = mono_method_get_header (method);
3158 method_index = get_method_index (acfg, method);
3161 /* Collect and sort relocations */
3162 patches = g_ptr_array_new ();
3163 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3164 g_ptr_array_add (patches, patch_info);
3165 g_ptr_array_sort (patches, compare_patches);
3168 for (i = 0; i < code_len; i++) {
3170 for (pindex = start_index; pindex < patches->len; ++pindex) {
3171 patch_info = g_ptr_array_index (patches, pindex);
3172 if (patch_info->ip.i >= i)
3176 #ifdef MONO_ARCH_AOT_SUPPORTED
3178 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3179 start_index = pindex;
3181 switch (patch_info->type) {
3182 case MONO_PATCH_INFO_NONE:
3184 case MONO_PATCH_INFO_GOT_OFFSET: {
3187 arch_emit_got_offset (acfg, code + i, &code_size);
3190 patch_info->type = MONO_PATCH_INFO_NONE;
3195 * If this patch is a call, try emitting a direct call instead of
3196 * through a PLT entry. This is possible if the called method is in
3197 * the same assembly and requires no initialization.
3199 direct_call = FALSE;
3200 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3201 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3202 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3203 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3205 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3206 patch_info->type = MONO_PATCH_INFO_NONE;
3207 acfg->stats.direct_calls ++;
3210 acfg->stats.all_calls ++;
3213 if (!got_only && !direct_call) {
3214 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3216 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3218 sprintf (direct_call_target, "%s", plt_entry->symbol);
3220 /* Nullify the patch */
3221 patch_info->type = MONO_PATCH_INFO_NONE;
3228 arch_emit_direct_call (acfg, direct_call_target, &call_size);
3233 got_slot = get_got_offset (acfg, patch_info);
3235 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3242 #endif /* MONO_ARCH_AOT_SUPPORTED */
3245 /* Find next patch */
3247 for (pindex = start_index; pindex < patches->len; ++pindex) {
3248 patch_info = g_ptr_array_index (patches, pindex);
3249 if (patch_info->ip.i >= i)
3253 /* Try to emit multiple bytes at once */
3254 if (pindex < patches->len && patch_info->ip.i > i) {
3255 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3256 i = patch_info->ip.i - 1;
3258 emit_bytes (acfg, code + i, 1);
3267 * Modify SYMBOL so it only includes characters permissible in symbols.
3270 sanitize_symbol (char *symbol)
3272 int i, len = strlen (symbol);
3274 for (i = 0; i < len; ++i)
3275 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3280 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3282 char *name1, *name2, *cached;
3283 int i, j, len, count;
3285 name1 = mono_method_full_name (method, TRUE);
3286 len = strlen (name1);
3287 name2 = malloc (strlen (prefix) + len + 16);
3288 memcpy (name2, prefix, strlen (prefix));
3289 j = strlen (prefix);
3290 for (i = 0; i < len; ++i) {
3291 if (isalnum (name1 [i])) {
3292 name2 [j ++] = name1 [i];
3293 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3295 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3298 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3307 while (g_hash_table_lookup (cache, name2)) {
3308 sprintf (name2 + j, "_%d", count);
3312 cached = g_strdup (name2);
3313 g_hash_table_insert (cache, cached, cached);
3319 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3324 char *debug_sym = NULL;
3326 int func_alignment = AOT_FUNC_ALIGNMENT;
3327 MonoMethodHeader *header;
3329 method = cfg->orig_method;
3330 code = cfg->native_code;
3331 header = cfg->header;
3333 method_index = get_method_index (acfg, method);
3335 /* Make the labels local */
3336 sprintf (symbol, "%s", cfg->asm_symbol);
3338 emit_section_change (acfg, ".text", 0);
3339 emit_alignment (acfg, func_alignment);
3340 emit_label (acfg, symbol);
3342 if (acfg->aot_opts.write_symbols) {
3344 * Write a C style symbol for every method, this has two uses:
3345 * - it works on platforms where the dwarf debugging info is not
3347 * - it allows the setting of breakpoints of aot-ed methods.
3349 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3351 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3352 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3353 emit_label (acfg, debug_sym);
3356 if (cfg->verbose_level > 0)
3357 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3359 acfg->stats.code_size += cfg->code_len;
3361 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3363 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3367 if (acfg->aot_opts.write_symbols) {
3368 emit_symbol_size (acfg, debug_sym, ".");
3372 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3373 emit_label (acfg, symbol);
3379 * Encode PATCH_INFO into its disk representation.
3382 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3386 switch (patch_info->type) {
3387 case MONO_PATCH_INFO_NONE:
3389 case MONO_PATCH_INFO_IMAGE:
3390 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3392 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3393 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3395 case MONO_PATCH_INFO_METHOD_REL:
3396 encode_value ((gint)patch_info->data.offset, p, &p);
3398 case MONO_PATCH_INFO_SWITCH: {
3399 gpointer *table = (gpointer *)patch_info->data.table->table;
3402 encode_value (patch_info->data.table->table_size, p, &p);
3403 for (k = 0; k < patch_info->data.table->table_size; k++)
3404 encode_value ((int)(gssize)table [k], p, &p);
3407 case MONO_PATCH_INFO_METHODCONST:
3408 case MONO_PATCH_INFO_METHOD:
3409 case MONO_PATCH_INFO_METHOD_JUMP:
3410 case MONO_PATCH_INFO_ICALL_ADDR:
3411 case MONO_PATCH_INFO_METHOD_RGCTX:
3412 encode_method_ref (acfg, patch_info->data.method, p, &p);
3414 case MONO_PATCH_INFO_INTERNAL_METHOD:
3415 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3416 guint32 len = strlen (patch_info->data.name);
3418 encode_value (len, p, &p);
3420 memcpy (p, patch_info->data.name, len);
3425 case MONO_PATCH_INFO_LDSTR: {
3426 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3427 guint32 token = patch_info->data.token->token;
3428 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3429 encode_value (image_index, p, &p);
3430 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3433 case MONO_PATCH_INFO_RVA:
3434 case MONO_PATCH_INFO_DECLSEC:
3435 case MONO_PATCH_INFO_LDTOKEN:
3436 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3437 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3438 encode_value (patch_info->data.token->token, p, &p);
3439 encode_value (patch_info->data.token->has_context, p, &p);
3440 if (patch_info->data.token->has_context)
3441 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3443 case MONO_PATCH_INFO_EXC_NAME: {
3444 MonoClass *ex_class;
3447 mono_class_from_name (mono_defaults.exception_class->image,
3448 "System", patch_info->data.target);
3449 g_assert (ex_class);
3450 encode_klass_ref (acfg, ex_class, p, &p);
3453 case MONO_PATCH_INFO_R4:
3454 encode_value (*((guint32 *)patch_info->data.target), p, &p);
3456 case MONO_PATCH_INFO_R8:
3457 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
3458 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
3460 case MONO_PATCH_INFO_VTABLE:
3461 case MONO_PATCH_INFO_CLASS:
3462 case MONO_PATCH_INFO_IID:
3463 case MONO_PATCH_INFO_ADJUSTED_IID:
3464 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3466 case MONO_PATCH_INFO_CLASS_INIT:
3467 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
3468 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
3470 case MONO_PATCH_INFO_FIELD:
3471 case MONO_PATCH_INFO_SFLDA:
3472 encode_field_info (acfg, patch_info->data.field, p, &p);
3474 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
3476 case MONO_PATCH_INFO_RGCTX_FETCH: {
3477 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
3479 encode_method_ref (acfg, entry->method, p, &p);
3480 encode_value (entry->in_mrgctx, p, &p);
3481 encode_value (entry->info_type, p, &p);
3482 encode_value (entry->data->type, p, &p);
3483 encode_patch (acfg, entry->data, p, &p);
3486 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
3487 case MONO_PATCH_INFO_MONITOR_ENTER:
3488 case MONO_PATCH_INFO_MONITOR_EXIT:
3489 case MONO_PATCH_INFO_SEQ_POINT_INFO:
3491 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
3492 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
3493 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
3496 g_warning ("unable to handle jump info %d", patch_info->type);
3497 g_assert_not_reached ();
3504 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
3507 guint32 pindex, offset;
3508 MonoJumpInfo *patch_info;
3510 encode_value (n_patches, p, &p);
3512 for (pindex = 0; pindex < patches->len; ++pindex) {
3513 patch_info = g_ptr_array_index (patches, pindex);
3515 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
3519 offset = get_got_offset (acfg, patch_info);
3520 encode_value (offset, p, &p);
3527 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
3531 int pindex, buf_size, n_patches;
3534 MonoJumpInfo *patch_info;
3535 MonoMethodHeader *header;
3536 guint32 method_index;
3538 guint32 first_got_offset;
3540 method = cfg->orig_method;
3541 code = cfg->native_code;
3542 header = mono_method_get_header (method);
3544 method_index = get_method_index (acfg, method);
3546 /* Sort relocations */
3547 patches = g_ptr_array_new ();
3548 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
3549 g_ptr_array_add (patches, patch_info);
3550 g_ptr_array_sort (patches, compare_patches);
3552 first_got_offset = acfg->cfgs [method_index]->got_offset;
3554 /**********************/
3555 /* Encode method info */
3556 /**********************/
3558 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
3559 p = buf = g_malloc (buf_size);
3561 if (mono_class_get_cctor (method->klass))
3562 encode_klass_ref (acfg, method->klass, p, &p);
3564 /* Not needed when loading the method */
3565 encode_value (0, p, &p);
3568 if (cfg->opt & MONO_OPT_SHARED) {
3569 encode_value (g_list_length (cfg->ldstr_list), p, &p);
3570 for (l = cfg->ldstr_list; l; l = l->next) {
3571 encode_value ((long)l->data, p, &p);
3575 /* Used only in shared mode */
3576 g_assert (!cfg->ldstr_list);
3579 for (pindex = 0; pindex < patches->len; ++pindex) {
3580 patch_info = g_ptr_array_index (patches, pindex);
3582 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
3583 (patch_info->type == MONO_PATCH_INFO_NONE)) {
3584 patch_info->type = MONO_PATCH_INFO_NONE;
3589 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
3590 /* Stored in a GOT slot initialized at module load time */
3591 patch_info->type = MONO_PATCH_INFO_NONE;
3595 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
3596 /* Stored in a GOT slot initialized at module load time */
3597 patch_info->type = MONO_PATCH_INFO_NONE;
3601 if (is_plt_patch (patch_info)) {
3602 /* Calls are made through the PLT */
3603 patch_info->type = MONO_PATCH_INFO_NONE;
3611 g_assert (cfg->has_got_slots);
3613 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
3615 acfg->stats.info_size += p - buf;
3617 g_assert (p - buf < buf_size);
3619 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
3624 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
3626 guint32 cache_index;
3629 /* Reuse the unwind module to canonize and store unwind info entries */
3630 cache_index = mono_cache_unwind_info (encoded, encoded_len);
3632 /* Use +/- 1 to distinguish 0s from missing entries */
3633 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
3641 * It would be easier to use assembler symbols, but the caller needs an
3644 offset = acfg->unwind_info_offset;
3645 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
3646 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
3649 encode_value (encoded_len, p, &p);
3651 acfg->unwind_info_offset += encoded_len + (p - buf);
3657 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
3660 int i, k, buf_size, method_index;
3661 guint32 debug_info_size;
3663 MonoMethodHeader *header;
3664 guint8 *p, *buf, *debug_info;
3665 MonoJitInfo *jinfo = cfg->jit_info;
3667 gboolean use_unwind_ops = FALSE;
3668 MonoSeqPointInfo *seq_points;
3670 method = cfg->orig_method;
3671 code = cfg->native_code;
3672 header = cfg->header;
3674 method_index = get_method_index (acfg, method);
3676 if (!acfg->aot_opts.nodebug) {
3677 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
3680 debug_info_size = 0;
3683 seq_points = cfg->seq_point_info;
3685 buf_size = header->num_clauses * 256 + debug_info_size + 1024 + (seq_points ? (seq_points->len * 64) : 0);
3686 p = buf = g_malloc (buf_size);
3688 #ifdef MONO_ARCH_HAVE_XP_UNWIND
3689 use_unwind_ops = cfg->unwind_ops != NULL;
3692 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);
3694 encode_value (flags, p, &p);
3696 if (use_unwind_ops) {
3697 guint32 encoded_len;
3701 * This is a duplicate of the data in the .debug_frame section, but that
3702 * section cannot be accessed using the dl interface.
3704 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
3705 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
3708 encode_value (jinfo->used_regs, p, &p);
3711 /*Encode the number of holes before the number of clauses to make decoding easier*/
3712 if (jinfo->has_try_block_holes) {
3713 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3714 encode_value (table->num_holes, p, &p);
3717 /* Exception table */
3718 if (cfg->compile_llvm) {
3720 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
3721 * since the information is only available to llc. Instead, we let llc save the data
3722 * into the LSDA, and read it from there at runtime.
3724 /* The assembly might be CIL stripped so emit the data ourselves */
3725 if (header->num_clauses)
3726 encode_value (header->num_clauses, p, &p);
3728 for (k = 0; k < header->num_clauses; ++k) {
3729 MonoExceptionClause *clause;
3731 clause = &header->clauses [k];
3733 encode_value (clause->flags, p, &p);
3734 if (clause->data.catch_class) {
3735 encode_value (1, p, &p);
3736 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
3738 encode_value (0, p, &p);
3741 /* Emit a list of nesting clauses */
3742 for (i = 0; i < header->num_clauses; ++i) {
3744 MonoExceptionClause *clause1 = &header->clauses [cindex1];
3746 MonoExceptionClause *clause2 = &header->clauses [cindex2];
3748 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
3749 encode_value (i, p, &p);
3751 encode_value (-1, p, &p);
3754 if (jinfo->num_clauses)
3755 encode_value (jinfo->num_clauses, p, &p);
3757 for (k = 0; k < jinfo->num_clauses; ++k) {
3758 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
3760 encode_value (ei->flags, p, &p);
3761 encode_value (ei->exvar_offset, p, &p);
3763 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
3764 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
3766 if (ei->data.catch_class) {
3767 encode_value (1, p, &p);
3768 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
3770 encode_value (0, p, &p);
3774 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
3775 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
3776 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
3780 if (jinfo->has_generic_jit_info) {
3781 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
3783 if (!cfg->compile_llvm) {
3784 encode_value (gi->has_this ? 1 : 0, p, &p);
3785 encode_value (gi->this_reg, p, &p);
3786 encode_value (gi->this_offset, p, &p);
3790 * Need to encode jinfo->method too, since it is not equal to 'method'
3791 * when using generic sharing.
3793 encode_method_ref (acfg, jinfo->method, p, &p);
3796 if (jinfo->has_try_block_holes) {
3797 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
3798 for (i = 0; i < table->num_holes; ++i) {
3799 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
3800 encode_value (hole->clause, p, &p);
3801 encode_value (hole->length, p, &p);
3802 encode_value (hole->offset, p, &p);
3807 int il_offset, native_offset, last_il_offset, last_native_offset, j;
3809 encode_value (seq_points->len, p, &p);
3810 last_il_offset = last_native_offset = 0;
3811 for (i = 0; i < seq_points->len; ++i) {
3812 SeqPoint *sp = &seq_points->seq_points [i];
3813 il_offset = sp->il_offset;
3814 native_offset = sp->native_offset;
3815 encode_value (il_offset - last_il_offset, p, &p);
3816 encode_value (native_offset - last_native_offset, p, &p);
3817 last_il_offset = il_offset;
3818 last_native_offset = native_offset;
3820 encode_value (sp->next_len, p, &p);
3821 for (j = 0; j < sp->next_len; ++j)
3822 encode_value (sp->next [j], p, &p);
3827 g_assert (debug_info_size < buf_size);
3829 encode_value (debug_info_size, p, &p);
3830 if (debug_info_size) {
3831 memcpy (p, debug_info, debug_info_size);
3832 p += debug_info_size;
3833 g_free (debug_info);
3836 acfg->stats.ex_info_size += p - buf;
3838 g_assert (p - buf < buf_size);
3841 cfg->ex_info_offset = add_to_blob (acfg, buf, p - buf);
3846 emit_klass_info (MonoAotCompile *acfg, guint32 token)
3848 MonoClass *klass = mono_class_get (acfg->image, token);
3850 int i, buf_size, res;
3851 gboolean no_special_static, cant_encode;
3852 gpointer iter = NULL;
3857 p = buf = g_malloc (buf_size);
3859 /* Mark as unusable */
3860 encode_value (-1, p, &p);
3862 res = add_to_blob (acfg, buf, p - buf);
3868 buf_size = 10240 + (klass->vtable_size * 16);
3869 p = buf = g_malloc (buf_size);
3873 mono_class_init (klass);
3875 mono_class_get_nested_types (klass, &iter);
3876 g_assert (klass->nested_classes_inited);
3878 mono_class_setup_vtable (klass);
3881 * Emit all the information which is required for creating vtables so
3882 * the runtime does not need to create the MonoMethod structures which
3883 * take up a lot of space.
3886 no_special_static = !mono_class_has_special_static_fields (klass);
3888 /* Check whenever we have enough info to encode the vtable */
3889 cant_encode = FALSE;
3890 for (i = 0; i < klass->vtable_size; ++i) {
3891 MonoMethod *cm = klass->vtable [i];
3893 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
3897 if (klass->generic_container || cant_encode) {
3898 encode_value (-1, p, &p);
3900 encode_value (klass->vtable_size, p, &p);
3901 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);
3902 if (klass->has_cctor)
3903 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
3904 if (klass->has_finalize)
3905 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
3907 encode_value (klass->instance_size, p, &p);
3908 encode_value (mono_class_data_size (klass), p, &p);
3909 encode_value (klass->packing_size, p, &p);
3910 encode_value (klass->min_align, p, &p);
3912 for (i = 0; i < klass->vtable_size; ++i) {
3913 MonoMethod *cm = klass->vtable [i];
3916 encode_method_ref (acfg, cm, p, &p);
3918 encode_value (0, p, &p);
3922 acfg->stats.class_info_size += p - buf;
3924 g_assert (p - buf < buf_size);
3925 res = add_to_blob (acfg, buf, p - buf);
3932 * Calls made from AOTed code are routed through a table of jumps similar to the
3933 * ELF PLT (Program Linkage Table). The differences are the following:
3934 * - the ELF PLT entries make an indirect jump though the GOT so they expect the
3935 * GOT pointer to be in EBX. We want to avoid this, so our table contains direct
3936 * jumps. This means the jumps need to be patched when the address of the callee is
3937 * known. Initially the PLT entries jump to code which transfers control to the
3938 * AOT runtime through the first PLT entry.
3941 emit_plt (MonoAotCompile *acfg)
3947 cache = g_hash_table_new (g_str_hash, g_str_equal);
3950 sprintf (symbol, "plt");
3952 emit_section_change (acfg, ".text", 0);
3953 emit_global (acfg, symbol, TRUE);
3954 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
3955 emit_label (acfg, symbol);
3956 emit_label (acfg, acfg->plt_symbol);
3958 for (i = 0; i < acfg->plt_offset; ++i) {
3960 char *debug_sym = NULL;
3961 MonoPltEntry *plt_entry = NULL;
3966 * The first plt entry is used to transfer code to the AOT loader.
3968 arch_emit_plt_entry (acfg, i);
3972 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
3974 sprintf (label, "%s", plt_entry->symbol);
3978 * If the target is directly callable, alias the plt symbol to point to
3980 * FIXME: Use this to simplify emit_and_reloc_code ().
3981 * FIXME: Avoid the got slot.
3982 * FIXME: Add support to the binary writer.
3984 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
3985 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
3986 fprintf (acfg->fp, "\n.set %s, %s\n", label, callee_cfg->asm_symbol);
3991 emit_label (acfg, label);
3993 if (acfg->aot_opts.write_symbols) {
3995 case MONO_PATCH_INFO_METHOD:
3996 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
3998 case MONO_PATCH_INFO_INTERNAL_METHOD:
3999 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4001 case MONO_PATCH_INFO_CLASS_INIT:
4002 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4003 sanitize_symbol (debug_sym);
4005 case MONO_PATCH_INFO_RGCTX_FETCH:
4006 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4008 case MONO_PATCH_INFO_ICALL_ADDR: {
4009 char *s = get_debug_sym (ji->data.method, "", cache);
4011 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4015 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4016 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4018 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4019 debug_sym = g_strdup_printf ("plt__generic_class_init");
4026 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4027 emit_label (acfg, debug_sym);
4031 arch_emit_plt_entry (acfg, i);
4034 emit_symbol_size (acfg, debug_sym, ".");
4039 emit_symbol_size (acfg, acfg->plt_symbol, ".");
4041 sprintf (symbol, "plt_end");
4042 emit_global (acfg, symbol, TRUE);
4043 emit_label (acfg, symbol);
4045 g_hash_table_destroy (cache);
4048 static G_GNUC_UNUSED void
4049 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4051 char start_symbol [256];
4053 guint32 buf_size, info_offset;
4054 MonoJumpInfo *patch_info;
4065 code_size = info->code_size;
4067 unwind_ops = info->unwind_ops;
4069 #ifdef __native_client_codegen__
4070 mono_nacl_fix_patches (code, ji);
4075 sprintf (start_symbol, "%s", name);
4077 emit_section_change (acfg, ".text", 0);
4078 emit_global (acfg, start_symbol, TRUE);
4079 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4080 emit_label (acfg, start_symbol);
4082 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4083 emit_label (acfg, symbol);
4086 * The code should access everything through the GOT, so we pass
4089 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4091 emit_symbol_size (acfg, start_symbol, ".");
4095 /* Sort relocations */
4096 patches = g_ptr_array_new ();
4097 for (patch_info = ji; patch_info; patch_info = patch_info->next)
4098 if (patch_info->type != MONO_PATCH_INFO_NONE)
4099 g_ptr_array_add (patches, patch_info);
4100 g_ptr_array_sort (patches, compare_patches);
4102 buf_size = patches->len * 128 + 128;
4103 buf = g_malloc (buf_size);
4106 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4107 g_assert (p - buf < buf_size);
4109 sprintf (symbol, "%s_p", name);
4111 info_offset = add_to_blob (acfg, buf, p - buf);
4113 emit_section_change (acfg, RODATA_SECT, 0);
4114 emit_global (acfg, symbol, FALSE);
4115 emit_label (acfg, symbol);
4117 emit_int32 (acfg, info_offset);
4119 /* Emit debug info */
4123 sprintf (symbol, "%s", name);
4124 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4127 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4132 emit_trampolines (MonoAotCompile *acfg)
4135 int i, tramp_got_offset;
4136 MonoAotTrampoline ntype;
4137 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4142 if (!acfg->aot_opts.full_aot)
4145 g_assert (acfg->image->assembly);
4147 /* Currently, we emit most trampolines into the mscorlib AOT image. */
4148 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4149 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4150 MonoTrampInfo *info;
4153 * Emit the generic trampolines.
4155 * We could save some code by treating the generic trampolines as a wrapper
4156 * method, but that approach has its own complexities, so we choose the simpler
4159 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4160 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4161 emit_trampoline (acfg, acfg->got_offset, info);
4164 mono_arch_get_nullified_class_init_trampoline (&info);
4165 emit_trampoline (acfg, acfg->got_offset, info);
4166 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4167 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4168 emit_trampoline (acfg, acfg->got_offset, info);
4169 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4170 emit_trampoline (acfg, acfg->got_offset, info);
4173 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4174 emit_trampoline (acfg, acfg->got_offset, info);
4176 /* Emit the exception related code pieces */
4177 code = mono_arch_get_restore_context (&info, TRUE);
4178 emit_trampoline (acfg, acfg->got_offset, info);
4179 code = mono_arch_get_call_filter (&info, TRUE);
4180 emit_trampoline (acfg, acfg->got_offset, info);
4181 code = mono_arch_get_throw_exception (&info, TRUE);
4182 emit_trampoline (acfg, acfg->got_offset, info);
4183 code = mono_arch_get_rethrow_exception (&info, TRUE);
4184 emit_trampoline (acfg, acfg->got_offset, info);
4185 code = mono_arch_get_throw_corlib_exception (&info, TRUE);
4186 emit_trampoline (acfg, acfg->got_offset, info);
4188 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4190 GSList *l = mono_arch_get_trampolines (TRUE);
4193 MonoTrampInfo *info = l->data;
4195 emit_trampoline (acfg, acfg->got_offset, info);
4201 for (i = 0; i < 128; ++i) {
4204 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4205 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4206 emit_trampoline (acfg, acfg->got_offset, info);
4208 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4209 code = mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4210 emit_trampoline (acfg, acfg->got_offset, info);
4216 /* delegate_invoke_impl trampolines */
4217 l = mono_arch_get_delegate_invoke_impls ();
4219 MonoTrampInfo *info = l->data;
4221 emit_trampoline (acfg, acfg->got_offset, info);
4226 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4228 /* Emit trampolines which are numerous */
4231 * These include the following:
4232 * - specific trampolines
4233 * - static rgctx invoke trampolines
4235 * These trampolines have the same code, they are parameterized by GOT
4237 * They are defined in this file, in the arch_... routines instead of
4238 * in tramp-<ARCH>.c, since it is easier to do it this way.
4242 * When running in aot-only mode, we can't create specific trampolines at
4243 * runtime, so we create a few, and save them in the AOT file.
4244 * Normal trampolines embed their argument as a literal inside the
4245 * trampoline code, we can't do that here, so instead we embed an offset
4246 * which needs to be added to the trampoline address to get the address of
4247 * the GOT slot which contains the argument value.
4248 * The generated trampolines jump to the generic trampolines using another
4249 * GOT slot, which will be setup by the AOT loader to point to the
4250 * generic trampoline code of the given type.
4254 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4258 emit_section_change (acfg, ".text", 0);
4260 tramp_got_offset = acfg->got_offset;
4262 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4264 case MONO_AOT_TRAMP_SPECIFIC:
4265 sprintf (symbol, "specific_trampolines");
4267 case MONO_AOT_TRAMP_STATIC_RGCTX:
4268 sprintf (symbol, "static_rgctx_trampolines");
4270 case MONO_AOT_TRAMP_IMT_THUNK:
4271 sprintf (symbol, "imt_thunks");
4274 g_assert_not_reached ();
4277 emit_global (acfg, symbol, TRUE);
4278 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4279 emit_label (acfg, symbol);
4281 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4283 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4287 case MONO_AOT_TRAMP_SPECIFIC:
4288 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4289 tramp_got_offset += 2;
4291 case MONO_AOT_TRAMP_STATIC_RGCTX:
4292 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
4293 tramp_got_offset += 2;
4295 case MONO_AOT_TRAMP_IMT_THUNK:
4296 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4297 tramp_got_offset += 1;
4300 g_assert_not_reached ();
4302 #ifdef __native_client_codegen__
4303 /* align to avoid 32-byte boundary crossings */
4304 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4307 if (!acfg->trampoline_size [ntype]) {
4308 g_assert (tramp_size);
4309 acfg->trampoline_size [ntype] = tramp_size;
4314 /* Reserve some entries at the end of the GOT for our use */
4315 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4318 acfg->got_offset += acfg->num_trampoline_got_entries;
4322 str_begins_with (const char *str1, const char *str2)
4324 int len = strlen (str2);
4325 return strncmp (str1, str2, len) == 0;
4329 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
4331 gchar **args, **ptr;
4333 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
4334 for (ptr = args; ptr && *ptr; ptr ++) {
4335 const char *arg = *ptr;
4337 if (str_begins_with (arg, "outfile=")) {
4338 opts->outfile = g_strdup (arg + strlen ("outfile="));
4339 } else if (str_begins_with (arg, "save-temps")) {
4340 opts->save_temps = TRUE;
4341 } else if (str_begins_with (arg, "keep-temps")) {
4342 opts->save_temps = TRUE;
4343 } else if (str_begins_with (arg, "write-symbols")) {
4344 opts->write_symbols = TRUE;
4345 } else if (str_begins_with (arg, "metadata-only")) {
4346 opts->metadata_only = TRUE;
4347 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
4348 opts->bind_to_runtime_version = TRUE;
4349 } else if (str_begins_with (arg, "full")) {
4350 opts->full_aot = TRUE;
4351 } else if (str_begins_with (arg, "threads=")) {
4352 opts->nthreads = atoi (arg + strlen ("threads="));
4353 } else if (str_begins_with (arg, "static")) {
4354 opts->static_link = TRUE;
4355 opts->no_dlsym = TRUE;
4356 } else if (str_begins_with (arg, "asmonly")) {
4357 opts->asm_only = TRUE;
4358 } else if (str_begins_with (arg, "asmwriter")) {
4359 opts->asm_writer = TRUE;
4360 } else if (str_begins_with (arg, "nodebug")) {
4361 opts->nodebug = TRUE;
4362 } else if (str_begins_with (arg, "ntrampolines=")) {
4363 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
4364 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
4365 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
4366 } else if (str_begins_with (arg, "nimt-trampolines=")) {
4367 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
4368 } else if (str_begins_with (arg, "autoreg")) {
4369 opts->autoreg = TRUE;
4370 } else if (str_begins_with (arg, "tool-prefix=")) {
4371 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
4372 } else if (str_begins_with (arg, "soft-debug")) {
4373 opts->soft_debug = TRUE;
4374 } else if (str_begins_with (arg, "print-skipped")) {
4375 opts->print_skipped_methods = TRUE;
4376 } else if (str_begins_with (arg, "stats")) {
4378 } else if (str_begins_with (arg, "mtriple=")) {
4379 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
4381 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
4390 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
4392 MonoMethod *method = (MonoMethod*)key;
4393 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
4394 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
4395 MonoAotCompile *acfg = user_data;
4397 new_ji->image = ji->image;
4398 new_ji->token = ji->token;
4399 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
4403 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
4405 if (klass->type_token)
4407 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
4410 return can_encode_class (acfg, klass->element_class);
4415 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
4417 switch (patch_info->type) {
4418 case MONO_PATCH_INFO_METHOD:
4419 case MONO_PATCH_INFO_METHODCONST: {
4420 MonoMethod *method = patch_info->data.method;
4422 if (method->wrapper_type) {
4423 switch (method->wrapper_type) {
4424 case MONO_WRAPPER_NONE:
4425 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
4426 case MONO_WRAPPER_XDOMAIN_INVOKE:
4427 case MONO_WRAPPER_STFLD:
4428 case MONO_WRAPPER_LDFLD:
4429 case MONO_WRAPPER_LDFLDA:
4430 case MONO_WRAPPER_LDFLD_REMOTE:
4431 case MONO_WRAPPER_STFLD_REMOTE:
4432 case MONO_WRAPPER_STELEMREF:
4433 case MONO_WRAPPER_ISINST:
4434 case MONO_WRAPPER_PROXY_ISINST:
4435 case MONO_WRAPPER_ALLOC:
4436 case MONO_WRAPPER_REMOTING_INVOKE:
4437 case MONO_WRAPPER_UNKNOWN:
4438 case MONO_WRAPPER_WRITE_BARRIER:
4440 case MONO_WRAPPER_MANAGED_TO_MANAGED:
4441 if (!strcmp (method->name, "ElementAddr"))
4446 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
4450 if (!method->token) {
4451 /* The method is part of a constructed type like Int[,].Set (). */
4452 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
4453 if (method->klass->rank)
4461 case MONO_PATCH_INFO_VTABLE:
4462 case MONO_PATCH_INFO_CLASS_INIT:
4463 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4464 case MONO_PATCH_INFO_CLASS:
4465 case MONO_PATCH_INFO_IID:
4466 case MONO_PATCH_INFO_ADJUSTED_IID:
4467 if (!can_encode_class (acfg, patch_info->data.klass)) {
4468 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
4472 case MONO_PATCH_INFO_RGCTX_FETCH: {
4473 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4475 if (!can_encode_patch (acfg, entry->data))
4489 * AOT compile a given method.
4490 * This function might be called by multiple threads, so it must be thread-safe.
4493 compile_method (MonoAotCompile *acfg, MonoMethod *method)
4496 MonoJumpInfo *patch_info;
4499 MonoMethod *wrapped;
4501 if (acfg->aot_opts.metadata_only)
4504 mono_acfg_lock (acfg);
4505 index = get_method_index (acfg, method);
4506 mono_acfg_unlock (acfg);
4508 /* fixme: maybe we can also precompile wrapper methods */
4509 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
4510 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
4511 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
4512 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
4516 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
4519 wrapped = mono_marshal_method_from_wrapper (method);
4520 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
4521 // FIXME: The wrapper should be generic too, but it is not
4524 InterlockedIncrement (&acfg->stats.mcount);
4527 if (method->is_generic || method->klass->generic_container) {
4528 InterlockedIncrement (&acfg->stats.genericcount);
4533 //acfg->aot_opts.print_skipped_methods = TRUE;
4536 * Since these methods are the only ones which are compiled with
4537 * AOT support, and they are not used by runtime startup/shutdown code,
4538 * the runtime will not see AOT methods during AOT compilation,so it
4539 * does not need to support them by creating a fake GOT etc.
4541 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
4542 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
4543 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
4544 InterlockedIncrement (&acfg->stats.genericcount);
4547 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
4548 /* Let the exception happen at runtime */
4552 if (cfg->disable_aot) {
4553 if (acfg->aot_opts.print_skipped_methods)
4554 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
4555 InterlockedIncrement (&acfg->stats.ocount);
4556 mono_destroy_compile (cfg);
4560 /* Nullify patches which need no aot processing */
4561 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4562 switch (patch_info->type) {
4563 case MONO_PATCH_INFO_LABEL:
4564 case MONO_PATCH_INFO_BB:
4565 patch_info->type = MONO_PATCH_INFO_NONE;
4572 /* Collect method->token associations from the cfg */
4573 mono_acfg_lock (acfg);
4574 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
4575 mono_acfg_unlock (acfg);
4578 * Check for absolute addresses.
4581 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4582 switch (patch_info->type) {
4583 case MONO_PATCH_INFO_ABS:
4584 /* unable to handle this */
4593 if (acfg->aot_opts.print_skipped_methods)
4594 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
4595 InterlockedIncrement (&acfg->stats.abscount);
4596 mono_destroy_compile (cfg);
4600 /* Lock for the rest of the code */
4601 mono_acfg_lock (acfg);
4604 * Check for methods/klasses we can't encode.
4607 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4608 if (!can_encode_patch (acfg, patch_info))
4613 if (acfg->aot_opts.print_skipped_methods)
4614 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
4615 acfg->stats.ocount++;
4616 mono_destroy_compile (cfg);
4617 mono_acfg_unlock (acfg);
4621 /* Adds generic instances referenced by this method */
4623 * The depth is used to avoid infinite loops when generic virtual recursion is
4626 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
4628 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4629 switch (patch_info->type) {
4630 case MONO_PATCH_INFO_METHOD: {
4631 MonoMethod *m = patch_info->data.method;
4632 if (m->is_inflated) {
4633 if (!(mono_class_generic_sharing_enabled (m->klass) &&
4634 mono_method_is_generic_sharable_impl (m, FALSE)) &&
4635 !method_has_type_vars (m)) {
4636 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
4637 if (acfg->aot_opts.full_aot)
4638 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
4640 add_extra_method_with_depth (acfg, m, depth + 1);
4643 add_generic_class_with_depth (acfg, m->klass, depth + 5);
4645 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
4646 add_extra_method_with_depth (acfg, m, depth + 1);
4649 case MONO_PATCH_INFO_VTABLE: {
4650 MonoClass *klass = patch_info->data.klass;
4652 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
4653 add_generic_class_with_depth (acfg, klass, depth + 5);
4662 /* Determine whenever the method has GOT slots */
4663 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4664 switch (patch_info->type) {
4665 case MONO_PATCH_INFO_GOT_OFFSET:
4666 case MONO_PATCH_INFO_NONE:
4667 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4669 case MONO_PATCH_INFO_IMAGE:
4670 /* The assembly is stored in GOT slot 0 */
4671 if (patch_info->data.image != acfg->image)
4672 cfg->has_got_slots = TRUE;
4675 if (!is_plt_patch (patch_info))
4676 cfg->has_got_slots = TRUE;
4681 if (!cfg->has_got_slots)
4682 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
4685 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
4687 /* Make a copy of the patch info which is in the mempool */
4689 MonoJumpInfo *patches = NULL, *patches_end = NULL;
4691 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
4692 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
4695 patches = new_patch_info;
4697 patches_end->next = new_patch_info;
4698 patches_end = new_patch_info;
4700 cfg->patch_info = patches;
4702 /* Make a copy of the unwind info */
4704 GSList *l, *unwind_ops;
4708 for (l = cfg->unwind_ops; l; l = l->next) {
4709 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
4710 memcpy (op, l->data, sizeof (MonoUnwindOp));
4711 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
4713 cfg->unwind_ops = g_slist_reverse (unwind_ops);
4715 /* Make a copy of the argument/local info */
4717 MonoInst **args, **locals;
4718 MonoMethodSignature *sig;
4719 MonoMethodHeader *header;
4722 sig = mono_method_signature (method);
4723 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
4724 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
4725 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4726 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
4730 header = mono_method_get_header (method);
4731 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
4732 for (i = 0; i < header->num_locals; ++i) {
4733 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
4734 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
4736 cfg->locals = locals;
4739 /* Free some fields used by cfg to conserve memory */
4740 mono_mempool_destroy (cfg->mempool);
4741 cfg->mempool = NULL;
4742 g_free (cfg->varinfo);
4743 cfg->varinfo = NULL;
4747 mono_regstate_free (cfg->rs);
4751 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
4753 while (index >= acfg->cfgs_size) {
4754 MonoCompile **new_cfgs;
4757 new_size = acfg->cfgs_size * 2;
4758 new_cfgs = g_new0 (MonoCompile*, new_size);
4759 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
4760 g_free (acfg->cfgs);
4761 acfg->cfgs = new_cfgs;
4762 acfg->cfgs_size = new_size;
4764 acfg->cfgs [index] = cfg;
4766 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
4769 if (cfg->orig_method->wrapper_type)
4770 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
4773 mono_acfg_unlock (acfg);
4775 InterlockedIncrement (&acfg->stats.ccount);
4779 compile_thread_main (gpointer *user_data)
4781 MonoDomain *domain = user_data [0];
4782 MonoAotCompile *acfg = user_data [1];
4783 GPtrArray *methods = user_data [2];
4786 mono_thread_attach (domain);
4788 for (i = 0; i < methods->len; ++i)
4789 compile_method (acfg, g_ptr_array_index (methods, i));
4793 load_profile_files (MonoAotCompile *acfg)
4797 int file_index, res, method_index, i;
4804 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
4806 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
4811 infile = fopen (tmp, "r");
4814 printf ("Using profile data file '%s'\n", tmp);
4819 res = fscanf (infile, "%32s\n", ver);
4820 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
4821 printf ("Profile file has wrong version or invalid.\n");
4828 MonoMethodDesc *desc;
4831 if (fgets (name, 1023, infile) == NULL)
4834 /* Kill the newline */
4835 if (strlen (name) > 0)
4836 name [strlen (name) - 1] = '\0';
4838 desc = mono_method_desc_new (name, TRUE);
4840 method = mono_method_desc_search_in_image (desc, acfg->image);
4842 if (method && mono_method_get_token (method)) {
4843 token = mono_method_get_token (method);
4844 method_index = mono_metadata_token_index (token) - 1;
4846 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (method_index))) {
4847 acfg->method_order = g_list_append (acfg->method_order, GUINT_TO_POINTER (method_index));
4850 //printf ("No method found matching '%s'.\n", name);
4856 /* Add missing methods */
4858 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
4859 if (!g_list_find (acfg->method_order, GUINT_TO_POINTER (i)))
4860 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (i));
4862 unordered = g_list_reverse (unordered);
4863 if (acfg->method_order)
4864 g_list_last (acfg->method_order)->next = unordered;
4866 acfg->method_order = unordered;
4869 /* Used by the LLVM backend */
4871 mono_aot_get_got_offset (MonoJumpInfo *ji)
4873 return get_got_offset (llvm_acfg, ji);
4877 mono_aot_get_method_name (MonoCompile *cfg)
4879 guint32 method_index = get_method_index (llvm_acfg, cfg->orig_method);
4881 return g_strdup_printf ("m_%x", method_index);
4885 mono_aot_get_method_debug_name (MonoCompile *cfg)
4887 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
4891 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
4893 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
4894 MonoPltEntry *plt_entry;
4897 ji->data.target = data;
4899 if (!can_encode_patch (llvm_acfg, ji))
4902 plt_entry = get_plt_entry (llvm_acfg, ji);
4904 return g_strdup_printf (plt_entry->symbol);
4908 mono_aot_patch_info_dup (MonoJumpInfo* ji)
4912 mono_acfg_lock (llvm_acfg);
4913 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
4914 mono_acfg_unlock (llvm_acfg);
4924 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
4928 emit_llvm_file (MonoAotCompile *acfg)
4930 char *command, *opts;
4932 MonoJumpInfo *patch_info;
4935 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
4939 /* Compute the final size of the got */
4940 for (i = 0; i < acfg->nmethods; ++i) {
4941 if (acfg->cfgs [i]) {
4942 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
4943 if (patch_info->type != MONO_PATCH_INFO_NONE) {
4944 if (!is_plt_patch (patch_info))
4945 get_got_offset (acfg, patch_info);
4947 get_plt_entry (acfg, patch_info);
4953 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
4955 if (acfg->aot_opts.full_aot) {
4959 * Need to add the got entries used by the trampolines.
4960 * This is only a conservative approximation.
4962 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4963 /* For the generic + rgctx trampolines */
4964 acfg->final_got_size += 200;
4965 /* For the specific trampolines */
4966 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
4967 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
4972 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
4975 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
4976 * a lot of time, and doesn't seem to save much space.
4977 * The following optimizations cannot be enabled:
4979 * - 'jump-threading' changes our blockaddress references to int constants.
4980 * The opt list below was produced by taking the output of:
4981 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
4982 * then removing tailcallelim + the global opts, and adding a second gvn.
4984 opts = g_strdup ("-instcombine -simplifycfg");
4985 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");
4987 command = g_strdup_printf ("opt -f %s -o temp.opt.bc temp.bc", opts);
4988 printf ("Executing opt: %s\n", command);
4989 if (system (command) != 0) {
4995 if (!acfg->llc_args)
4996 acfg->llc_args = g_string_new ("");
4998 #if !LLVM_CHECK_VERSION(2, 8)
4999 /* LLVM 2.8 removed the -f flag ??? */
5000 g_string_append (acfg->llc_args, " -f");
5003 if (acfg->aot_opts.mtriple)
5004 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5006 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);
5008 printf ("Executing llc: %s\n", command);
5010 if (system (command) != 0) {
5017 emit_code (MonoAotCompile *acfg)
5021 char end_symbol [256];
5024 #if defined(TARGET_POWERPC64)
5025 sprintf (symbol, ".Lgot_addr");
5026 emit_section_change (acfg, ".text", 0);
5027 emit_alignment (acfg, 8);
5028 emit_label (acfg, symbol);
5029 emit_pointer (acfg, acfg->got_symbol);
5033 * This global symbol is used to compute the address of each method using the
5034 * code_offsets array. It is also used to compute the memory ranges occupied by
5035 * AOT code, so it must be equal to the address of the first emitted method.
5037 sprintf (symbol, "methods");
5038 emit_section_change (acfg, ".text", 0);
5039 emit_global (acfg, symbol, TRUE);
5040 emit_alignment (acfg, 8);
5042 for (i = 0; i < acfg->nmethods; ++i) {
5043 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
5044 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
5048 if (i == acfg->nmethods)
5049 /* No LLVM compiled methods */
5050 emit_label (acfg, symbol);
5052 emit_label (acfg, symbol);
5056 * Emit some padding so the local symbol for the first method doesn't have the
5057 * same address as 'methods'.
5059 #if defined(__default_codegen__)
5060 emit_zero_bytes (acfg, 16);
5061 #elif defined(__native_client_codegen__)
5063 const int kPaddingSize = 16;
5064 guint8 pad_buffer[kPaddingSize];
5065 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
5066 emit_bytes (acfg, pad_buffer, kPaddingSize);
5071 for (l = acfg->method_order; l != NULL; l = l->next) {
5075 i = GPOINTER_TO_UINT (l->data);
5077 cfg = acfg->cfgs [i];
5082 method = cfg->orig_method;
5084 /* Emit unbox trampoline */
5085 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
5086 char call_target [256];
5088 if (!method->wrapper_type && !method->is_inflated) {
5089 g_assert (method->token);
5090 sprintf (symbol, "ut_%d", mono_metadata_token_index (method->token) - 1);
5092 sprintf (symbol, "ut_e_%d", get_method_index (acfg, method));
5095 emit_section_change (acfg, ".text", 0);
5096 #ifdef __native_client_codegen__
5097 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5099 emit_global (acfg, symbol, TRUE);
5100 emit_label (acfg, symbol);
5102 sprintf (call_target, "%s", cfg->asm_symbol);
5104 arch_emit_unbox_trampoline (acfg, cfg->orig_method, call_target);
5107 if (cfg->compile_llvm)
5108 acfg->stats.llvm_count ++;
5110 emit_method_code (acfg, cfg);
5113 sprintf (symbol, "methods_end");
5114 emit_section_change (acfg, ".text", 0);
5115 emit_global (acfg, symbol, FALSE);
5116 emit_alignment (acfg, 8);
5117 emit_label (acfg, symbol);
5119 sprintf (symbol, "code_offsets");
5120 emit_section_change (acfg, RODATA_SECT, 1);
5121 emit_global (acfg, symbol, FALSE);
5122 emit_alignment (acfg, 8);
5123 emit_label (acfg, symbol);
5125 acfg->stats.offsets_size += acfg->nmethods * 4;
5127 sprintf (end_symbol, "methods");
5128 for (i = 0; i < acfg->nmethods; ++i) {
5129 if (acfg->cfgs [i]) {
5130 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
5132 emit_int32 (acfg, 0xffffffff);
5139 emit_info (MonoAotCompile *acfg)
5146 offsets = g_new0 (gint32, acfg->nmethods);
5148 for (l = acfg->method_order; l != NULL; l = l->next) {
5149 i = GPOINTER_TO_UINT (l->data);
5151 if (acfg->cfgs [i]) {
5152 emit_method_info (acfg, acfg->cfgs [i]);
5153 offsets [i] = acfg->cfgs [i]->method_info_offset;
5159 sprintf (symbol, "method_info_offsets");
5160 emit_section_change (acfg, RODATA_SECT, 1);
5161 emit_global (acfg, symbol, FALSE);
5162 emit_alignment (acfg, 8);
5163 emit_label (acfg, symbol);
5165 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5170 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
5172 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
5173 #define mix(a,b,c) { \
5174 a -= c; a ^= rot(c, 4); c += b; \
5175 b -= a; b ^= rot(a, 6); a += c; \
5176 c -= b; c ^= rot(b, 8); b += a; \
5177 a -= c; a ^= rot(c,16); c += b; \
5178 b -= a; b ^= rot(a,19); a += c; \
5179 c -= b; c ^= rot(b, 4); b += a; \
5181 #define final(a,b,c) { \
5182 c ^= b; c -= rot(b,14); \
5183 a ^= c; a -= rot(c,11); \
5184 b ^= a; b -= rot(a,25); \
5185 c ^= b; c -= rot(b,16); \
5186 a ^= c; a -= rot(c,4); \
5187 b ^= a; b -= rot(a,14); \
5188 c ^= b; c -= rot(b,24); \
5192 mono_aot_type_hash (MonoType *t1)
5194 guint hash = t1->type;
5196 hash |= t1->byref << 6; /* do not collide with t1->type values */
5198 case MONO_TYPE_VALUETYPE:
5199 case MONO_TYPE_CLASS:
5200 case MONO_TYPE_SZARRAY:
5201 /* check if the distribution is good enough */
5202 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
5204 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
5205 case MONO_TYPE_ARRAY:
5206 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
5207 case MONO_TYPE_GENERICINST:
5208 return ((hash << 5) - hash) ^ 0;
5214 * mono_aot_method_hash:
5216 * Return a hash code for methods which only depends on metadata.
5219 mono_aot_method_hash (MonoMethod *method)
5221 MonoMethodSignature *sig;
5225 guint32 *hashes_start, *hashes;
5227 MonoGenericInst *ginst = NULL;
5229 /* Similar to the hash in mono_method_get_imt_slot () */
5231 sig = mono_method_signature (method);
5233 if (method->is_inflated)
5234 ginst = ((MonoMethodInflated*)method)->context.method_inst;
5236 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
5237 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
5238 hashes = hashes_start;
5240 /* Some wrappers are assigned to random classes */
5241 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
5242 klass = method->klass;
5244 klass = mono_defaults.object_class;
5246 if (!method->wrapper_type) {
5247 char *full_name = mono_type_full_name (&klass->byval_arg);
5249 hashes [0] = mono_metadata_str_hash (full_name);
5253 hashes [0] = mono_metadata_str_hash (klass->name);
5254 hashes [1] = mono_metadata_str_hash (klass->name_space);
5256 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
5257 /* The method name includes a stringified pointer */
5260 hashes [2] = mono_metadata_str_hash (method->name);
5261 hashes [3] = method->wrapper_type;
5262 hashes [4] = mono_aot_type_hash (sig->ret);
5264 for (i = 0; i < sig->param_count; i++) {
5265 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
5268 for (i = 0; i < ginst->type_argc; ++i)
5269 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
5271 g_assert (hindex == hashes_count);
5273 /* Setup internal state */
5274 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
5276 /* Handle most of the hashes */
5277 while (hashes_count > 3) {
5286 /* Handle the last 3 hashes (all the case statements fall through) */
5287 switch (hashes_count) {
5288 case 3 : c += hashes [2];
5289 case 2 : b += hashes [1];
5290 case 1 : a += hashes [0];
5292 case 0: /* nothing left to add */
5296 free (hashes_start);
5305 * mono_aot_wrapper_name:
5307 * Return a string which uniqely identifies the given wrapper method.
5310 mono_aot_wrapper_name (MonoMethod *method)
5312 char *name, *tmpsig, *klass_desc;
5314 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
5316 switch (method->wrapper_type) {
5317 case MONO_WRAPPER_RUNTIME_INVOKE:
5318 if (!strcmp (method->name, "runtime_invoke_dynamic"))
5319 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
5321 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
5324 klass_desc = mono_type_full_name (&method->klass->byval_arg);
5325 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
5326 g_free (klass_desc);
5336 * mono_aot_get_array_helper_from_wrapper;
5338 * Get the helper method in Array called by an array wrapper method.
5341 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
5345 MonoGenericContext ctx;
5346 MonoType *args [16];
5347 char *mname, *iname, *s, *s2, *helper_name = NULL;
5349 prefix = "System.Collections.Generic";
5350 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
5351 s2 = strstr (s, "`1.");
5357 //printf ("X: %s %s\n", iname, mname);
5359 if (!strcmp (iname, "IList"))
5360 helper_name = g_strdup_printf ("InternalArray__%s", mname);
5362 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
5363 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
5365 g_free (helper_name);
5368 if (m->is_generic) {
5369 memset (&ctx, 0, sizeof (ctx));
5370 args [0] = &method->klass->element_class->byval_arg;
5371 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
5372 m = mono_class_inflate_generic_method (m, &ctx);
5378 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
5380 typedef struct HashEntry {
5381 guint32 key, value, index;
5382 struct HashEntry *next;
5386 * emit_extra_methods:
5388 * Emit methods which are not in the METHOD table, like wrappers.
5391 emit_extra_methods (MonoAotCompile *acfg)
5393 int i, table_size, buf_size;
5396 guint32 *info_offsets;
5399 HashEntry *entry, *new_entry;
5400 int nmethods, max_chain_length;
5403 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
5405 /* Emit method info */
5407 for (i = 0; i < acfg->extra_methods->len; ++i) {
5408 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5409 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5416 p = buf = g_malloc (buf_size);
5420 method = cfg->method_to_register;
5423 if (method->wrapper_type) {
5425 * We encode some wrappers using their name, since encoding them
5426 * directly would be difficult. This also avoids creating the wrapper
5427 * methods at runtime, since they are not needed anyway.
5429 switch (method->wrapper_type) {
5430 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5431 case MONO_WRAPPER_SYNCHRONIZED:
5432 /* encode_method_ref () can handle these */
5434 case MONO_WRAPPER_RUNTIME_INVOKE:
5435 if (mono_marshal_method_from_wrapper (method) != method && !strstr (method->name, "virtual"))
5436 /* Direct wrapper, encode normally */
5440 name = mono_aot_wrapper_name (method);
5446 encode_value (1, p, &p);
5447 encode_value (method->wrapper_type, p, &p);
5448 strcpy ((char*)p, name);
5449 p += strlen (name ) + 1;
5452 encode_value (0, p, &p);
5453 encode_method_ref (acfg, method, p, &p);
5456 g_assert ((p - buf) < buf_size);
5458 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5463 * Construct a chained hash table for mapping indexes in extra_method_info to
5466 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
5467 table = g_ptr_array_sized_new (table_size);
5468 for (i = 0; i < table_size; ++i)
5469 g_ptr_array_add (table, NULL);
5470 chain_lengths = g_new0 (int, table_size);
5471 max_chain_length = 0;
5472 for (i = 0; i < acfg->extra_methods->len; ++i) {
5473 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5474 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
5480 key = info_offsets [i];
5481 value = get_method_index (acfg, method);
5483 hash = mono_aot_method_hash (method) % table_size;
5485 chain_lengths [hash] ++;
5486 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
5488 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
5489 new_entry->key = key;
5490 new_entry->value = value;
5492 entry = g_ptr_array_index (table, hash);
5493 if (entry == NULL) {
5494 new_entry->index = hash;
5495 g_ptr_array_index (table, hash) = new_entry;
5498 entry = entry->next;
5500 entry->next = new_entry;
5501 new_entry->index = table->len;
5502 g_ptr_array_add (table, new_entry);
5506 //printf ("MAX: %d\n", max_chain_length);
5508 /* Emit the table */
5509 sprintf (symbol, "extra_method_table");
5510 emit_section_change (acfg, RODATA_SECT, 0);
5511 emit_global (acfg, symbol, FALSE);
5512 emit_alignment (acfg, 8);
5513 emit_label (acfg, symbol);
5515 emit_int32 (acfg, table_size);
5516 for (i = 0; i < table->len; ++i) {
5517 HashEntry *entry = g_ptr_array_index (table, i);
5519 if (entry == NULL) {
5520 emit_int32 (acfg, 0);
5521 emit_int32 (acfg, 0);
5522 emit_int32 (acfg, 0);
5524 //g_assert (entry->key > 0);
5525 emit_int32 (acfg, entry->key);
5526 emit_int32 (acfg, entry->value);
5528 emit_int32 (acfg, entry->next->index);
5530 emit_int32 (acfg, 0);
5535 * Emit a table reverse mapping method indexes to their index in extra_method_info.
5536 * This is used by mono_aot_find_jit_info ().
5538 sprintf (symbol, "extra_method_info_offsets");
5539 emit_section_change (acfg, RODATA_SECT, 0);
5540 emit_global (acfg, symbol, FALSE);
5541 emit_alignment (acfg, 8);
5542 emit_label (acfg, symbol);
5544 emit_int32 (acfg, acfg->extra_methods->len);
5545 for (i = 0; i < acfg->extra_methods->len; ++i) {
5546 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
5548 emit_int32 (acfg, get_method_index (acfg, method));
5549 emit_int32 (acfg, info_offsets [i]);
5554 emit_exception_info (MonoAotCompile *acfg)
5560 offsets = g_new0 (gint32, acfg->nmethods);
5561 for (i = 0; i < acfg->nmethods; ++i) {
5562 if (acfg->cfgs [i]) {
5563 emit_exception_debug_info (acfg, acfg->cfgs [i]);
5564 offsets [i] = acfg->cfgs [i]->ex_info_offset;
5570 sprintf (symbol, "ex_info_offsets");
5571 emit_section_change (acfg, RODATA_SECT, 1);
5572 emit_global (acfg, symbol, FALSE);
5573 emit_alignment (acfg, 8);
5574 emit_label (acfg, symbol);
5576 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
5581 emit_unwind_info (MonoAotCompile *acfg)
5587 * The unwind info contains a lot of duplicates so we emit each unique
5588 * entry once, and only store the offset from the start of the table in the
5592 sprintf (symbol, "unwind_info");
5593 emit_section_change (acfg, RODATA_SECT, 1);
5594 emit_alignment (acfg, 8);
5595 emit_label (acfg, symbol);
5596 emit_global (acfg, symbol, FALSE);
5598 for (i = 0; i < acfg->unwind_ops->len; ++i) {
5599 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
5600 guint8 *unwind_info;
5601 guint32 unwind_info_len;
5605 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
5608 encode_value (unwind_info_len, p, &p);
5609 emit_bytes (acfg, buf, p - buf);
5610 emit_bytes (acfg, unwind_info, unwind_info_len);
5612 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
5616 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
5619 sprintf (symbol, "mono_eh_frame_addr");
5620 emit_section_change (acfg, ".data", 0);
5621 emit_global (acfg, symbol, FALSE);
5622 emit_alignment (acfg, 8);
5623 emit_label (acfg, symbol);
5624 emit_pointer (acfg, "mono_eh_frame");
5629 emit_class_info (MonoAotCompile *acfg)
5635 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
5636 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
5637 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
5639 sprintf (symbol, "class_info_offsets");
5640 emit_section_change (acfg, RODATA_SECT, 1);
5641 emit_global (acfg, symbol, FALSE);
5642 emit_alignment (acfg, 8);
5643 emit_label (acfg, symbol);
5645 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
5649 typedef struct ClassNameTableEntry {
5650 guint32 token, index;
5651 struct ClassNameTableEntry *next;
5652 } ClassNameTableEntry;
5655 emit_class_name_table (MonoAotCompile *acfg)
5658 guint32 token, hash;
5663 ClassNameTableEntry *entry, *new_entry;
5666 * Construct a chained hash table for mapping class names to typedef tokens.
5668 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
5669 table = g_ptr_array_sized_new (table_size);
5670 for (i = 0; i < table_size; ++i)
5671 g_ptr_array_add (table, NULL);
5672 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
5673 token = MONO_TOKEN_TYPE_DEF | (i + 1);
5674 klass = mono_class_get (acfg->image, token);
5677 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
5678 hash = mono_metadata_str_hash (full_name) % table_size;
5681 /* FIXME: Allocate from the mempool */
5682 new_entry = g_new0 (ClassNameTableEntry, 1);
5683 new_entry->token = token;
5685 entry = g_ptr_array_index (table, hash);
5686 if (entry == NULL) {
5687 new_entry->index = hash;
5688 g_ptr_array_index (table, hash) = new_entry;
5691 entry = entry->next;
5693 entry->next = new_entry;
5694 new_entry->index = table->len;
5695 g_ptr_array_add (table, new_entry);
5699 /* Emit the table */
5700 sprintf (symbol, "class_name_table");
5701 emit_section_change (acfg, RODATA_SECT, 0);
5702 emit_global (acfg, symbol, FALSE);
5703 emit_alignment (acfg, 8);
5704 emit_label (acfg, symbol);
5706 /* FIXME: Optimize memory usage */
5707 g_assert (table_size < 65000);
5708 emit_int16 (acfg, table_size);
5709 g_assert (table->len < 65000);
5710 for (i = 0; i < table->len; ++i) {
5711 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
5713 if (entry == NULL) {
5714 emit_int16 (acfg, 0);
5715 emit_int16 (acfg, 0);
5717 emit_int16 (acfg, mono_metadata_token_index (entry->token));
5719 emit_int16 (acfg, entry->next->index);
5721 emit_int16 (acfg, 0);
5727 emit_image_table (MonoAotCompile *acfg)
5733 * The image table is small but referenced in a lot of places.
5734 * So we emit it at once, and reference its elements by an index.
5737 sprintf (symbol, "mono_image_table");
5738 emit_section_change (acfg, RODATA_SECT, 1);
5739 emit_global (acfg, symbol, FALSE);
5740 emit_alignment (acfg, 8);
5741 emit_label (acfg, symbol);
5743 emit_int32 (acfg, acfg->image_table->len);
5744 for (i = 0; i < acfg->image_table->len; i++) {
5745 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
5746 MonoAssemblyName *aname = &image->assembly->aname;
5748 /* FIXME: Support multi-module assemblies */
5749 g_assert (image->assembly->image == image);
5751 emit_string (acfg, image->assembly_name);
5752 emit_string (acfg, image->guid);
5753 emit_string (acfg, aname->culture ? aname->culture : "");
5754 emit_string (acfg, (const char*)aname->public_key_token);
5756 emit_alignment (acfg, 8);
5757 emit_int32 (acfg, aname->flags);
5758 emit_int32 (acfg, aname->major);
5759 emit_int32 (acfg, aname->minor);
5760 emit_int32 (acfg, aname->build);
5761 emit_int32 (acfg, aname->revision);
5766 emit_got_info (MonoAotCompile *acfg)
5769 int i, first_plt_got_patch, buf_size;
5771 guint32 *got_info_offsets;
5773 /* Add the patches needed by the PLT to the GOT */
5774 acfg->plt_got_offset_base = acfg->got_offset;
5775 first_plt_got_patch = acfg->got_patches->len;
5776 for (i = 1; i < acfg->plt_offset; ++i) {
5777 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5779 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
5782 acfg->got_offset += acfg->plt_offset;
5786 * - optimize offsets table.
5787 * - reduce number of exported symbols.
5788 * - emit info for a klass only once.
5789 * - determine when a method uses a GOT slot which is guaranteed to be already
5791 * - clean up and document the code.
5792 * - use String.Empty in class libs.
5795 /* Encode info required to decode shared GOT entries */
5796 buf_size = acfg->got_patches->len * 128;
5797 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
5798 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
5799 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
5801 if (acfg->plt_offset)
5802 acfg->plt_got_info_offsets [0] = 0;
5803 for (i = 0; i < acfg->got_patches->len; ++i) {
5804 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
5808 encode_value (ji->type, p, &p);
5809 encode_patch (acfg, ji, p, &p);
5811 g_assert (p - buf <= buf_size);
5812 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
5814 if (i >= first_plt_got_patch)
5815 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
5816 acfg->stats.got_info_size += p - buf;
5819 /* Emit got_info_offsets table */
5820 sprintf (symbol, "got_info_offsets");
5821 emit_section_change (acfg, RODATA_SECT, 1);
5822 emit_global (acfg, symbol, FALSE);
5823 emit_alignment (acfg, 8);
5824 emit_label (acfg, symbol);
5826 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
5827 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
5831 emit_got (MonoAotCompile *acfg)
5836 /* Don't make GOT global so accesses to it don't need relocations */
5837 sprintf (symbol, "%s", acfg->got_symbol);
5838 emit_section_change (acfg, ".bss", 0);
5839 emit_alignment (acfg, 8);
5840 emit_local_symbol (acfg, symbol, "got_end", FALSE);
5841 emit_label (acfg, symbol);
5842 if (acfg->got_offset > 0)
5843 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
5845 sprintf (symbol, "got_end");
5846 emit_label (acfg, symbol);
5849 sprintf (symbol, "mono_aot_got_addr");
5850 emit_section_change (acfg, ".data", 0);
5851 emit_global (acfg, symbol, FALSE);
5852 emit_alignment (acfg, 8);
5853 emit_label (acfg, symbol);
5854 emit_pointer (acfg, acfg->got_symbol);
5857 typedef struct GlobalsTableEntry {
5858 guint32 value, index;
5859 struct GlobalsTableEntry *next;
5860 } GlobalsTableEntry;
5863 emit_globals_table (MonoAotCompile *acfg)
5869 GlobalsTableEntry *entry, *new_entry;
5872 * Construct a chained hash table for mapping global names to their index in
5873 * the globals table.
5875 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
5876 table = g_ptr_array_sized_new (table_size);
5877 for (i = 0; i < table_size; ++i)
5878 g_ptr_array_add (table, NULL);
5879 for (i = 0; i < acfg->globals->len; ++i) {
5880 char *name = g_ptr_array_index (acfg->globals, i);
5882 hash = mono_metadata_str_hash (name) % table_size;
5884 /* FIXME: Allocate from the mempool */
5885 new_entry = g_new0 (GlobalsTableEntry, 1);
5886 new_entry->value = i;
5888 entry = g_ptr_array_index (table, hash);
5889 if (entry == NULL) {
5890 new_entry->index = hash;
5891 g_ptr_array_index (table, hash) = new_entry;
5894 entry = entry->next;
5896 entry->next = new_entry;
5897 new_entry->index = table->len;
5898 g_ptr_array_add (table, new_entry);
5902 /* Emit the table */
5903 sprintf (symbol, ".Lglobals_hash");
5904 emit_section_change (acfg, RODATA_SECT, 0);
5905 emit_alignment (acfg, 8);
5906 emit_label (acfg, symbol);
5908 /* FIXME: Optimize memory usage */
5909 g_assert (table_size < 65000);
5910 emit_int16 (acfg, table_size);
5911 for (i = 0; i < table->len; ++i) {
5912 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
5914 if (entry == NULL) {
5915 emit_int16 (acfg, 0);
5916 emit_int16 (acfg, 0);
5918 emit_int16 (acfg, entry->value + 1);
5920 emit_int16 (acfg, entry->next->index);
5922 emit_int16 (acfg, 0);
5926 /* Emit the names */
5927 for (i = 0; i < acfg->globals->len; ++i) {
5928 char *name = g_ptr_array_index (acfg->globals, i);
5930 sprintf (symbol, "name_%d", i);
5931 emit_section_change (acfg, RODATA_SECT, 1);
5932 emit_label (acfg, symbol);
5933 emit_string (acfg, name);
5936 /* Emit the globals table */
5937 sprintf (symbol, ".Lglobals");
5938 emit_section_change (acfg, ".data", 0);
5939 /* This is not a global, since it is accessed by the init function */
5940 emit_alignment (acfg, 8);
5941 emit_label (acfg, symbol);
5943 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
5944 emit_pointer (acfg, symbol);
5946 for (i = 0; i < acfg->globals->len; ++i) {
5947 char *name = g_ptr_array_index (acfg->globals, i);
5949 sprintf (symbol, "name_%d", i);
5950 emit_pointer (acfg, symbol);
5952 sprintf (symbol, "%s", name);
5953 emit_pointer (acfg, symbol);
5955 /* Null terminate the table */
5956 emit_int32 (acfg, 0);
5957 emit_int32 (acfg, 0);
5961 emit_globals (MonoAotCompile *acfg)
5965 emit_string_symbol (acfg, "mono_assembly_guid" , acfg->image->guid);
5967 emit_string_symbol (acfg, "mono_aot_version", MONO_AOT_FILE_VERSION);
5969 if (acfg->aot_opts.bind_to_runtime_version) {
5970 build_info = mono_get_runtime_build_info ();
5971 emit_string_symbol (acfg, "mono_runtime_version", build_info);
5972 g_free (build_info);
5974 emit_string_symbol (acfg, "mono_runtime_version", "");
5978 * When static linking, we emit a global which will point to the symbol table.
5980 if (acfg->aot_opts.static_link) {
5984 /* Emit a string holding the assembly name */
5985 emit_string_symbol (acfg, "mono_aot_assembly_name", acfg->image->assembly->aname.name);
5987 emit_globals_table (acfg);
5990 * Emit a global symbol which can be passed by an embedding app to
5991 * mono_aot_register_module ().
5993 #if defined(__MACH__) && !defined(__native_client_codegen__)
5994 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5996 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
5999 /* Get rid of characters which cannot occur in symbols */
6001 for (p = symbol; *p; ++p) {
6002 if (!(isalnum (*p) || *p == '_'))
6005 acfg->static_linking_symbol = g_strdup (symbol);
6006 emit_global_inner (acfg, symbol, FALSE);
6007 emit_alignment (acfg, 8);
6008 emit_label (acfg, symbol);
6009 sprintf (symbol, "%sglobals", acfg->temp_prefix);
6010 emit_pointer (acfg, symbol);
6015 emit_autoreg (MonoAotCompile *acfg)
6020 * Emit a function into the .ctor section which will be called by the ELF
6021 * loader to register this module with the runtime.
6023 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6026 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6028 arch_emit_autoreg (acfg, symbol);
6034 emit_mem_end (MonoAotCompile *acfg)
6038 sprintf (symbol, "mem_end");
6039 emit_section_change (acfg, ".text", 1);
6040 emit_global (acfg, symbol, FALSE);
6041 emit_alignment (acfg, 8);
6042 emit_label (acfg, symbol);
6046 * Emit a structure containing all the information not stored elsewhere.
6049 emit_file_info (MonoAotCompile *acfg)
6054 const char *gc_name;
6057 * The managed allocators are GC specific, so can't use an AOT image created by one GC
6060 gc_name = mono_gc_get_gc_name ();
6061 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
6063 sprintf (symbol, "mono_aot_file_info");
6064 emit_section_change (acfg, ".data", 0);
6065 emit_alignment (acfg, 8);
6066 emit_label (acfg, symbol);
6067 emit_global (acfg, symbol, FALSE);
6069 /* The data emitted here must match MonoAotFileInfo. */
6070 emit_int32 (acfg, acfg->plt_got_offset_base);
6071 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6072 emit_int32 (acfg, acfg->plt_offset);
6073 emit_int32 (acfg, acfg->nmethods);
6074 emit_int32 (acfg, acfg->flags);
6075 emit_int32 (acfg, acfg->opts);
6076 emit_int32 (acfg, gc_name_offset);
6078 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6079 emit_int32 (acfg, acfg->num_trampolines [i]);
6080 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6081 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
6082 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6083 emit_int32 (acfg, acfg->trampoline_size [i]);
6087 emit_blob (MonoAotCompile *acfg)
6091 sprintf (symbol, "blob");
6092 emit_section_change (acfg, RODATA_SECT, 1);
6093 emit_global (acfg, symbol, FALSE);
6094 emit_alignment (acfg, 8);
6095 emit_label (acfg, symbol);
6097 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
6101 emit_dwarf_info (MonoAotCompile *acfg)
6103 #ifdef EMIT_DWARF_INFO
6105 char symbol [128], symbol2 [128];
6107 /* DIEs for methods */
6108 for (i = 0; i < acfg->nmethods; ++i) {
6109 MonoCompile *cfg = acfg->cfgs [i];
6114 // FIXME: LLVM doesn't define .Lme_...
6115 if (cfg->compile_llvm)
6118 sprintf (symbol, "%s", cfg->asm_symbol);
6119 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
6121 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 ()));
6127 collect_methods (MonoAotCompile *acfg)
6130 MonoImage *image = acfg->image;
6132 /* Collect methods */
6133 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
6135 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
6137 method = mono_get_method (acfg->image, token, NULL);
6140 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
6144 /* Load all methods eagerly to skip the slower lazy loading code */
6145 mono_class_setup_methods (method->klass);
6147 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6148 /* Compile the wrapper instead */
6149 /* We do this here instead of add_wrappers () because it is easy to do it here */
6150 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
6154 /* FIXME: Some mscorlib methods don't have debug info */
6156 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
6157 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6158 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6159 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
6160 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
6161 if (!mono_debug_lookup_method (method)) {
6162 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
6169 /* Since we add the normal methods first, their index will be equal to their zero based token index */
6170 add_method_with_index (acfg, method, i, FALSE);
6171 acfg->method_index ++;
6174 add_generic_instances (acfg);
6176 if (acfg->aot_opts.full_aot)
6177 add_wrappers (acfg);
6181 compile_methods (MonoAotCompile *acfg)
6185 if (acfg->aot_opts.nthreads > 0) {
6190 gpointer *user_data;
6191 MonoMethod **methods;
6193 methods_len = acfg->methods->len;
6195 len = acfg->methods->len / acfg->aot_opts.nthreads;
6198 * Partition the list of methods into fragments, and hand it to threads to
6201 threads = g_ptr_array_new ();
6202 /* Make a copy since acfg->methods is modified by compile_method () */
6203 methods = g_new0 (MonoMethod*, methods_len);
6204 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
6205 for (i = 0; i < methods_len; ++i)
6206 methods [i] = g_ptr_array_index (acfg->methods, i);
6208 while (i < methods_len) {
6209 frag = g_ptr_array_new ();
6210 for (j = 0; j < len; ++j) {
6211 if (i < methods_len) {
6212 g_ptr_array_add (frag, methods [i]);
6217 user_data = g_new0 (gpointer, 3);
6218 user_data [0] = mono_domain_get ();
6219 user_data [1] = acfg;
6220 user_data [2] = frag;
6222 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
6223 g_ptr_array_add (threads, handle);
6227 for (i = 0; i < threads->len; ++i) {
6228 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
6234 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
6235 for (i = methods_len; i < acfg->methods->len; ++i) {
6236 /* This can new methods to acfg->methods */
6237 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
6242 compile_asm (MonoAotCompile *acfg)
6244 char *command, *objfile;
6245 char *outfile_name, *tmp_outfile_name;
6246 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
6248 #if defined(TARGET_AMD64)
6249 #define AS_OPTIONS "--64"
6250 #elif defined(TARGET_POWERPC64)
6251 #define AS_OPTIONS "-a64 -mppc64"
6252 #define LD_OPTIONS "-m elf64ppc"
6253 #elif defined(sparc) && SIZEOF_VOID_P == 8
6254 #define AS_OPTIONS "-xarch=v9"
6255 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6256 #define AS_OPTIONS "-arch i386 -W"
6258 #define AS_OPTIONS ""
6261 #ifdef __native_client_codegen__
6262 #if defined(TARGET_AMD64)
6263 #define AS_NAME "nacl64-as"
6265 #define AS_NAME "nacl-as"
6268 #define AS_NAME "as"
6272 #define LD_OPTIONS ""
6275 #define EH_LD_OPTIONS ""
6277 if (acfg->aot_opts.asm_only) {
6278 printf ("Output file: '%s'.\n", acfg->tmpfname);
6279 if (acfg->aot_opts.static_link)
6280 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6284 if (acfg->aot_opts.static_link) {
6285 if (acfg->aot_opts.outfile)
6286 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6288 objfile = g_strdup_printf ("%s.o", acfg->image->name);
6290 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
6292 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);
6293 printf ("Executing the native assembler: %s\n", command);
6294 if (system (command) != 0) {
6302 if (acfg->aot_opts.static_link) {
6303 printf ("Output file: '%s'.\n", objfile);
6304 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
6309 if (acfg->aot_opts.outfile)
6310 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6312 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6314 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6317 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6318 #elif defined(__ppc__) && defined(__MACH__)
6319 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6320 #elif defined(HOST_WIN32)
6321 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6322 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
6323 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
6325 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
6327 printf ("Executing the native linker: %s\n", command);
6328 if (system (command) != 0) {
6329 g_free (tmp_outfile_name);
6330 g_free (outfile_name);
6338 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
6339 printf ("Stripping the binary: %s\n", com);
6343 #if defined(TARGET_ARM) && !defined(__MACH__)
6345 * gas generates 'mapping symbols' each time code and data is mixed, which
6346 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
6348 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
6349 printf ("Stripping the binary: %s\n", command);
6350 if (system (command) != 0) {
6351 g_free (tmp_outfile_name);
6352 g_free (outfile_name);
6359 rename (tmp_outfile_name, outfile_name);
6361 g_free (tmp_outfile_name);
6362 g_free (outfile_name);
6365 if (acfg->aot_opts.save_temps)
6366 printf ("Retained input file.\n");
6368 unlink (acfg->tmpfname);
6373 static MonoAotCompile*
6374 acfg_create (MonoAssembly *ass, guint32 opts)
6376 MonoImage *image = ass->image;
6377 MonoAotCompile *acfg;
6380 acfg = g_new0 (MonoAotCompile, 1);
6381 acfg->methods = g_ptr_array_new ();
6382 acfg->method_indexes = g_hash_table_new (NULL, NULL);
6383 acfg->method_depth = g_hash_table_new (NULL, NULL);
6384 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
6385 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6386 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6387 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
6388 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6389 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
6390 acfg->got_patches = g_ptr_array_new ();
6391 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
6392 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
6393 acfg->image_hash = g_hash_table_new (NULL, NULL);
6394 acfg->image_table = g_ptr_array_new ();
6395 acfg->globals = g_ptr_array_new ();
6396 acfg->image = image;
6398 acfg->mempool = mono_mempool_new ();
6399 acfg->extra_methods = g_ptr_array_new ();
6400 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
6401 acfg->unwind_ops = g_ptr_array_new ();
6402 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
6403 InitializeCriticalSection (&acfg->mutex);
6409 acfg_free (MonoAotCompile *acfg)
6413 img_writer_destroy (acfg->w);
6414 for (i = 0; i < acfg->nmethods; ++i)
6416 g_free (acfg->cfgs [i]);
6417 g_free (acfg->cfgs);
6418 g_free (acfg->static_linking_symbol);
6419 g_free (acfg->got_symbol);
6420 g_free (acfg->plt_symbol);
6421 g_ptr_array_free (acfg->methods, TRUE);
6422 g_ptr_array_free (acfg->got_patches, TRUE);
6423 g_ptr_array_free (acfg->image_table, TRUE);
6424 g_ptr_array_free (acfg->globals, TRUE);
6425 g_ptr_array_free (acfg->unwind_ops, TRUE);
6426 g_hash_table_destroy (acfg->method_indexes);
6427 g_hash_table_destroy (acfg->method_depth);
6428 g_hash_table_destroy (acfg->plt_offset_to_entry);
6429 g_hash_table_destroy (acfg->patch_to_plt_entry);
6430 g_hash_table_destroy (acfg->patch_to_got_offset);
6431 g_hash_table_destroy (acfg->method_to_cfg);
6432 g_hash_table_destroy (acfg->token_info_hash);
6433 g_hash_table_destroy (acfg->image_hash);
6434 g_hash_table_destroy (acfg->unwind_info_offsets);
6435 g_hash_table_destroy (acfg->method_label_hash);
6436 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
6437 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
6438 g_free (acfg->patch_to_got_offset_by_type);
6439 mono_mempool_destroy (acfg->mempool);
6444 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
6446 MonoImage *image = ass->image;
6448 MonoAotCompile *acfg;
6449 char *outfile_name, *tmp_outfile_name, *p;
6453 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
6455 acfg = acfg_create (ass, opts);
6457 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
6458 acfg->aot_opts.write_symbols = TRUE;
6459 acfg->aot_opts.ntrampolines = 1024;
6460 acfg->aot_opts.nrgctx_trampolines = 1024;
6461 acfg->aot_opts.nimt_trampolines = 128;
6463 mono_aot_parse_options (aot_options, &acfg->aot_opts);
6465 if (acfg->aot_opts.static_link)
6466 acfg->aot_opts.autoreg = TRUE;
6468 //acfg->aot_opts.print_skipped_methods = TRUE;
6470 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
6471 if (acfg->aot_opts.full_aot) {
6472 printf ("--aot=full is not supported on this platform.\n");
6477 if (acfg->aot_opts.static_link)
6478 acfg->aot_opts.asm_writer = TRUE;
6480 if (acfg->aot_opts.soft_debug) {
6481 MonoDebugOptions *opt = mini_get_debug_options ();
6483 opt->mdb_optimizations = TRUE;
6484 opt->gen_seq_points = TRUE;
6486 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
6487 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
6490 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
6493 if (mono_use_llvm) {
6495 acfg->aot_opts.asm_writer = TRUE;
6496 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
6499 if (acfg->aot_opts.full_aot)
6500 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
6502 load_profile_files (acfg);
6504 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
6505 #ifdef MONO_ARCH_HAVE_STATIC_RGCTX_TRAMPOLINE
6506 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
6508 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
6510 acfg->got_symbol_base = g_strdup_printf ("%smono_aot_%s_got", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
6511 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
6513 /* Get rid of characters which cannot occur in symbols */
6514 for (p = acfg->got_symbol_base; *p; ++p) {
6515 if (!(isalnum (*p) || *p == '_'))
6518 for (p = acfg->plt_symbol; *p; ++p) {
6519 if (!(isalnum (*p) || *p == '_'))
6523 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
6526 * The prefix LLVM likes to put in front of symbol names on darwin.
6527 * The mach-os specs require this for globals, but LLVM puts them in front of all
6528 * symbols. We need to handle this, since we need to refer to LLVM generated
6531 acfg->llvm_label_prefix = "";
6535 acfg->method_index = 1;
6537 collect_methods (acfg);
6539 acfg->cfgs_size = acfg->methods->len + 32;
6540 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
6542 /* PLT offset 0 is reserved for the PLT trampoline */
6543 acfg->plt_offset = 1;
6548 mono_llvm_create_aot_module (acfg->got_symbol_base);
6552 /* GOT offset 0 is reserved for the address of the current assembly */
6556 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6557 ji->type = MONO_PATCH_INFO_IMAGE;
6558 ji->data.image = acfg->image;
6560 get_got_offset (acfg, ji);
6562 /* Slot 1 is reserved for the mscorlib got addr */
6563 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6564 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
6565 get_got_offset (acfg, ji);
6567 /* This is very common */
6568 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
6569 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
6570 get_got_offset (acfg, ji);
6575 compile_methods (acfg);
6579 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
6585 if (acfg->aot_opts.asm_only) {
6586 if (acfg->aot_opts.outfile)
6587 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6589 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6591 acfg->tmpfname = g_strdup ("temp.s");
6594 emit_llvm_file (acfg);
6598 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
6599 if (acfg->aot_opts.outfile)
6600 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6602 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
6605 * Can't use g_file_open_tmp () as it will be deleted at exit, and
6606 * it might be in another file system so the rename () won't work.
6608 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
6610 acfg->fp = fopen (tmp_outfile_name, "w");
6612 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
6616 acfg->w = img_writer_create (acfg->fp, TRUE);
6617 acfg->use_bin_writer = TRUE;
6620 /* Append to the .s file created by llvm */
6621 /* FIXME: Use multiple files instead */
6622 acfg->fp = fopen (acfg->tmpfname, "a+");
6624 if (acfg->aot_opts.asm_only) {
6625 if (acfg->aot_opts.outfile)
6626 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
6628 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
6629 acfg->fp = fopen (acfg->tmpfname, "w+");
6631 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
6632 acfg->fp = fdopen (i, "w+");
6634 g_assert (acfg->fp);
6636 acfg->w = img_writer_create (acfg->fp, FALSE);
6638 tmp_outfile_name = NULL;
6639 outfile_name = NULL;
6642 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
6644 /* Compute symbols for methods */
6645 for (i = 0; i < acfg->nmethods; ++i) {
6646 if (acfg->cfgs [i]) {
6647 MonoCompile *cfg = acfg->cfgs [i];
6648 int method_index = get_method_index (acfg, cfg->orig_method);
6650 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
6654 if (!acfg->aot_opts.nodebug)
6655 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
6657 img_writer_emit_start (acfg->w);
6660 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
6666 emit_extra_methods (acfg);
6668 emit_trampolines (acfg);
6670 emit_class_name_table (acfg);
6672 emit_got_info (acfg);
6674 emit_exception_info (acfg);
6676 emit_unwind_info (acfg);
6678 emit_class_info (acfg);
6682 emit_image_table (acfg);
6686 emit_file_info (acfg);
6690 emit_globals (acfg);
6692 emit_autoreg (acfg);
6695 emit_dwarf_info (acfg);
6696 mono_dwarf_writer_close (acfg->dwarf);
6699 emit_mem_end (acfg);
6703 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
6706 g_assert (acfg->got_offset <= acfg->final_got_size);
6708 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);
6711 res = img_writer_emit_writeout (acfg->w);
6716 if (acfg->use_bin_writer) {
6717 int err = rename (tmp_outfile_name, outfile_name);
6720 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
6724 res = compile_asm (acfg);
6731 acfg->stats.link_time = TV_ELAPSED (atv, btv);
6733 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);
6734 if (acfg->stats.genericcount)
6735 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
6736 if (acfg->stats.abscount)
6737 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
6738 if (acfg->stats.lmfcount)
6739 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
6740 if (acfg->stats.ocount)
6741 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
6743 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
6744 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);
6745 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
6747 if (acfg->aot_opts.stats) {
6750 printf ("GOT slot distribution:\n");
6751 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
6752 if (acfg->stats.got_slot_types [i])
6753 printf ("\t%s: %d\n", get_patch_name (i), acfg->stats.got_slot_types [i]);
6756 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);
6768 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)