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.
9 * Copyright 2003-2011 Novell, Inc
10 * Copyright 2011 Xamarin Inc (http://www.xamarin.com)
13 /* Remaining AOT-only work:
14 * - optimize the trampolines, generate more code in the arch files.
15 * - make things more consistent with how elf works, for example, use ELF
17 * Remaining generics sharing work:
18 * - optimize the size of the data which is encoded.
19 * - optimize the runtime loading of data:
20 * - the trampoline code calls mono_jit_info_table_find () to find the rgctx,
21 * which loads the debugging+exception handling info for the method. This is a
22 * huge waste of time and code, since the rgctx structure is currently empty.
23 * - every shared method has a MonoGenericJitInfo structure which is only really
24 * used for handling catch clauses with open types, not a very common use case.
27 #include <sys/types.h>
48 #include <mono/metadata/tabledefs.h>
49 #include <mono/metadata/class.h>
50 #include <mono/metadata/object.h>
51 #include <mono/metadata/tokentype.h>
52 #include <mono/metadata/appdomain.h>
53 #include <mono/metadata/debug-helpers.h>
54 #include <mono/metadata/assembly.h>
55 #include <mono/metadata/metadata-internals.h>
56 #include <mono/metadata/marshal.h>
57 #include <mono/metadata/gc-internal.h>
58 #include <mono/metadata/monitor.h>
59 #include <mono/metadata/mempool-internals.h>
60 #include <mono/metadata/mono-endian.h>
61 #include <mono/metadata/threads-types.h>
62 #include <mono/utils/mono-logger-internal.h>
63 #include <mono/utils/mono-compiler.h>
64 #include <mono/utils/mono-time.h>
65 #include <mono/utils/mono-mmap.h>
68 #include "image-writer.h"
69 #include "dwarfwriter.h"
71 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
73 #if defined(__linux__) || defined(__native_client_codegen__)
74 #define RODATA_SECT ".rodata"
76 #define RODATA_SECT ".text"
79 #define TV_DECLARE(name) gint64 name
80 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
81 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
84 #define SHARED_EXT ".dll"
85 #elif defined(__ppc__) && defined(__APPLE__)
86 #define SHARED_EXT ".dylib"
87 #elif defined(__APPLE__) && defined(TARGET_X86) && !defined(__native_client_codegen__)
88 #define SHARED_EXT ".dylib"
90 #define SHARED_EXT ".so"
93 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
94 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
95 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
97 /* predefined values for static readonly fields without needed to run the .cctor */
98 typedef struct _ReadOnlyValue ReadOnlyValue;
99 struct _ReadOnlyValue {
102 int type; /* to be used later for typechecking to prevent user errors */
111 static ReadOnlyValue *readonly_values = NULL;
113 typedef struct MonoAotOptions {
116 gboolean write_symbols;
117 gboolean metadata_only;
118 gboolean bind_to_runtime_version;
121 gboolean static_link;
128 int nrgctx_trampolines;
129 int nimt_trampolines;
130 gboolean print_skipped_methods;
138 typedef struct MonoAotStats {
139 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
140 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
141 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
142 int got_slots, offsets_size;
143 int got_slot_types [MONO_PATCH_INFO_NONE];
144 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
145 int jit_time, gen_time, link_time;
148 typedef struct MonoAotCompile {
151 GHashTable *method_indexes;
152 GHashTable *method_depth;
155 GHashTable *patch_to_plt_entry;
156 GHashTable *plt_offset_to_entry;
157 GHashTable *patch_to_got_offset;
158 GHashTable **patch_to_got_offset_by_type;
159 GPtrArray *got_patches;
160 GHashTable *image_hash;
161 GHashTable *method_to_cfg;
162 GHashTable *token_info_hash;
163 GPtrArray *extra_methods;
164 GPtrArray *image_table;
166 GPtrArray *method_order;
167 GHashTable *export_names;
168 /* Maps MonoClass* -> blob offset */
169 GHashTable *klass_blob_hash;
170 /* Maps MonoMethod* -> blob offset */
171 GHashTable *method_blob_hash;
172 guint32 *plt_got_info_offsets;
173 guint32 got_offset, plt_offset, plt_got_offset_base;
174 guint32 final_got_size;
175 /* Number of GOT entries reserved for trampolines */
176 guint32 num_trampoline_got_entries;
178 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
179 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
180 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
182 MonoAotOptions aot_opts;
185 MonoMemPool *mempool;
188 char *static_linking_symbol;
189 CRITICAL_SECTION mutex;
190 gboolean use_bin_writer;
192 MonoDwarfWriter *dwarf;
196 GHashTable *unwind_info_offsets;
197 GPtrArray *unwind_ops;
198 guint32 unwind_info_offset;
199 char *got_symbol_base;
202 GHashTable *method_label_hash;
203 const char *temp_prefix;
204 const char *llvm_label_prefix;
205 guint32 label_generator;
207 MonoAotFileFlags flags;
208 MonoDynamicStream blob;
209 MonoClass **typespec_classes;
212 char *assembly_name_sym;
213 GHashTable *plt_entry_debug_sym_cache;
214 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
215 GHashTable *ginst_hash;
220 char *symbol, *llvm_symbol, *debug_sym;
222 gboolean jit_used, llvm_used;
225 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
226 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
228 /* This points to the current acfg in LLVM mode */
229 static MonoAotCompile *llvm_acfg;
231 #ifdef HAVE_ARRAY_ELEM_INIT
232 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
233 #define MSGSTRFIELD1(line) str##line
234 static const struct msgstr_t {
235 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
236 #include "patch-info.h"
239 #define PATCH_INFO(a,b) b,
240 #include "patch-info.h"
243 static const gint16 opidx [] = {
244 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
245 #include "patch-info.h"
249 static G_GNUC_UNUSED const char*
250 get_patch_name (int info)
252 return (const char*)&opstr + opidx [info];
256 #define PATCH_INFO(a,b) b,
257 static const char* const
258 patch_types [MONO_PATCH_INFO_NUM + 1] = {
259 #include "patch-info.h"
263 static G_GNUC_UNUSED const char*
264 get_patch_name (int info)
266 return patch_types [info];
272 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
274 /* Wrappers around the image writer functions */
277 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
279 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
283 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
285 img_writer_emit_push_section (acfg->w, section_name, subsection);
289 emit_pop_section (MonoAotCompile *acfg)
291 img_writer_emit_pop_section (acfg->w);
295 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
297 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
301 emit_label (MonoAotCompile *acfg, const char *name)
303 img_writer_emit_label (acfg->w, name);
307 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
309 img_writer_emit_bytes (acfg->w, buf, size);
313 emit_string (MonoAotCompile *acfg, const char *value)
315 img_writer_emit_string (acfg->w, value);
319 emit_line (MonoAotCompile *acfg)
321 img_writer_emit_line (acfg->w);
325 emit_alignment (MonoAotCompile *acfg, int size)
327 img_writer_emit_alignment (acfg->w, size);
331 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
333 img_writer_emit_pointer_unaligned (acfg->w, target);
337 emit_pointer (MonoAotCompile *acfg, const char *target)
339 img_writer_emit_pointer (acfg->w, target);
343 emit_int16 (MonoAotCompile *acfg, int value)
345 img_writer_emit_int16 (acfg->w, value);
349 emit_int32 (MonoAotCompile *acfg, int value)
351 img_writer_emit_int32 (acfg->w, value);
355 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
357 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
361 emit_zero_bytes (MonoAotCompile *acfg, int num)
363 img_writer_emit_zero_bytes (acfg->w, num);
367 emit_byte (MonoAotCompile *acfg, guint8 val)
369 img_writer_emit_byte (acfg->w, val);
372 #ifdef __native_client_codegen__
374 emit_nacl_call_alignment (MonoAotCompile *acfg)
376 img_writer_emit_nacl_call_alignment (acfg->w);
380 static G_GNUC_UNUSED void
381 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
383 img_writer_emit_global (acfg->w, name, func);
387 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
389 if (acfg->aot_opts.no_dlsym) {
390 g_ptr_array_add (acfg->globals, g_strdup (name));
391 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
393 img_writer_emit_global (acfg->w, name, func);
398 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
400 img_writer_emit_symbol_size (acfg->w, name, end_label);
404 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
406 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
408 /* On apple, all symbols need to be aligned to avoid warnings from ld */
409 emit_alignment (acfg, 4);
411 img_writer_emit_label (acfg->w, name);
412 img_writer_emit_string (acfg->w, value);
415 static G_GNUC_UNUSED void
416 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
419 guint8 b = value & 0x7f;
421 if (value != 0) /* more bytes to come */
427 static G_GNUC_UNUSED void
428 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
431 gboolean negative = (value < 0);
438 /* the following is unnecessary if the
439 * implementation of >>= uses an arithmetic rather
440 * than logical shift for a signed left operand
444 value |= - ((gint64)1 <<(size - 7));
445 /* sign bit of byte is second high order bit (0x40) */
446 if ((value == 0 && !(byte & 0x40)) ||
447 (value == -1 && (byte & 0x40)))
451 emit_byte (acfg, byte);
455 static G_GNUC_UNUSED void
456 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
461 guint8 b = value & 0x7f;
463 if (value != 0) /* more bytes to come */
471 static G_GNUC_UNUSED void
472 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
475 gboolean negative = (value < 0);
483 /* the following is unnecessary if the
484 * implementation of >>= uses an arithmetic rather
485 * than logical shift for a signed left operand
489 value |= - (1 <<(size - 7));
490 /* sign bit of byte is second high order bit (0x40) */
491 if ((value == 0 && !(byte & 0x40)) ||
492 (value == -1 && (byte & 0x40)))
502 /* ARCHITECTURE SPECIFIC CODE */
504 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
505 #define EMIT_DWARF_INFO 1
508 #if defined(TARGET_ARM)
509 #define AOT_FUNC_ALIGNMENT 4
511 #define AOT_FUNC_ALIGNMENT 16
513 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
514 #undef AOT_FUNC_ALIGNMENT
515 #define AOT_FUNC_ALIGNMENT 32
518 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
519 #define PPC_LD_OP "ld"
520 #define PPC_LDX_OP "ldx"
522 #define PPC_LD_OP "lwz"
523 #define PPC_LDX_OP "lwzx"
527 #define AOT_TARGET_STR "AMD64"
532 #define AOT_TARGET_STR "ARM (MACH)"
534 #define AOT_TARGET_STR "ARM (!MACH)"
538 #ifdef TARGET_POWERPC64
539 #ifdef __mono_ilp32__
540 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
542 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
545 #ifdef TARGET_POWERPC
546 #ifdef __mono_ilp32__
547 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
549 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
556 #define AOT_TARGET_STR "X86 (WIN32)"
557 #elif defined(__native_client_codegen__)
558 #define AOT_TARGET_STR "X86 (native client codegen)"
560 #define AOT_TARGET_STR "X86 (!native client codegen)"
564 #ifndef AOT_TARGET_STR
565 #define AOT_TARGET_STR ""
569 arch_init (MonoAotCompile *acfg)
571 acfg->llc_args = g_string_new ("");
572 acfg->as_args = g_string_new ("");
575 * The prefix LLVM likes to put in front of symbol names on darwin.
576 * The mach-os specs require this for globals, but LLVM puts them in front of all
577 * symbols. We need to handle this, since we need to refer to LLVM generated
580 acfg->llvm_label_prefix = "";
583 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
584 g_string_append (acfg->llc_args, "-mattr=+v6");
587 g_string_append (acfg->llc_args, " -mattr=+vfp2,+d16");
588 g_string_append (acfg->as_args, " -mfpu=vfp3");
590 g_string_append (acfg->llc_args, " -soft-float");
593 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
594 acfg->thumb_mixed = TRUE;
596 if (acfg->aot_opts.mtriple)
597 mono_arch_set_target (acfg->aot_opts.mtriple);
601 acfg->llvm_label_prefix = "_";
602 acfg->need_no_dead_strip = TRUE;
605 #if defined(__linux__) && !defined(TARGET_ARM)
606 acfg->need_pt_gnu_stack = TRUE;
611 * arch_emit_direct_call:
613 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
617 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, int *call_size)
619 #if defined(TARGET_X86) || defined(TARGET_AMD64)
620 /* Need to make sure this is exactly 5 bytes long */
621 emit_byte (acfg, '\xe8');
622 emit_symbol_diff (acfg, target, ".", -4);
624 #elif defined(TARGET_ARM)
625 if (acfg->use_bin_writer) {
632 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
633 emit_bytes (acfg, buf, 4);
635 img_writer_emit_unset_mode (acfg->w);
636 fprintf (acfg->fp, "bl %s\n", target);
639 #elif defined(TARGET_POWERPC)
640 if (acfg->use_bin_writer) {
641 g_assert_not_reached ();
643 img_writer_emit_unset_mode (acfg->w);
644 fprintf (acfg->fp, "bl %s\n", target);
648 g_assert_not_reached ();
654 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
656 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
657 * in in the 2. slot of every GOT, and require every method to place the GOT
658 * address in r30, even when it doesn't access the GOT otherwise. This way,
659 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
664 * PPC64 uses function descriptors which greatly complicate all code, since
665 * these are used very inconsistently in the runtime. Some functions like
666 * mono_compile_method () return ftn descriptors, while others like the
667 * trampoline creation functions do not.
668 * We assume that all GOT slots contain function descriptors, and create
669 * descriptors in aot-runtime.c when needed.
670 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
671 * from function descriptors, we could do the same, but it would require
672 * rewriting all the ppc/aot code to handle function descriptors properly.
673 * So instead, we use the same approach as on PPC32.
674 * This is a horrible mess, but fixing it would probably lead to an even bigger
680 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
683 #ifdef MONO_ARCH_AOT_SUPPORTED
685 * arch_emit_got_offset:
687 * The memory pointed to by CODE should hold native code for computing the GOT
688 * address. Emit this code while patching it with the offset between code and
689 * the GOT. CODE_SIZE is set to the number of bytes emitted.
692 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
694 #if defined(TARGET_POWERPC64)
695 g_assert (!acfg->use_bin_writer);
696 img_writer_emit_unset_mode (acfg->w);
698 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
699 * unsupported relocations. So we store the got address into the .Lgot_addr
700 * symbol which is in the text segment, compute its address, and load it.
702 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
703 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
704 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
705 fprintf (acfg->fp, "add 30, 30, 0\n");
706 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
707 acfg->label_generator ++;
709 #elif defined(TARGET_POWERPC)
710 g_assert (!acfg->use_bin_writer);
711 img_writer_emit_unset_mode (acfg->w);
712 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
713 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
714 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
715 acfg->label_generator ++;
718 guint32 offset = mono_arch_get_patch_offset (code);
719 emit_bytes (acfg, code, offset);
720 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
722 *code_size = offset + 4;
727 * arch_emit_got_access:
729 * The memory pointed to by CODE should hold native code for loading a GOT
730 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
731 * CODE_SIZE is set to the number of bytes emitted.
734 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
736 /* Emit beginning of instruction */
737 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
739 /* Emit the offset */
741 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
742 *code_size = mono_arch_get_patch_offset (code) + 4;
743 #elif defined(TARGET_X86)
744 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
745 *code_size = mono_arch_get_patch_offset (code) + 4;
746 #elif defined(TARGET_ARM)
747 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
748 *code_size = mono_arch_get_patch_offset (code) + 4;
749 #elif defined(TARGET_POWERPC)
755 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
756 g_assert (code - buf == 8);
757 emit_bytes (acfg, buf, code - buf);
758 *code_size = code - buf;
761 g_assert_not_reached ();
768 * arch_emit_plt_entry:
770 * Emit code for the PLT entry with index INDEX.
773 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
775 #if defined(TARGET_X86)
776 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
777 #if defined(__default_codegen__)
778 /* jmp *<offset>(%ebx) */
779 emit_byte (acfg, 0xff);
780 emit_byte (acfg, 0xa3);
781 emit_int32 (acfg, offset);
782 /* Used by mono_aot_get_plt_info_offset */
783 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
784 #elif defined(__native_client_codegen__)
785 const guint8 kSizeOfNaClJmp = 11;
786 guint8 bytes[kSizeOfNaClJmp];
787 guint8 *pbytes = &bytes[0];
789 x86_jump_membase32 (pbytes, X86_EBX, offset);
790 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
791 /* four bytes of data, used by mono_arch_patch_plt_entry */
792 /* For Native Client, make this work with data embedded in push. */
793 emit_byte (acfg, 0x68); /* hide data in a push */
794 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
795 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
796 #endif /*__native_client_codegen__*/
797 #elif defined(TARGET_AMD64)
798 #if defined(__default_codegen__)
800 * We can't emit jumps because they are 32 bits only so they can't be patched.
801 * So we make indirect calls through GOT entries which are patched by the AOT
802 * loader to point to .Lpd entries.
804 /* jmpq *<offset>(%rip) */
805 emit_byte (acfg, '\xff');
806 emit_byte (acfg, '\x25');
807 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
808 /* Used by mono_aot_get_plt_info_offset */
809 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
810 #elif defined(__native_client_codegen__)
812 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
813 guint8 *code = buf_aligned;
815 /* mov <OFFSET>(%rip), %r11d */
816 emit_byte (acfg, '\x45');
817 emit_byte (acfg, '\x8b');
818 emit_byte (acfg, '\x1d');
819 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
821 amd64_jump_reg (code, AMD64_R11);
822 /* This should be constant for the plt patch */
823 g_assert ((size_t)(code-buf_aligned) == 10);
824 emit_bytes (acfg, buf_aligned, code - buf_aligned);
826 /* Hide data in a push imm32 so it passes validation */
827 emit_byte (acfg, 0x68); /* push */
828 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
829 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
830 #endif /*__native_client_codegen__*/
831 #elif defined(TARGET_ARM)
836 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
837 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
838 emit_bytes (acfg, buf, code - buf);
839 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
840 /* Used by mono_aot_get_plt_info_offset */
841 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
842 #elif defined(TARGET_POWERPC)
843 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
845 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
846 g_assert (!acfg->use_bin_writer);
847 img_writer_emit_unset_mode (acfg->w);
848 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
849 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
850 fprintf (acfg->fp, "add 11, 11, 30\n");
851 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
852 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
853 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
854 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
856 fprintf (acfg->fp, "mtctr 11\n");
857 fprintf (acfg->fp, "bctr\n");
858 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
860 g_assert_not_reached ();
865 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
867 #if defined(TARGET_ARM)
869 /* LLVM calls the PLT entries using bl, so emit a stub */
870 /* FIXME: Too much overhead on every call */
871 fprintf (acfg->fp, ".thumb_func\n");
872 fprintf (acfg->fp, "bx pc\n");
873 fprintf (acfg->fp, "nop\n");
874 fprintf (acfg->fp, ".arm\n");
876 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
877 /* The caller already transitioned to thumb */
878 /* The code below should be 12 bytes long */
879 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
880 /* thumb can't encode ld pc, [pc, ip] */
881 fprintf (acfg->fp, "add ip, pc, ip\n");
882 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
883 fprintf (acfg->fp, "bx ip\n");
884 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
885 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
887 g_assert_not_reached ();
892 * arch_emit_specific_trampoline:
894 * Emit code for a specific trampoline. OFFSET is the offset of the first of
895 * two GOT slots which contain the generic trampoline address and the trampoline
896 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
899 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
902 * The trampolines created here are variations of the specific
903 * trampolines created in mono_arch_create_specific_trampoline (). The
905 * - the generic trampoline address is taken from a got slot.
906 * - the offset of the got slot where the trampoline argument is stored
907 * is embedded in the instruction stream, and the generic trampoline
908 * can load the argument by loading the offset, adding it to the
909 * address of the trampoline to get the address of the got slot, and
910 * loading the argument from there.
911 * - all the trampolines should be of the same length.
913 #if defined(TARGET_AMD64)
914 #if defined(__default_codegen__)
915 /* This should be exactly 16 bytes long */
917 /* call *<offset>(%rip) */
918 emit_byte (acfg, '\x41');
919 emit_byte (acfg, '\xff');
920 emit_byte (acfg, '\x15');
921 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
922 /* This should be relative to the start of the trampoline */
923 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
924 emit_zero_bytes (acfg, 5);
925 #elif defined(__native_client_codegen__)
927 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
928 guint8 *code = buf_aligned;
933 /* Emit this call in 'code' so we can find out how long it is. */
934 amd64_call_reg (code, AMD64_R11);
935 call_start = mono_arch_nacl_skip_nops (buf_aligned);
936 call_len = code - call_start;
938 /* The tramp_size is twice the NaCl alignment because it starts with */
939 /* a call which needs to be aligned to the end of the boundary. */
940 *tramp_size = kNaClAlignment*2;
942 /* Emit nops to align call site below which is 7 bytes plus */
943 /* the length of the call sequence emitted above. */
944 /* Note: this requires the specific trampoline starts on a */
945 /* kNaclAlignedment aligned address, which it does because */
946 /* it's its own function that is aligned. */
948 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
949 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
950 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
952 /* The trampoline is stored at the offset'th pointer, the -4 is */
953 /* present because RIP relative addressing starts at the end of */
954 /* the current instruction, while the label "." is relative to */
955 /* the beginning of the current asm location, which in this case */
956 /* is not the mov instruction, but the offset itself, due to the */
957 /* way the bytes and ints are emitted here. */
958 got_offset = (offset * sizeof(gpointer)) - 4;
960 /* mov <OFFSET>(%rip), %r11d */
961 emit_byte (acfg, '\x45');
962 emit_byte (acfg, '\x8b');
963 emit_byte (acfg, '\x1d');
964 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
967 emit_bytes (acfg, call_start, call_len);
969 /* The arg is stored at the offset+1 pointer, relative to beginning */
970 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
971 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
973 /* We can't emit this data directly, hide in a "push imm32" */
974 emit_byte (acfg, '\x68'); /* push */
975 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
976 emit_alignment (acfg, kNaClAlignment);
977 #endif /*__native_client_codegen__*/
978 #elif defined(TARGET_ARM)
982 /* This should be exactly 20 bytes long */
985 ARM_PUSH (code, 0x5fff);
986 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
987 /* Load the value from the GOT */
988 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
990 ARM_BLX_REG (code, ARMREG_R1);
992 g_assert (code - buf == 16);
995 emit_bytes (acfg, buf, code - buf);
997 * Only one offset is needed, since the second one would be equal to the
1000 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1001 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1002 #elif defined(TARGET_POWERPC)
1009 g_assert (!acfg->use_bin_writer);
1012 * PPC has no ip relative addressing, so we need to compute the address
1013 * of the mscorlib got. That is slow and complex, so instead, we store it
1014 * in the second got slot of every aot image. The caller already computed
1015 * the address of its got and placed it into r30.
1017 img_writer_emit_unset_mode (acfg->w);
1018 /* Load mscorlib got address */
1019 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1020 /* Load generic trampoline address */
1021 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1022 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1023 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1024 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1025 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1027 fprintf (acfg->fp, "mtctr 11\n");
1028 /* Load trampoline argument */
1029 /* On ppc, we pass it normally to the generic trampoline */
1030 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1031 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1032 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1033 /* Branch to generic trampoline */
1034 fprintf (acfg->fp, "bctr\n");
1036 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1037 *tramp_size = 10 * 4;
1039 *tramp_size = 9 * 4;
1041 #elif defined(TARGET_X86)
1045 /* Similar to the PPC code above */
1047 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1049 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1050 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1051 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1055 /* Load mscorlib got address */
1056 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1057 /* Push trampoline argument */
1058 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1059 /* Load generic trampoline address */
1060 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1061 /* Branch to generic trampoline */
1062 x86_jump_reg (code, X86_ECX);
1064 #ifdef __native_client_codegen__
1066 /* emit nops to next 32 byte alignment */
1067 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1068 while (code < (buf + a)) x86_nop(code);
1071 emit_bytes (acfg, buf, code - buf);
1073 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1074 g_assert (code - buf == *tramp_size);
1076 g_assert_not_reached ();
1081 * arch_emit_unbox_trampoline:
1083 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1084 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1087 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1089 #if defined(TARGET_AMD64)
1094 this_reg = mono_arch_get_this_arg_reg (NULL);
1096 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1098 emit_bytes (acfg, buf, code - buf);
1100 emit_byte (acfg, '\xe9');
1101 emit_symbol_diff (acfg, call_target, ".", -4);
1102 #elif defined(TARGET_X86)
1109 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1111 emit_bytes (acfg, buf, code - buf);
1114 emit_byte (acfg, '\xe9');
1115 emit_symbol_diff (acfg, call_target, ".", -4);
1116 #elif defined(TARGET_ARM)
1120 if (acfg->thumb_mixed && cfg->compile_llvm) {
1121 fprintf (acfg->fp, "add r0, r0, #%d\n", sizeof (MonoObject));
1122 fprintf (acfg->fp, "b %s\n", call_target);
1123 fprintf (acfg->fp, ".arm\n");
1129 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1131 emit_bytes (acfg, buf, code - buf);
1132 /* jump to method */
1133 if (acfg->use_bin_writer) {
1140 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1141 emit_bytes (acfg, buf, 4);
1143 if (acfg->thumb_mixed && cfg->compile_llvm)
1144 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1146 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1148 #elif defined(TARGET_POWERPC)
1151 g_assert (!acfg->use_bin_writer);
1153 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1154 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1156 g_assert_not_reached ();
1161 * arch_emit_static_rgctx_trampoline:
1163 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1164 * two GOT slots which contain the rgctx argument, and the method to jump to.
1165 * TRAMP_SIZE is set to the size of the emitted trampoline.
1166 * These kinds of trampolines cannot be enumerated statically, since there could
1167 * be one trampoline per method instantiation, so we emit the same code for all
1168 * trampolines, and parameterize them using two GOT slots.
1171 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1173 #if defined(TARGET_AMD64)
1174 #if defined(__default_codegen__)
1175 /* This should be exactly 13 bytes long */
1178 /* mov <OFFSET>(%rip), %r10 */
1179 emit_byte (acfg, '\x4d');
1180 emit_byte (acfg, '\x8b');
1181 emit_byte (acfg, '\x15');
1182 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1184 /* jmp *<offset>(%rip) */
1185 emit_byte (acfg, '\xff');
1186 emit_byte (acfg, '\x25');
1187 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1188 #elif defined(__native_client_codegen__)
1190 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1191 guint8 *code = buf_aligned;
1193 /* mov <OFFSET>(%rip), %r10d */
1194 emit_byte (acfg, '\x45');
1195 emit_byte (acfg, '\x8b');
1196 emit_byte (acfg, '\x15');
1197 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1199 /* mov <OFFSET>(%rip), %r11d */
1200 emit_byte (acfg, '\x45');
1201 emit_byte (acfg, '\x8b');
1202 emit_byte (acfg, '\x1d');
1203 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1206 amd64_jump_reg (code, AMD64_R11);
1207 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1209 emit_alignment (acfg, kNaClAlignment);
1210 *tramp_size = kNaClAlignment;
1211 #endif /*__native_client_codegen__*/
1213 #elif defined(TARGET_ARM)
1217 /* This should be exactly 24 bytes long */
1220 /* Load rgctx value */
1221 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1222 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1223 /* Load branch addr + branch */
1224 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1225 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1227 g_assert (code - buf == 16);
1230 emit_bytes (acfg, buf, code - buf);
1231 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1232 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1233 #elif defined(TARGET_POWERPC)
1240 g_assert (!acfg->use_bin_writer);
1243 * PPC has no ip relative addressing, so we need to compute the address
1244 * of the mscorlib got. That is slow and complex, so instead, we store it
1245 * in the second got slot of every aot image. The caller already computed
1246 * the address of its got and placed it into r30.
1248 img_writer_emit_unset_mode (acfg->w);
1249 /* Load mscorlib got address */
1250 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1252 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1253 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1254 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1255 /* Load target address */
1256 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1257 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1258 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1259 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1260 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1261 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1263 fprintf (acfg->fp, "mtctr 11\n");
1264 /* Branch to the target address */
1265 fprintf (acfg->fp, "bctr\n");
1267 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1268 *tramp_size = 11 * 4;
1270 *tramp_size = 9 * 4;
1273 #elif defined(TARGET_X86)
1277 /* Similar to the PPC code above */
1279 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1282 /* Load mscorlib got address */
1283 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1285 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1286 /* Branch to the target address */
1287 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1289 #ifdef __native_client_codegen__
1291 /* emit nops to next 32 byte alignment */
1292 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1293 while (code < (buf + a)) x86_nop(code);
1297 emit_bytes (acfg, buf, code - buf);
1299 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1300 g_assert (code - buf == *tramp_size);
1302 g_assert_not_reached ();
1307 * arch_emit_imt_thunk:
1309 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1310 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1311 * key is the IMT key, and ptr holds the address of a memory location holding
1312 * the address to branch to if the IMT arg matches the key. The array is
1313 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1315 * TRAMP_SIZE is set to the size of the emitted trampoline.
1318 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1320 #if defined(TARGET_AMD64)
1322 #if defined(__native_client_codegen__)
1327 guint8 *mov_buf_ptr = mov_buf;
1329 const int kSizeOfMove = 7;
1330 #if defined(__default_codegen__)
1331 code = buf = g_malloc (256);
1332 #elif defined(__native_client_codegen__)
1333 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1334 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1335 /* The RIP relative move below is emitted first */
1340 /* FIXME: Optimize this, i.e. use binary search etc. */
1341 /* Maybe move the body into a separate function (slower, but much smaller) */
1343 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1346 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1348 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1351 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1353 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1356 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1357 amd64_jump_code (code, labels [0]);
1360 mono_amd64_patch (labels [2], code);
1361 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1362 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1366 mono_amd64_patch (labels [1], code);
1367 x86_breakpoint (code);
1369 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1370 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1371 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1372 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1373 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1374 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1376 emit_bytes (acfg, buf, code - buf);
1378 *tramp_size = code - buf + kSizeOfMove;
1379 #if defined(__native_client_codegen__)
1380 /* The tramp will be padded to the next kNaClAlignment bundle. */
1381 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1384 #if defined(__default_codegen__)
1386 #elif defined(__native_client_codegen__)
1390 #elif defined(TARGET_X86)
1392 #ifdef __native_client_codegen__
1397 #if defined(__default_codegen__)
1398 code = buf = g_malloc (256);
1399 #elif defined(__native_client_codegen__)
1400 buf_alloc = g_malloc (256 + kNaClAlignment);
1401 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1404 /* Allocate a temporary stack slot */
1405 x86_push_reg (code, X86_EAX);
1407 x86_push_reg (code, X86_EAX);
1409 /* Load mscorlib got address */
1410 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1412 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1415 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1417 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1420 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1422 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1425 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1426 x86_jump_code (code, labels [0]);
1429 mono_x86_patch (labels [2], code);
1430 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1431 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1432 /* Save the target address to the temporary stack location */
1433 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1435 x86_pop_reg (code, X86_EAX);
1436 /* Jump to the target address */
1441 mono_x86_patch (labels [1], code);
1442 x86_breakpoint (code);
1444 #ifdef __native_client_codegen__
1446 /* emit nops to next 32 byte alignment */
1447 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1448 while (code < (buf + a)) x86_nop(code);
1451 emit_bytes (acfg, buf, code - buf);
1453 *tramp_size = code - buf;
1455 #if defined(__default_codegen__)
1457 #elif defined(__native_client_codegen__)
1461 #elif defined(TARGET_ARM)
1463 guint8 *code, *code2, *labels [16];
1467 /* The IMT method is in v5 */
1469 /* Need at least two free registers, plus a slot for storing the pc */
1470 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1472 /* Load the parameter from the GOT */
1473 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1474 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1477 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1478 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1480 ARM_B_COND (code, ARMCOND_EQ, 0);
1482 /* End-of-loop check */
1483 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1485 ARM_B_COND (code, ARMCOND_EQ, 0);
1488 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1491 arm_patch (labels [4], labels [1]);
1494 arm_patch (labels [2], code);
1495 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1496 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1497 /* Save it to the third stack slot */
1498 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1499 /* Restore the registers and branch */
1500 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1503 arm_patch (labels [3], code);
1504 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1505 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1506 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1510 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1512 emit_bytes (acfg, buf, code - buf);
1513 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1515 *tramp_size = code - buf + 4;
1516 #elif defined(TARGET_POWERPC)
1518 guint8 *code, *labels [16];
1522 /* Load the mscorlib got address */
1523 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1524 /* Load the parameter from the GOT */
1525 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1526 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1528 /* Load and check key */
1530 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1531 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1533 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1535 /* End-of-loop check */
1536 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1538 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1541 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1544 mono_ppc_patch (labels [4], labels [1]);
1547 mono_ppc_patch (labels [2], code);
1548 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1549 /* r11 now contains the value of the vtable slot */
1550 /* this is not a function descriptor on ppc64 */
1551 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1552 ppc_mtctr (code, ppc_r11);
1553 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1556 mono_ppc_patch (labels [3], code);
1560 *tramp_size = code - buf;
1562 emit_bytes (acfg, buf, code - buf);
1564 g_assert_not_reached ();
1569 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1571 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1572 /* Based on code generated by gcc */
1573 img_writer_emit_unset_mode (acfg->w);
1576 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1577 ".section .ctors,\"aw\",@progbits\n"
1581 ".section .opd,\"aw\"\n"
1584 ".long .%s,.TOC.@tocbase32\n"
1587 ".type .%s,@function\n"
1589 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1591 ".section .ctors,\"aw\",@progbits\n"
1595 ".section .opd,\"aw\"\n"
1598 ".long .%1$s,.TOC.@tocbase32\n"
1599 ".size %1$s,.-%1$s\n"
1601 ".type .%1$s,@function\n"
1603 ".%1$s:\n", symbol);
1614 "lis 3, .Lglobals@h\n"
1615 "ori 3, 3, .Lglobals@l\n"
1616 "bl .mono_aot_register_module\n"
1624 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1626 ".size .%s,.-.%s\n", symbol, symbol);
1629 ".size .%1$s,.-.%1$s\n", symbol);
1635 /* END OF ARCH SPECIFIC CODE */
1638 mono_get_field_token (MonoClassField *field)
1640 MonoClass *klass = field->parent;
1643 for (i = 0; i < klass->field.count; ++i) {
1644 if (field == &klass->fields [i])
1645 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1648 g_assert_not_reached ();
1653 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1657 //printf ("ENCODE: %d 0x%x.\n", value, value);
1660 * Same encoding as the one used in the metadata, extended to handle values
1661 * greater than 0x1fffffff.
1663 if ((value >= 0) && (value <= 127))
1665 else if ((value >= 0) && (value <= 16383)) {
1666 p [0] = 0x80 | (value >> 8);
1667 p [1] = value & 0xff;
1669 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1670 p [0] = (value >> 24) | 0xc0;
1671 p [1] = (value >> 16) & 0xff;
1672 p [2] = (value >> 8) & 0xff;
1673 p [3] = value & 0xff;
1678 p [1] = (value >> 24) & 0xff;
1679 p [2] = (value >> 16) & 0xff;
1680 p [3] = (value >> 8) & 0xff;
1681 p [4] = value & 0xff;
1689 stream_init (MonoDynamicStream *sh)
1692 sh->alloc_size = 4096;
1693 sh->data = g_malloc (4096);
1695 /* So offsets are > 0 */
1701 make_room_in_stream (MonoDynamicStream *stream, int size)
1703 if (size <= stream->alloc_size)
1706 while (stream->alloc_size <= size) {
1707 if (stream->alloc_size < 4096)
1708 stream->alloc_size = 4096;
1710 stream->alloc_size *= 2;
1713 stream->data = g_realloc (stream->data, stream->alloc_size);
1717 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
1721 make_room_in_stream (stream, stream->index + len);
1722 memcpy (stream->data + stream->index, data, len);
1723 idx = stream->index;
1724 stream->index += len;
1731 * Add data to the binary blob inside the aot image. Returns the offset inside the
1732 * blob where the data was stored.
1735 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
1737 if (acfg->blob.alloc_size == 0)
1738 stream_init (&acfg->blob);
1740 return add_stream_data (&acfg->blob, (char*)data, data_len);
1744 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
1749 if (acfg->blob.alloc_size == 0)
1750 stream_init (&acfg->blob);
1752 count = acfg->blob.index % align;
1754 /* we assume the stream data will be aligned */
1756 add_stream_data (&acfg->blob, buf, 4 - count);
1758 return add_stream_data (&acfg->blob, (char*)data, data_len);
1762 * emit_offset_table:
1764 * Emit a table of increasing offsets in a compact form using differential encoding.
1765 * There is an index entry for each GROUP_SIZE number of entries. The greater the
1766 * group size, the more compact the table becomes, but the slower it becomes to compute
1767 * a given entry. Returns the size of the table.
1770 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
1772 gint32 current_offset;
1773 int i, buf_size, ngroups, index_entry_size;
1775 guint32 *index_offsets;
1777 ngroups = (noffsets + (group_size - 1)) / group_size;
1779 index_offsets = g_new0 (guint32, ngroups);
1781 buf_size = noffsets * 4;
1782 p = buf = g_malloc0 (buf_size);
1785 for (i = 0; i < noffsets; ++i) {
1786 //printf ("D: %d -> %d\n", i, offsets [i]);
1787 if ((i % group_size) == 0) {
1788 index_offsets [i / group_size] = p - buf;
1789 /* Emit the full value for these entries */
1790 encode_value (offsets [i], p, &p);
1792 /* The offsets are allowed to be non-increasing */
1793 //g_assert (offsets [i] >= current_offset);
1794 encode_value (offsets [i] - current_offset, p, &p);
1796 current_offset = offsets [i];
1799 if (ngroups && index_offsets [ngroups - 1] < 65000)
1800 index_entry_size = 2;
1802 index_entry_size = 4;
1804 /* Emit the header */
1805 emit_int32 (acfg, noffsets);
1806 emit_int32 (acfg, group_size);
1807 emit_int32 (acfg, ngroups);
1808 emit_int32 (acfg, index_entry_size);
1810 /* Emit the index */
1811 for (i = 0; i < ngroups; ++i) {
1812 if (index_entry_size == 2)
1813 emit_int16 (acfg, index_offsets [i]);
1815 emit_int32 (acfg, index_offsets [i]);
1819 emit_bytes (acfg, buf, p - buf);
1821 return (int)(p - buf) + (ngroups * 4);
1825 get_image_index (MonoAotCompile *cfg, MonoImage *image)
1829 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
1833 index = g_hash_table_size (cfg->image_hash);
1834 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
1835 g_ptr_array_add (cfg->image_table, image);
1841 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
1844 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
1846 /* FIXME: Search referenced images as well */
1847 if (!acfg->typespec_classes) {
1848 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
1849 for (i = 0; i < len; ++i) {
1850 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
1853 for (i = 0; i < len; ++i) {
1854 if (acfg->typespec_classes [i] == klass)
1859 return MONO_TOKEN_TYPE_SPEC | (i + 1);
1865 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
1868 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
1871 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
1874 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
1877 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1882 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
1886 if (klass->generic_class) {
1888 g_assert (klass->type_token);
1890 /* Find a typespec for a class if possible */
1891 token = find_typespec_for_class (acfg, klass);
1893 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
1894 encode_value (token, p, &p);
1896 MonoClass *gclass = klass->generic_class->container_class;
1897 MonoGenericInst *inst = klass->generic_class->context.class_inst;
1898 static int count = 0;
1901 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
1902 encode_klass_ref (acfg, gclass, p, &p);
1903 encode_ginst (acfg, inst, p, &p);
1907 } else if (klass->type_token) {
1908 int iindex = get_image_index (acfg, klass->image);
1910 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
1912 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
1913 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1915 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
1916 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
1917 encode_value (get_image_index (acfg, klass->image), p, &p);
1919 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1920 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
1921 g_assert (container);
1923 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
1924 encode_value (klass->byval_arg.type, p, &p);
1925 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
1927 encode_value (container->is_method, p, &p);
1928 if (container->is_method)
1929 encode_method_ref (acfg, container->owner.method, p, &p);
1931 encode_klass_ref (acfg, container->owner.klass, p, &p);
1932 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
1933 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
1934 encode_type (acfg, &klass->byval_arg, p, &p);
1937 g_assert (klass->rank > 0);
1938 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
1939 encode_value (klass->rank, p, &p);
1940 encode_klass_ref (acfg, klass->element_class, p, &p);
1948 * Encode a reference to KLASS. We use our home-grown encoding instead of the
1949 * standard metadata encoding.
1952 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
1954 gboolean shared = FALSE;
1957 * The encoding of generic instances is large so emit them only once.
1959 if (klass->generic_class) {
1961 g_assert (klass->type_token);
1963 /* Find a typespec for a class if possible */
1964 token = find_typespec_for_class (acfg, klass);
1967 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
1972 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
1976 buf2 = g_malloc (1024);
1979 encode_klass_ref_inner (acfg, klass, p, &p);
1980 g_assert (p - buf2 < 1024);
1982 offset = add_to_blob (acfg, buf2, p - buf2);
1985 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
1991 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
1992 encode_value (offset, p, &p);
1997 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2001 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2003 guint32 token = mono_get_field_token (field);
2006 encode_klass_ref (cfg, field->parent, p, &p);
2007 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2008 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2013 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2018 encode_value (inst->type_argc, p, &p);
2019 for (i = 0; i < inst->type_argc; ++i)
2020 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2025 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2028 MonoGenericInst *inst;
2030 inst = context->class_inst;
2032 g_assert (inst->type_argc);
2033 encode_ginst (acfg, inst, p, &p);
2035 encode_value (0, p, &p);
2037 inst = context->method_inst;
2039 g_assert (inst->type_argc);
2040 encode_ginst (acfg, inst, p, &p);
2042 encode_value (0, p, &p);
2048 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2052 g_assert (t->num_mods == 0);
2053 /* t->attrs can be ignored */
2054 //g_assert (t->attrs == 0);
2057 *p = MONO_TYPE_PINNED;
2061 *p = MONO_TYPE_BYREF;
2069 case MONO_TYPE_VOID:
2070 case MONO_TYPE_BOOLEAN:
2071 case MONO_TYPE_CHAR:
2084 case MONO_TYPE_STRING:
2085 case MONO_TYPE_OBJECT:
2086 case MONO_TYPE_TYPEDBYREF:
2088 case MONO_TYPE_VALUETYPE:
2089 case MONO_TYPE_CLASS:
2090 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2092 case MONO_TYPE_SZARRAY:
2093 encode_klass_ref (acfg, t->data.klass, p, &p);
2096 encode_type (acfg, t->data.type, p, &p);
2098 case MONO_TYPE_GENERICINST: {
2099 MonoClass *gclass = t->data.generic_class->container_class;
2100 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2102 encode_klass_ref (acfg, gclass, p, &p);
2103 encode_ginst (acfg, inst, p, &p);
2106 case MONO_TYPE_ARRAY: {
2107 MonoArrayType *array = t->data.array;
2110 encode_klass_ref (acfg, array->eklass, p, &p);
2111 encode_value (array->rank, p, &p);
2112 encode_value (array->numsizes, p, &p);
2113 for (i = 0; i < array->numsizes; ++i)
2114 encode_value (array->sizes [i], p, &p);
2115 encode_value (array->numlobounds, p, &p);
2116 for (i = 0; i < array->numlobounds; ++i)
2117 encode_value (array->lobounds [i], p, &p);
2121 g_assert_not_reached ();
2128 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2134 /* Similar to the metadata encoding */
2135 if (sig->generic_param_count)
2139 if (sig->explicit_this)
2141 flags |= (sig->call_convention & 0x0F);
2145 if (sig->generic_param_count)
2146 encode_value (sig->generic_param_count, p, &p);
2147 encode_value (sig->param_count, p, &p);
2149 encode_type (acfg, sig->ret, p, &p);
2150 for (i = 0; i < sig->param_count; ++i) {
2151 if (sig->sentinelpos == i) {
2152 *p = MONO_TYPE_SENTINEL;
2155 encode_type (acfg, sig->params [i], p, &p);
2161 #define MAX_IMAGE_INDEX 250
2164 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2166 guint32 image_index = get_image_index (acfg, method->klass->image);
2167 guint32 token = method->token;
2168 MonoJumpInfoToken *ji;
2172 * The encoding for most methods is as follows:
2173 * - image index encoded as a leb128
2174 * - token index encoded as a leb128
2175 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2176 * types of method encodings.
2179 g_assert (image_index < MONO_AOT_METHODREF_MIN);
2181 /* Mark methods which can't use aot trampolines because they need the further
2182 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2184 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2185 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2186 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2188 if (method->wrapper_type) {
2189 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2191 encode_value (method->wrapper_type, p, &p);
2193 switch (method->wrapper_type) {
2194 case MONO_WRAPPER_REMOTING_INVOKE:
2195 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2196 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2199 m = mono_marshal_method_from_wrapper (method);
2201 encode_method_ref (acfg, m, p, &p);
2204 case MONO_WRAPPER_PROXY_ISINST:
2205 case MONO_WRAPPER_LDFLD:
2206 case MONO_WRAPPER_LDFLDA:
2207 case MONO_WRAPPER_STFLD:
2208 case MONO_WRAPPER_ISINST: {
2209 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2210 encode_klass_ref (acfg, proxy_class, p, &p);
2213 case MONO_WRAPPER_LDFLD_REMOTE:
2214 case MONO_WRAPPER_STFLD_REMOTE:
2216 case MONO_WRAPPER_ALLOC: {
2217 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2219 /* The GC name is saved once in MonoAotFileInfo */
2220 g_assert (info->alloc_type != -1);
2221 encode_value (info->alloc_type, p, &p);
2224 case MONO_WRAPPER_WRITE_BARRIER:
2226 case MONO_WRAPPER_STELEMREF: {
2227 MonoClass *klass = mono_marshal_get_wrapper_info (method);
2230 /* Normal wrapper */
2231 encode_value (0, p, &p);
2235 /* virtual wrapper */
2236 name = mono_aot_wrapper_name (method);
2237 encode_value (MONO_AOT_WRAPPER_BY_NAME, p, &p);
2238 strcpy ((char*)p, name);
2239 p += strlen (name) + 1;
2244 case MONO_WRAPPER_UNKNOWN:
2245 if (strcmp (method->name, "FastMonitorEnter") == 0) {
2246 encode_value (MONO_AOT_WRAPPER_MONITOR_ENTER, p, &p);
2247 } else if (strcmp (method->name, "FastMonitorExit") == 0) {
2248 encode_value (MONO_AOT_WRAPPER_MONITOR_EXIT, p, &p);
2249 } else if (strcmp (method->name, "FastMonitorEnterV4") == 0) {
2250 encode_value (MONO_AOT_WRAPPER_MONITOR_ENTER_V4, p, &p);
2251 } else if (strcmp (method->name, "PtrToStructure") == 0) {
2252 encode_value (MONO_AOT_WRAPPER_PTR_TO_STRUCTURE, p, &p);
2253 encode_klass_ref (acfg, method->klass, p, &p);
2254 } else if (strcmp (method->name, "StructureToPtr") == 0) {
2255 encode_value (MONO_AOT_WRAPPER_STRUCTURE_TO_PTR, p, &p);
2256 encode_klass_ref (acfg, method->klass, p, &p);
2258 g_assert_not_reached ();
2261 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2264 if (strstr (method->name, "__icall_wrapper")) {
2265 encode_value (MONO_AOT_WRAPPER_JIT_ICALL, p, &p);
2267 strcpy ((char*)p, method->name);
2268 p += strlen (method->name) + 1;
2270 encode_value (0, p, &p);
2271 m = mono_marshal_method_from_wrapper (method);
2273 g_assert (m != method);
2274 encode_method_ref (acfg, m, p, &p);
2278 case MONO_WRAPPER_SYNCHRONIZED: {
2281 m = mono_marshal_method_from_wrapper (method);
2283 g_assert (m != method);
2284 encode_method_ref (acfg, m, p, &p);
2287 case MONO_WRAPPER_MANAGED_TO_MANAGED:
2288 if (!strcmp (method->name, "ElementAddr")) {
2289 ElementAddrWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2291 printf ("X: %d\n", info->rank);
2293 encode_value (MONO_AOT_WRAPPER_ELEMENT_ADDR, p, &p);
2294 encode_value (info->rank, p, &p);
2295 encode_value (info->elem_size, p, &p);
2299 name = mono_aot_wrapper_name (method);
2300 encode_value (MONO_AOT_WRAPPER_BY_NAME, p, &p);
2301 strcpy ((char*)p, name);
2302 p += strlen (name) + 1;
2306 case MONO_WRAPPER_CASTCLASS:
2307 if (!strcmp (method->name, "__castclass_with_cache")) {
2308 encode_value (MONO_AOT_WRAPPER_CASTCLASS_WITH_CACHE, p, &p);
2309 } else if (!strcmp (method->name, "__isinst_with_cache")) {
2310 encode_value (MONO_AOT_WRAPPER_ISINST_WITH_CACHE, p, &p);
2312 g_assert_not_reached ();
2315 case MONO_WRAPPER_RUNTIME_INVOKE: {
2316 if (!strcmp (method->name, "runtime_invoke_dynamic")) {
2317 encode_value (MONO_AOT_WRAPPER_RUNTIME_INVOKE_DYNAMIC, p, &p);
2318 } else if (mono_marshal_method_from_wrapper (method) != method) {
2321 /* Direct wrapper, encode it normally */
2322 if (!strstr (method->name, "virtual"))
2323 encode_value (MONO_AOT_WRAPPER_RUNTIME_INVOKE_DIRECT, p, &p);
2325 encode_value (MONO_AOT_WRAPPER_RUNTIME_INVOKE_VIRTUAL, p, &p);
2327 m = mono_marshal_method_from_wrapper (method);
2329 g_assert (m != method);
2330 encode_method_ref (acfg, m, p, &p);
2332 MonoMethodSignature *sig;
2334 encode_value (0, p, &p);
2336 sig = mono_method_signature (method);
2337 encode_signature (acfg, sig, p, &p);
2341 case MONO_WRAPPER_DELEGATE_INVOKE:
2342 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2343 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2344 MonoMethodSignature *sig = mono_method_signature (method);
2345 encode_signature (acfg, sig, p, &p);
2348 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2349 NativeToManagedWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2351 encode_method_ref (acfg, info->method, p, &p);
2352 encode_klass_ref (acfg, info->klass, p, &p);
2356 g_assert_not_reached ();
2358 } else if (mono_method_signature (method)->is_inflated) {
2360 * This is a generic method, find the original token which referenced it and
2362 * Obtain the token from information recorded by the JIT.
2364 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2366 image_index = get_image_index (acfg, ji->image);
2367 g_assert (image_index < MAX_IMAGE_INDEX);
2370 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2371 encode_value (image_index, p, &p);
2372 encode_value (token, p, &p);
2374 MonoMethod *declaring;
2375 MonoGenericContext *context = mono_method_get_context (method);
2377 g_assert (method->is_inflated);
2378 declaring = ((MonoMethodInflated*)method)->declaring;
2381 * This might be a non-generic method of a generic instance, which
2382 * doesn't have a token since the reference is generated by the JIT
2383 * like Nullable:Box/Unbox, or by generic sharing.
2386 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2387 /* Encode the klass */
2388 encode_klass_ref (acfg, method->klass, p, &p);
2389 /* Encode the method */
2390 image_index = get_image_index (acfg, method->klass->image);
2391 g_assert (image_index < MAX_IMAGE_INDEX);
2392 g_assert (declaring->token);
2393 token = declaring->token;
2394 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2395 encode_value (image_index, p, &p);
2396 encode_value (token, p, &p);
2397 encode_generic_context (acfg, context, p, &p);
2399 } else if (token == 0) {
2400 /* This might be a method of a constructed type like int[,].Set */
2401 /* Obtain the token from information recorded by the JIT */
2402 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2404 image_index = get_image_index (acfg, ji->image);
2405 g_assert (image_index < MAX_IMAGE_INDEX);
2408 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2409 encode_value (image_index, p, &p);
2410 encode_value (token, p, &p);
2413 g_assert (method->klass->rank);
2415 /* Encode directly */
2416 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2417 encode_klass_ref (acfg, method->klass, p, &p);
2418 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2419 encode_value (0, p, &p);
2420 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2421 encode_value (1, p, &p);
2422 else if (!strcmp (method->name, "Get"))
2423 encode_value (2, p, &p);
2424 else if (!strcmp (method->name, "Address"))
2425 encode_value (3, p, &p);
2426 else if (!strcmp (method->name, "Set"))
2427 encode_value (4, p, &p);
2429 g_assert_not_reached ();
2432 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2433 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2439 compare_patches (gconstpointer a, gconstpointer b)
2443 i = (*(MonoJumpInfo**)a)->ip.i;
2444 j = (*(MonoJumpInfo**)b)->ip.i;
2455 static G_GNUC_UNUSED char*
2456 patch_to_string (MonoJumpInfo *patch_info)
2460 str = g_string_new ("");
2462 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2464 switch (patch_info->type) {
2465 case MONO_PATCH_INFO_VTABLE:
2466 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2471 g_string_append_printf (str, ")");
2472 return g_string_free (str, FALSE);
2478 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2481 static inline gboolean
2482 is_plt_patch (MonoJumpInfo *patch_info)
2484 switch (patch_info->type) {
2485 case MONO_PATCH_INFO_METHOD:
2486 case MONO_PATCH_INFO_INTERNAL_METHOD:
2487 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2488 case MONO_PATCH_INFO_ICALL_ADDR:
2489 case MONO_PATCH_INFO_CLASS_INIT:
2490 case MONO_PATCH_INFO_RGCTX_FETCH:
2491 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2492 case MONO_PATCH_INFO_MONITOR_ENTER:
2493 case MONO_PATCH_INFO_MONITOR_EXIT:
2494 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2504 * Return the symbol identifying the plt entry PLT_OFFSET.
2507 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2511 * The Apple linker reorganizes object files, so it doesn't like branches to local
2512 * labels, since those have no relocations.
2514 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2516 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2523 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2525 static MonoPltEntry*
2526 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2530 if (!is_plt_patch (patch_info))
2533 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2535 // FIXME: This breaks the calculation of final_got_size
2536 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2538 * Allocate a separate PLT slot for each such patch, since some plt
2539 * entries will refer to the method itself, and some will refer to the
2546 MonoJumpInfo *new_ji;
2548 g_assert (!acfg->final_got_size);
2550 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2552 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2553 res->plt_offset = acfg->plt_offset;
2555 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2556 if (acfg->aot_opts.write_symbols)
2557 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2559 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2561 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2563 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2565 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2567 acfg->plt_offset ++;
2576 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2577 * JI could be found if it exists, otherwise allocates a new one.
2580 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2584 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2586 return got_offset - 1;
2588 got_offset = acfg->got_offset;
2589 acfg->got_offset ++;
2591 if (acfg->final_got_size)
2592 g_assert (got_offset < acfg->final_got_size);
2594 acfg->stats.got_slots ++;
2595 acfg->stats.got_slot_types [ji->type] ++;
2597 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2598 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2599 g_ptr_array_add (acfg->got_patches, ji);
2604 /* Add a method to the list of methods which need to be emitted */
2606 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2609 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2610 g_ptr_array_add (acfg->methods, method);
2611 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2612 acfg->nmethods = acfg->methods->len + 1;
2615 if (method->wrapper_type || extra)
2616 g_ptr_array_add (acfg->extra_methods, method);
2620 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2622 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2630 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2634 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2638 index = acfg->method_index;
2639 add_method_with_index (acfg, method, index, extra);
2641 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
2643 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2645 acfg->method_index ++;
2651 add_method (MonoAotCompile *acfg, MonoMethod *method)
2653 return add_method_full (acfg, method, FALSE, 0);
2657 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2659 add_method_full (acfg, method, TRUE, 0);
2663 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2665 add_method_full (acfg, method, TRUE, depth);
2669 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2671 MonoAotCompile *acfg = user_data;
2672 MonoJitICallInfo *callinfo = value;
2673 MonoMethod *wrapper;
2679 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2680 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2683 add_method (acfg, wrapper);
2687 get_runtime_invoke_sig (MonoMethodSignature *sig)
2689 MonoMethodBuilder *mb;
2692 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2693 m = mono_mb_create_method (mb, sig, 16);
2694 return mono_marshal_get_runtime_invoke (m, FALSE);
2698 can_marshal_struct (MonoClass *klass)
2700 MonoClassField *field;
2701 gboolean can_marshal = TRUE;
2702 gpointer iter = NULL;
2704 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
2707 /* Only allow a few field types to avoid asserts in the marshalling code */
2708 while ((field = mono_class_get_fields (klass, &iter))) {
2709 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
2712 switch (field->type->type) {
2717 case MONO_TYPE_BOOLEAN:
2720 case MONO_TYPE_CHAR:
2728 case MONO_TYPE_STRING:
2730 case MONO_TYPE_VALUETYPE:
2731 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
2732 can_marshal = FALSE;
2735 can_marshal = FALSE;
2741 /* Its hard to compute whenever these can be marshalled or not */
2742 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs"))
2749 add_wrappers (MonoAotCompile *acfg)
2751 MonoMethod *method, *m;
2753 MonoMethodSignature *sig, *csig;
2757 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
2758 * so there is only one wrapper of a given type, or inlining their contents into their
2763 * FIXME: This depends on the fact that different wrappers have different
2767 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2769 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2770 gboolean skip = FALSE;
2772 method = mono_get_method (acfg->image, token, NULL);
2774 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
2775 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
2776 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
2779 if (method->is_generic || method->klass->generic_container)
2782 /* Skip methods which can not be handled by get_runtime_invoke () */
2783 sig = mono_method_signature (method);
2786 if ((sig->ret->type == MONO_TYPE_PTR) ||
2787 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
2790 for (j = 0; j < sig->param_count; j++) {
2791 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
2795 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2796 if (!method->klass->contextbound) {
2797 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
2798 gboolean has_nullable = FALSE;
2800 for (j = 0; j < sig->param_count; j++) {
2801 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
2802 has_nullable = TRUE;
2805 if (info && !has_nullable) {
2806 /* Supported by the dynamic runtime-invoke wrapper */
2814 //printf ("%s\n", mono_method_full_name (method, TRUE));
2815 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2819 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
2820 #ifdef MONO_ARCH_HAVE_TLS_GET
2821 MonoMethodDesc *desc;
2822 MonoMethod *orig_method;
2826 /* Runtime invoke wrappers */
2828 /* void runtime-invoke () [.cctor] */
2829 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2830 csig->ret = &mono_defaults.void_class->byval_arg;
2831 add_method (acfg, get_runtime_invoke_sig (csig));
2833 /* void runtime-invoke () [Finalize] */
2834 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2836 csig->ret = &mono_defaults.void_class->byval_arg;
2837 add_method (acfg, get_runtime_invoke_sig (csig));
2839 /* void runtime-invoke (string) [exception ctor] */
2840 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
2842 csig->ret = &mono_defaults.void_class->byval_arg;
2843 csig->params [0] = &mono_defaults.string_class->byval_arg;
2844 add_method (acfg, get_runtime_invoke_sig (csig));
2846 /* void runtime-invoke (string, string) [exception ctor] */
2847 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2849 csig->ret = &mono_defaults.void_class->byval_arg;
2850 csig->params [0] = &mono_defaults.string_class->byval_arg;
2851 csig->params [1] = &mono_defaults.string_class->byval_arg;
2852 add_method (acfg, get_runtime_invoke_sig (csig));
2854 /* string runtime-invoke () [Exception.ToString ()] */
2855 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
2857 csig->ret = &mono_defaults.string_class->byval_arg;
2858 add_method (acfg, get_runtime_invoke_sig (csig));
2860 /* void runtime-invoke (string, Exception) [exception ctor] */
2861 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2863 csig->ret = &mono_defaults.void_class->byval_arg;
2864 csig->params [0] = &mono_defaults.string_class->byval_arg;
2865 csig->params [1] = &mono_defaults.exception_class->byval_arg;
2866 add_method (acfg, get_runtime_invoke_sig (csig));
2868 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
2869 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
2871 csig->ret = &(mono_class_from_name (
2872 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
2873 csig->params [0] = &mono_defaults.string_class->byval_arg;
2874 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
2875 add_method (acfg, get_runtime_invoke_sig (csig));
2877 /* runtime-invoke used by finalizers */
2878 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
2880 /* This is used by mono_runtime_capture_context () */
2881 method = mono_get_context_capture_method ();
2883 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
2885 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
2886 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
2889 /* JIT icall wrappers */
2890 /* FIXME: locking */
2891 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
2894 add_method (acfg, mono_marshal_get_stelemref ());
2896 #ifdef MONO_ARCH_HAVE_TLS_GET
2897 /* Managed Allocators */
2898 nallocators = mono_gc_get_managed_allocator_types ();
2899 for (i = 0; i < nallocators; ++i) {
2900 m = mono_gc_get_managed_allocator_by_type (i);
2902 add_method (acfg, m);
2905 /* Monitor Enter/Exit */
2906 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
2907 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2908 /* This is a v4 method */
2910 method = mono_monitor_get_fast_path (orig_method);
2912 add_method (acfg, method);
2914 mono_method_desc_free (desc);
2916 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
2917 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2918 g_assert (orig_method);
2919 mono_method_desc_free (desc);
2920 method = mono_monitor_get_fast_path (orig_method);
2922 add_method (acfg, method);
2925 /* Stelemref wrappers */
2926 /* There is only a constant number of these, iterating over all types should handle them all */
2927 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2930 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2931 klass = mono_class_get (acfg->image, token);
2933 add_method (acfg, mono_marshal_get_virtual_stelemref (mono_array_class_get (klass, 1)));
2935 mono_loader_clear_error ();
2938 /* castclass_with_check wrapper */
2939 add_method (acfg, mono_marshal_get_castclass_with_cache ());
2940 /* isinst_with_check wrapper */
2941 add_method (acfg, mono_marshal_get_isinst_with_cache ());
2943 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
2945 MonoMethodDesc *desc;
2948 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
2949 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
2950 mono_method_desc_free (desc);
2952 m = mono_monitor_get_fast_path (m);
2953 add_method (acfg, m);
2960 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
2961 * we use the original method instead at runtime.
2962 * Since full-aot doesn't support remoting, this is not a problem.
2965 /* remoting-invoke wrappers */
2966 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
2967 MonoMethodSignature *sig;
2969 token = MONO_TOKEN_METHOD_DEF | (i + 1);
2970 method = mono_get_method (acfg->image, token, NULL);
2972 sig = mono_method_signature (method);
2974 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
2975 m = mono_marshal_get_remoting_invoke_with_check (method);
2977 add_method (acfg, m);
2982 /* delegate-invoke wrappers */
2983 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
2986 token = MONO_TOKEN_TYPE_DEF | (i + 1);
2987 klass = mono_class_get (acfg->image, token);
2990 mono_loader_clear_error ();
2994 if (klass->delegate && klass != mono_defaults.delegate_class && klass != mono_defaults.multicastdelegate_class && !klass->generic_container) {
2995 method = mono_get_delegate_invoke (klass);
2997 m = mono_marshal_get_delegate_invoke (method, NULL);
2999 add_method (acfg, m);
3001 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3003 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3005 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3007 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3011 /* Synchronized wrappers */
3012 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3013 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3014 method = mono_get_method (acfg->image, token, NULL);
3016 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
3017 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3020 /* pinvoke wrappers */
3021 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3023 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3025 method = mono_get_method (acfg->image, token, NULL);
3027 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3028 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3029 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3033 /* native-to-managed wrappers */
3034 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3036 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3037 MonoCustomAttrInfo *cattr;
3040 method = mono_get_method (acfg->image, token, NULL);
3043 * Only generate native-to-managed wrappers for methods which have an
3044 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3045 * name to avoid defining a new assembly to contain it.
3047 cattr = mono_custom_attrs_from_method (method);
3050 for (j = 0; j < cattr->num_attrs; ++j)
3051 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3053 if (j < cattr->num_attrs) {
3054 MonoCustomAttrEntry *e = &cattr->attrs [j];
3055 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3056 const char *p = (const char*)e->data;
3058 int slen, num_named, named_type, data_type;
3062 char *export_name = NULL;
3063 MonoMethod *wrapper;
3065 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3066 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3067 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3068 mono_method_full_name (method, TRUE));
3072 g_assert (sig->param_count == 1);
3073 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3076 * Decode the cattr manually since we can't create objects
3077 * during aot compilation.
3083 /* From load_cattr_value () in reflection.c */
3084 slen = mono_metadata_decode_value (p, &p);
3085 n = g_memdup (p, slen + 1);
3087 t = mono_reflection_type_from_name (n, acfg->image);
3091 klass = mono_class_from_mono_type (t);
3092 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3096 num_named = read16 (p);
3099 g_assert (num_named < 2);
3100 if (num_named == 1) {
3103 MonoType *prop_type;
3105 /* parse ExportSymbol attribute */
3107 named_type = *named;
3112 name_len = mono_metadata_decode_blob_size (named, &named);
3113 name = g_malloc (name_len + 1);
3114 memcpy (name, named, name_len);
3115 name [name_len] = 0;
3118 g_assert (named_type == 0x54);
3119 g_assert (!strcmp (name, "ExportSymbol"));
3121 prop_type = &mono_defaults.string_class->byval_arg;
3123 /* load_cattr_value (), string case */
3124 g_assert (*named != (char)0xff);
3125 slen = mono_metadata_decode_value (named, &named);
3126 export_name = g_malloc (slen + 1);
3127 memcpy (export_name, named, slen);
3128 export_name [slen] = 0;
3132 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3133 add_method (acfg, wrapper);
3135 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3139 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3140 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3141 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3145 /* StructureToPtr/PtrToStructure wrappers */
3146 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3149 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3150 klass = mono_class_get (acfg->image, token);
3153 mono_loader_clear_error ();
3157 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass)) {
3158 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3159 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3165 has_type_vars (MonoClass *klass)
3167 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3170 return has_type_vars (klass->element_class);
3171 if (klass->generic_class) {
3172 MonoGenericContext *context = &klass->generic_class->context;
3173 if (context->class_inst) {
3176 for (i = 0; i < context->class_inst->type_argc; ++i)
3177 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3185 method_has_type_vars (MonoMethod *method)
3187 if (has_type_vars (method->klass))
3190 if (method->is_inflated) {
3191 MonoGenericContext *context = mono_method_get_context (method);
3192 if (context->method_inst) {
3195 for (i = 0; i < context->method_inst->type_argc; ++i)
3196 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3203 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth);
3206 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force)
3208 /* This might lead to a huge code blowup so only do it if neccesary */
3209 if (!acfg->aot_opts.full_aot && !force)
3212 add_generic_class_with_depth (acfg, klass, 0);
3216 check_type_depth (MonoType *t, int depth)
3224 case MONO_TYPE_GENERICINST: {
3225 MonoGenericClass *gklass = t->data.generic_class;
3226 MonoGenericInst *ginst = gklass->context.class_inst;
3229 for (i = 0; i < ginst->type_argc; ++i) {
3230 if (check_type_depth (ginst->type_argv [i], depth + 1))
3244 * add_generic_class:
3246 * Add all methods of a generic class.
3249 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth)
3254 mono_class_init (klass);
3256 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3259 if (has_type_vars (klass))
3262 if (!klass->generic_class && !klass->rank)
3265 if (!acfg->ginst_hash)
3266 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3268 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3271 if (check_type_depth (&klass->byval_arg, 0))
3274 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3277 while ((method = mono_class_get_methods (klass, &iter))) {
3278 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3282 if (method->is_generic)
3287 * FIXME: Instances which are referenced by these methods are not added,
3288 * for example Array.Resize<int> for List<int>.Add ().
3290 add_extra_method_with_depth (acfg, method, depth + 1);
3293 if (klass->delegate) {
3294 method = mono_get_delegate_invoke (klass);
3296 method = mono_marshal_get_delegate_invoke (method, NULL);
3298 add_method (acfg, method);
3301 /* Add superclasses */
3303 add_generic_class_with_depth (acfg, klass->parent, depth);
3306 * For ICollection<T>, add instances of the helper methods
3307 * in Array, since a T[] could be cast to ICollection<T>.
3309 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3310 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1"))) {
3311 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3312 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3316 if (!strcmp (klass->name, "IEnumerator`1"))
3317 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3319 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3321 /* Add the T[]/InternalEnumerator class */
3322 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3326 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3327 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3331 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3332 add_generic_class (acfg, nclass, FALSE);
3336 while ((method = mono_class_get_methods (array_class, &iter))) {
3337 if (strstr (method->name, name_prefix)) {
3338 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3339 add_extra_method_with_depth (acfg, m, depth);
3343 g_free (name_prefix);
3346 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3347 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3348 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3349 MonoClass *icomparable, *gcomparer;
3350 MonoGenericContext ctx;
3351 MonoType *args [16];
3353 memset (&ctx, 0, sizeof (ctx));
3355 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3356 g_assert (icomparable);
3357 args [0] = &tclass->byval_arg;
3358 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3360 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3361 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3362 g_assert (gcomparer);
3363 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
3367 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3368 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3369 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3370 MonoClass *iface, *gcomparer;
3371 MonoGenericContext ctx;
3372 MonoType *args [16];
3374 memset (&ctx, 0, sizeof (ctx));
3376 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3378 args [0] = &tclass->byval_arg;
3379 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3381 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3382 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3383 g_assert (gcomparer);
3384 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE);
3390 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3393 MonoGenericContext ctx;
3394 MonoType *args [16];
3396 memset (&ctx, 0, sizeof (ctx));
3398 for (i = 0; i < ninsts; ++i) {
3399 args [0] = insts [i];
3400 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3401 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force);
3406 * add_generic_instances:
3408 * Add instances referenced by the METHODSPEC/TYPESPEC table.
3411 add_generic_instances (MonoAotCompile *acfg)
3416 MonoMethodHeader *header;
3417 MonoMethodSignature *sig;
3418 MonoGenericContext *context;
3420 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3421 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3422 method = mono_get_method (acfg->image, token, NULL);
3427 if (method->klass->image != acfg->image)
3430 context = mono_method_get_context (method);
3432 if (context && ((context->class_inst && context->class_inst->is_open)))
3436 * For open methods, create an instantiation which can be passed to the JIT.
3437 * FIXME: Handle class_inst as well.
3439 if (context && context->method_inst && context->method_inst->is_open) {
3440 MonoGenericContext shared_context;
3441 MonoGenericInst *inst;
3442 MonoType **type_argv;
3444 MonoMethod *declaring_method;
3445 gboolean supported = TRUE;
3447 /* Check that the context doesn't contain open constructed types */
3448 if (context->class_inst) {
3449 inst = context->class_inst;
3450 for (i = 0; i < inst->type_argc; ++i) {
3451 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)
3453 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3457 if (context->method_inst) {
3458 inst = context->method_inst;
3459 for (i = 0; i < inst->type_argc; ++i) {
3460 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)
3462 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3470 memset (&shared_context, 0, sizeof (MonoGenericContext));
3472 inst = context->class_inst;
3474 type_argv = g_new0 (MonoType*, inst->type_argc);
3475 for (i = 0; i < inst->type_argc; ++i) {
3476 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)
3477 type_argv [i] = &mono_defaults.object_class->byval_arg;
3479 type_argv [i] = inst->type_argv [i];
3482 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3486 inst = context->method_inst;
3488 type_argv = g_new0 (MonoType*, inst->type_argc);
3489 for (i = 0; i < inst->type_argc; ++i) {
3490 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)
3491 type_argv [i] = &mono_defaults.object_class->byval_arg;
3493 type_argv [i] = inst->type_argv [i];
3496 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3500 if (method->is_generic || method->klass->generic_container)
3501 declaring_method = method;
3503 declaring_method = mono_method_get_declaring_generic_method (method);
3505 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3509 * If the method is fully sharable, it was already added in place of its
3510 * generic definition.
3512 if (mono_method_is_generic_sharable_impl_full (method, FALSE, FALSE))
3516 * FIXME: Partially shared methods are not shared here, so we end up with
3517 * many identical methods.
3519 add_extra_method (acfg, method);
3522 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
3525 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
3527 klass = mono_class_get (acfg->image, token);
3528 if (!klass || klass->rank) {
3529 mono_loader_clear_error ();
3533 add_generic_class (acfg, klass, FALSE);
3536 /* Add types of args/locals */
3537 for (i = 0; i < acfg->methods->len; ++i) {
3540 method = g_ptr_array_index (acfg->methods, i);
3542 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3544 sig = mono_method_signature (method);
3547 for (j = 0; j < sig->param_count; ++j)
3548 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3549 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1);
3552 header = mono_method_get_header (method);
3555 for (j = 0; j < header->num_locals; ++j)
3556 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3557 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1);
3561 if (acfg->image == mono_defaults.corlib) {
3563 MonoType *insts [256];
3566 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
3567 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
3568 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
3569 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
3570 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
3571 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
3572 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
3573 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
3574 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
3575 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
3576 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
3577 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
3579 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
3580 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
3582 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3583 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
3585 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3587 /* Add instances of the array generic interfaces for primitive types */
3588 /* This will add instances of the InternalArray_ helper methods in Array too */
3589 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
3591 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3592 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
3594 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3595 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
3597 add_instances_of (acfg, klass, insts, ninsts, TRUE);
3600 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
3601 * used for all instances of GetGenericValueImpl by the AOT runtime.
3604 MonoGenericContext ctx;
3605 MonoType *args [16];
3606 MonoMethod *get_method;
3607 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
3609 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
3612 memset (&ctx, 0, sizeof (ctx));
3613 args [0] = &mono_defaults.object_class->byval_arg;
3614 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3615 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
3619 /* Same for CompareExchange<T>/Exchange<T> */
3621 MonoGenericContext ctx;
3622 MonoType *args [16];
3624 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
3625 gpointer iter = NULL;
3627 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
3628 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
3629 memset (&ctx, 0, sizeof (ctx));
3630 args [0] = &mono_defaults.object_class->byval_arg;
3631 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
3632 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
3640 * is_direct_callable:
3642 * Return whenever the method identified by JI is directly callable without
3643 * going through the PLT.
3646 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
3648 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3649 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3651 gboolean direct_callable = TRUE;
3653 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
3654 direct_callable = FALSE;
3655 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
3656 // FIXME: Maybe call the wrapper directly ?
3657 direct_callable = FALSE;
3659 if (direct_callable)
3668 * emit_and_reloc_code:
3670 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
3671 * is true, calls are made through the GOT too. This is used for emitting trampolines
3672 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
3673 * since trampolines are needed to make PTL work.
3676 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
3678 int i, pindex, start_index, method_index;
3680 MonoJumpInfo *patch_info;
3681 MonoMethodHeader *header;
3682 gboolean skip, direct_call;
3684 char direct_call_target [1024];
3687 header = mono_method_get_header (method);
3689 method_index = get_method_index (acfg, method);
3692 /* Collect and sort relocations */
3693 patches = g_ptr_array_new ();
3694 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
3695 g_ptr_array_add (patches, patch_info);
3696 g_ptr_array_sort (patches, compare_patches);
3699 for (i = 0; i < code_len; i++) {
3701 for (pindex = start_index; pindex < patches->len; ++pindex) {
3702 patch_info = g_ptr_array_index (patches, pindex);
3703 if (patch_info->ip.i >= i)
3707 #ifdef MONO_ARCH_AOT_SUPPORTED
3709 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
3710 start_index = pindex;
3712 switch (patch_info->type) {
3713 case MONO_PATCH_INFO_NONE:
3715 case MONO_PATCH_INFO_GOT_OFFSET: {
3718 arch_emit_got_offset (acfg, code + i, &code_size);
3721 patch_info->type = MONO_PATCH_INFO_NONE;
3726 * If this patch is a call, try emitting a direct call instead of
3727 * through a PLT entry. This is possible if the called method is in
3728 * the same assembly and requires no initialization.
3730 direct_call = FALSE;
3731 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
3732 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
3733 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
3734 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
3736 g_assert (strlen (callee_cfg->asm_symbol) < 1000);
3737 sprintf (direct_call_target, "%s", callee_cfg->asm_symbol);
3738 patch_info->type = MONO_PATCH_INFO_NONE;
3739 acfg->stats.direct_calls ++;
3742 acfg->stats.all_calls ++;
3745 if (!got_only && !direct_call) {
3746 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
3748 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
3750 sprintf (direct_call_target, "%s", plt_entry->symbol);
3752 /* Nullify the patch */
3753 patch_info->type = MONO_PATCH_INFO_NONE;
3754 plt_entry->jit_used = TRUE;
3761 arch_emit_direct_call (acfg, direct_call_target, &call_size);
3766 got_slot = get_got_offset (acfg, patch_info);
3768 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
3775 #endif /* MONO_ARCH_AOT_SUPPORTED */
3778 /* Find next patch */
3780 for (pindex = start_index; pindex < patches->len; ++pindex) {
3781 patch_info = g_ptr_array_index (patches, pindex);
3782 if (patch_info->ip.i >= i)
3786 /* Try to emit multiple bytes at once */
3787 if (pindex < patches->len && patch_info->ip.i > i) {
3788 emit_bytes (acfg, code + i, patch_info->ip.i - i);
3789 i = patch_info->ip.i - 1;
3791 emit_bytes (acfg, code + i, 1);
3800 * Modify SYMBOL so it only includes characters permissible in symbols.
3803 sanitize_symbol (char *symbol)
3805 int i, len = strlen (symbol);
3807 for (i = 0; i < len; ++i)
3808 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
3813 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
3815 char *name1, *name2, *cached;
3816 int i, j, len, count;
3818 name1 = mono_method_full_name (method, TRUE);
3819 len = strlen (name1);
3820 name2 = malloc (strlen (prefix) + len + 16);
3821 memcpy (name2, prefix, strlen (prefix));
3822 j = strlen (prefix);
3823 for (i = 0; i < len; ++i) {
3824 if (isalnum (name1 [i])) {
3825 name2 [j ++] = name1 [i];
3826 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
3828 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
3831 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
3840 while (g_hash_table_lookup (cache, name2)) {
3841 sprintf (name2 + j, "_%d", count);
3845 cached = g_strdup (name2);
3846 g_hash_table_insert (cache, cached, cached);
3852 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
3857 char *debug_sym = NULL;
3859 int func_alignment = AOT_FUNC_ALIGNMENT;
3860 MonoMethodHeader *header;
3863 method = cfg->orig_method;
3864 code = cfg->native_code;
3865 header = cfg->header;
3867 method_index = get_method_index (acfg, method);
3869 /* Make the labels local */
3870 sprintf (symbol, "%s", cfg->asm_symbol);
3872 emit_section_change (acfg, ".text", 0);
3873 emit_alignment (acfg, func_alignment);
3874 emit_label (acfg, symbol);
3876 if (acfg->aot_opts.write_symbols) {
3878 * Write a C style symbol for every method, this has two uses:
3879 * - it works on platforms where the dwarf debugging info is not
3881 * - it allows the setting of breakpoints of aot-ed methods.
3883 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
3885 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3886 if (acfg->need_no_dead_strip)
3887 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
3888 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
3889 emit_label (acfg, debug_sym);
3892 export_name = g_hash_table_lookup (acfg->export_names, method);
3894 /* Emit a global symbol for the method */
3895 emit_global_inner (acfg, export_name, TRUE);
3896 emit_label (acfg, export_name);
3899 if (cfg->verbose_level > 0)
3900 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), symbol);
3902 acfg->stats.code_size += cfg->code_len;
3904 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
3906 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
3910 if (acfg->aot_opts.write_symbols) {
3911 emit_symbol_size (acfg, debug_sym, ".");
3915 sprintf (symbol, "%sme_%x", acfg->temp_prefix, method_index);
3916 emit_label (acfg, symbol);
3922 * Encode PATCH_INFO into its disk representation.
3925 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
3929 switch (patch_info->type) {
3930 case MONO_PATCH_INFO_NONE:
3932 case MONO_PATCH_INFO_IMAGE:
3933 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
3935 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
3936 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
3937 case MONO_PATCH_INFO_CASTCLASS_CACHE:
3939 case MONO_PATCH_INFO_METHOD_REL:
3940 encode_value ((gint)patch_info->data.offset, p, &p);
3942 case MONO_PATCH_INFO_SWITCH: {
3943 gpointer *table = (gpointer *)patch_info->data.table->table;
3946 encode_value (patch_info->data.table->table_size, p, &p);
3947 for (k = 0; k < patch_info->data.table->table_size; k++)
3948 encode_value ((int)(gssize)table [k], p, &p);
3951 case MONO_PATCH_INFO_METHODCONST:
3952 case MONO_PATCH_INFO_METHOD:
3953 case MONO_PATCH_INFO_METHOD_JUMP:
3954 case MONO_PATCH_INFO_ICALL_ADDR:
3955 case MONO_PATCH_INFO_METHOD_RGCTX:
3956 encode_method_ref (acfg, patch_info->data.method, p, &p);
3958 case MONO_PATCH_INFO_INTERNAL_METHOD:
3959 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
3960 guint32 len = strlen (patch_info->data.name);
3962 encode_value (len, p, &p);
3964 memcpy (p, patch_info->data.name, len);
3969 case MONO_PATCH_INFO_LDSTR: {
3970 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
3971 guint32 token = patch_info->data.token->token;
3972 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
3973 encode_value (image_index, p, &p);
3974 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
3977 case MONO_PATCH_INFO_RVA:
3978 case MONO_PATCH_INFO_DECLSEC:
3979 case MONO_PATCH_INFO_LDTOKEN:
3980 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
3981 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
3982 encode_value (patch_info->data.token->token, p, &p);
3983 encode_value (patch_info->data.token->has_context, p, &p);
3984 if (patch_info->data.token->has_context)
3985 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
3987 case MONO_PATCH_INFO_EXC_NAME: {
3988 MonoClass *ex_class;
3991 mono_class_from_name (mono_defaults.exception_class->image,
3992 "System", patch_info->data.target);
3993 g_assert (ex_class);
3994 encode_klass_ref (acfg, ex_class, p, &p);
3997 case MONO_PATCH_INFO_R4:
3998 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4000 case MONO_PATCH_INFO_R8:
4001 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4002 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4004 case MONO_PATCH_INFO_VTABLE:
4005 case MONO_PATCH_INFO_CLASS:
4006 case MONO_PATCH_INFO_IID:
4007 case MONO_PATCH_INFO_ADJUSTED_IID:
4008 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4010 case MONO_PATCH_INFO_CLASS_INIT:
4011 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4012 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4014 case MONO_PATCH_INFO_FIELD:
4015 case MONO_PATCH_INFO_SFLDA:
4016 encode_field_info (acfg, patch_info->data.field, p, &p);
4018 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4020 case MONO_PATCH_INFO_RGCTX_FETCH: {
4021 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4026 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4027 * reference the same method, so encode the method only once.
4029 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
4031 buf2 = g_malloc (1024);
4034 encode_method_ref (acfg, entry->method, p2, &p2);
4035 g_assert (p2 - buf2 < 1024);
4037 offset = add_to_blob (acfg, buf2, p2 - buf2);
4040 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
4045 encode_value (offset, p, &p);
4046 g_assert (entry->info_type < 256);
4047 g_assert (entry->data->type < 256);
4048 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
4049 encode_patch (acfg, entry->data, p, &p);
4052 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4053 case MONO_PATCH_INFO_MONITOR_ENTER:
4054 case MONO_PATCH_INFO_MONITOR_EXIT:
4055 case MONO_PATCH_INFO_SEQ_POINT_INFO:
4057 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
4058 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
4059 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
4061 case MONO_PATCH_INFO_SIGNATURE:
4062 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
4065 g_warning ("unable to handle jump info %d", patch_info->type);
4066 g_assert_not_reached ();
4073 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
4076 guint32 pindex, offset;
4077 MonoJumpInfo *patch_info;
4079 encode_value (n_patches, p, &p);
4081 for (pindex = 0; pindex < patches->len; ++pindex) {
4082 patch_info = g_ptr_array_index (patches, pindex);
4084 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
4088 offset = get_got_offset (acfg, patch_info);
4089 encode_value (offset, p, &p);
4096 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
4100 int pindex, buf_size, n_patches;
4102 MonoJumpInfo *patch_info;
4103 MonoMethodHeader *header;
4104 guint32 method_index;
4106 guint32 first_got_offset;
4108 method = cfg->orig_method;
4109 header = mono_method_get_header (method);
4111 method_index = get_method_index (acfg, method);
4113 /* Sort relocations */
4114 patches = g_ptr_array_new ();
4115 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
4116 g_ptr_array_add (patches, patch_info);
4117 g_ptr_array_sort (patches, compare_patches);
4119 first_got_offset = acfg->cfgs [method_index]->got_offset;
4121 /**********************/
4122 /* Encode method info */
4123 /**********************/
4125 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
4126 p = buf = g_malloc (buf_size);
4128 if (mono_class_get_cctor (method->klass))
4129 encode_klass_ref (acfg, method->klass, p, &p);
4131 /* Not needed when loading the method */
4132 encode_value (0, p, &p);
4135 if (cfg->opt & MONO_OPT_SHARED) {
4136 encode_value (g_list_length (cfg->ldstr_list), p, &p);
4137 for (l = cfg->ldstr_list; l; l = l->next) {
4138 encode_value ((long)l->data, p, &p);
4142 /* Used only in shared mode */
4143 g_assert (!cfg->ldstr_list);
4146 for (pindex = 0; pindex < patches->len; ++pindex) {
4147 patch_info = g_ptr_array_index (patches, pindex);
4149 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
4150 (patch_info->type == MONO_PATCH_INFO_NONE)) {
4151 patch_info->type = MONO_PATCH_INFO_NONE;
4156 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
4157 /* Stored in a GOT slot initialized at module load time */
4158 patch_info->type = MONO_PATCH_INFO_NONE;
4162 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
4163 /* Stored in a GOT slot initialized at module load time */
4164 patch_info->type = MONO_PATCH_INFO_NONE;
4168 if (is_plt_patch (patch_info)) {
4169 /* Calls are made through the PLT */
4170 patch_info->type = MONO_PATCH_INFO_NONE;
4178 g_assert (cfg->has_got_slots);
4180 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
4182 acfg->stats.info_size += p - buf;
4184 g_assert (p - buf < buf_size);
4186 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
4191 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
4193 guint32 cache_index;
4196 /* Reuse the unwind module to canonize and store unwind info entries */
4197 cache_index = mono_cache_unwind_info (encoded, encoded_len);
4199 /* Use +/- 1 to distinguish 0s from missing entries */
4200 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
4208 * It would be easier to use assembler symbols, but the caller needs an
4211 offset = acfg->unwind_info_offset;
4212 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
4213 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
4216 encode_value (encoded_len, p, &p);
4218 acfg->unwind_info_offset += encoded_len + (p - buf);
4224 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
4227 int i, k, buf_size, method_index;
4228 guint32 debug_info_size;
4230 MonoMethodHeader *header;
4231 guint8 *p, *buf, *debug_info;
4232 MonoJitInfo *jinfo = cfg->jit_info;
4234 gboolean use_unwind_ops = FALSE;
4235 MonoSeqPointInfo *seq_points;
4237 method = cfg->orig_method;
4238 code = cfg->native_code;
4239 header = cfg->header;
4241 method_index = get_method_index (acfg, method);
4243 if (!acfg->aot_opts.nodebug) {
4244 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
4247 debug_info_size = 0;
4250 seq_points = cfg->seq_point_info;
4252 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
4253 p = buf = g_malloc (buf_size);
4255 #ifdef MONO_ARCH_HAVE_XP_UNWIND
4256 use_unwind_ops = cfg->unwind_ops != NULL;
4259 flags = (jinfo->has_generic_jit_info ? 1 : 0) | (use_unwind_ops ? 2 : 0) | (header->num_clauses ? 4 : 0) | (seq_points ? 8 : 0) | (cfg->compile_llvm ? 16 : 0) | (jinfo->has_try_block_holes ? 32 : 0) | (cfg->gc_map ? 64 : 0) | (jinfo->has_arch_eh_info ? 128 : 0);
4261 encode_value (flags, p, &p);
4263 if (use_unwind_ops) {
4264 guint32 encoded_len;
4268 * This is a duplicate of the data in the .debug_frame section, but that
4269 * section cannot be accessed using the dl interface.
4271 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
4272 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
4275 encode_value (jinfo->used_regs, p, &p);
4278 /*Encode the number of holes before the number of clauses to make decoding easier*/
4279 if (jinfo->has_try_block_holes) {
4280 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4281 encode_value (table->num_holes, p, &p);
4284 /* Exception table */
4285 if (cfg->compile_llvm) {
4287 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
4288 * since the information is only available to llc. Instead, we let llc save the data
4289 * into the LSDA, and read it from there at runtime.
4291 /* The assembly might be CIL stripped so emit the data ourselves */
4292 if (header->num_clauses)
4293 encode_value (header->num_clauses, p, &p);
4295 for (k = 0; k < header->num_clauses; ++k) {
4296 MonoExceptionClause *clause;
4298 clause = &header->clauses [k];
4300 encode_value (clause->flags, p, &p);
4301 if (clause->data.catch_class) {
4302 encode_value (1, p, &p);
4303 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
4305 encode_value (0, p, &p);
4308 /* Emit a list of nesting clauses */
4309 for (i = 0; i < header->num_clauses; ++i) {
4311 MonoExceptionClause *clause1 = &header->clauses [cindex1];
4313 MonoExceptionClause *clause2 = &header->clauses [cindex2];
4315 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
4316 encode_value (i, p, &p);
4318 encode_value (-1, p, &p);
4321 if (jinfo->num_clauses)
4322 encode_value (jinfo->num_clauses, p, &p);
4324 for (k = 0; k < jinfo->num_clauses; ++k) {
4325 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
4327 encode_value (ei->flags, p, &p);
4328 encode_value (ei->exvar_offset, p, &p);
4330 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
4331 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
4333 if (ei->data.catch_class) {
4334 encode_value (1, p, &p);
4335 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
4337 encode_value (0, p, &p);
4341 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
4342 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
4343 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
4347 if (jinfo->has_generic_jit_info) {
4348 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
4350 if (!cfg->compile_llvm) {
4351 encode_value (gi->has_this ? 1 : 0, p, &p);
4352 encode_value (gi->this_reg, p, &p);
4353 encode_value (gi->this_offset, p, &p);
4357 * Need to encode jinfo->method too, since it is not equal to 'method'
4358 * when using generic sharing.
4360 encode_method_ref (acfg, jinfo->method, p, &p);
4363 if (jinfo->has_try_block_holes) {
4364 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4365 for (i = 0; i < table->num_holes; ++i) {
4366 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
4367 encode_value (hole->clause, p, &p);
4368 encode_value (hole->length, p, &p);
4369 encode_value (hole->offset, p, &p);
4373 if (jinfo->has_arch_eh_info) {
4374 MonoArchEHJitInfo *eh_info;
4376 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
4377 encode_value (eh_info->stack_size, p, &p);
4381 int il_offset, native_offset, last_il_offset, last_native_offset, j;
4383 encode_value (seq_points->len, p, &p);
4384 last_il_offset = last_native_offset = 0;
4385 for (i = 0; i < seq_points->len; ++i) {
4386 SeqPoint *sp = &seq_points->seq_points [i];
4387 il_offset = sp->il_offset;
4388 native_offset = sp->native_offset;
4389 encode_value (il_offset - last_il_offset, p, &p);
4390 encode_value (native_offset - last_native_offset, p, &p);
4391 last_il_offset = il_offset;
4392 last_native_offset = native_offset;
4394 encode_value (sp->next_len, p, &p);
4395 for (j = 0; j < sp->next_len; ++j)
4396 encode_value (sp->next [j], p, &p);
4400 g_assert (debug_info_size < buf_size);
4402 encode_value (debug_info_size, p, &p);
4403 if (debug_info_size) {
4404 memcpy (p, debug_info, debug_info_size);
4405 p += debug_info_size;
4406 g_free (debug_info);
4411 encode_value (cfg->gc_map_size, p, &p);
4412 /* The GC map requires 4 bytes of alignment */
4413 while ((gsize)p % 4)
4415 memcpy (p, cfg->gc_map, cfg->gc_map_size);
4416 p += cfg->gc_map_size;
4419 acfg->stats.ex_info_size += p - buf;
4421 g_assert (p - buf < buf_size);
4424 /* The GC Map requires 4 byte alignment */
4425 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
4430 emit_klass_info (MonoAotCompile *acfg, guint32 token)
4432 MonoClass *klass = mono_class_get (acfg->image, token);
4434 int i, buf_size, res;
4435 gboolean no_special_static, cant_encode;
4436 gpointer iter = NULL;
4439 mono_loader_clear_error ();
4443 p = buf = g_malloc (buf_size);
4445 /* Mark as unusable */
4446 encode_value (-1, p, &p);
4448 res = add_to_blob (acfg, buf, p - buf);
4454 buf_size = 10240 + (klass->vtable_size * 16);
4455 p = buf = g_malloc (buf_size);
4459 mono_class_init (klass);
4461 mono_class_get_nested_types (klass, &iter);
4462 g_assert (klass->nested_classes_inited);
4464 mono_class_setup_vtable (klass);
4467 * Emit all the information which is required for creating vtables so
4468 * the runtime does not need to create the MonoMethod structures which
4469 * take up a lot of space.
4472 no_special_static = !mono_class_has_special_static_fields (klass);
4474 /* Check whenever we have enough info to encode the vtable */
4475 cant_encode = FALSE;
4476 for (i = 0; i < klass->vtable_size; ++i) {
4477 MonoMethod *cm = klass->vtable [i];
4479 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
4483 mono_class_has_finalizer (klass);
4485 if (klass->generic_container || cant_encode) {
4486 encode_value (-1, p, &p);
4488 encode_value (klass->vtable_size, p, &p);
4489 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);
4490 if (klass->has_cctor)
4491 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
4492 if (klass->has_finalize)
4493 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
4495 encode_value (klass->instance_size, p, &p);
4496 encode_value (mono_class_data_size (klass), p, &p);
4497 encode_value (klass->packing_size, p, &p);
4498 encode_value (klass->min_align, p, &p);
4500 for (i = 0; i < klass->vtable_size; ++i) {
4501 MonoMethod *cm = klass->vtable [i];
4504 encode_method_ref (acfg, cm, p, &p);
4506 encode_value (0, p, &p);
4510 acfg->stats.class_info_size += p - buf;
4512 g_assert (p - buf < buf_size);
4513 res = add_to_blob (acfg, buf, p - buf);
4520 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
4522 char *debug_sym = NULL;
4525 case MONO_PATCH_INFO_METHOD:
4526 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
4528 case MONO_PATCH_INFO_INTERNAL_METHOD:
4529 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
4531 case MONO_PATCH_INFO_CLASS_INIT:
4532 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
4533 sanitize_symbol (debug_sym);
4535 case MONO_PATCH_INFO_RGCTX_FETCH:
4536 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
4538 case MONO_PATCH_INFO_ICALL_ADDR: {
4539 char *s = get_debug_sym (ji->data.method, "", cache);
4541 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
4545 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
4546 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
4548 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4549 debug_sym = g_strdup_printf ("plt__generic_class_init");
4559 * Calls made from AOTed code are routed through a table of jumps similar to the
4560 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
4561 * control to the AOT runtime through a trampoline.
4564 emit_plt (MonoAotCompile *acfg)
4570 sprintf (symbol, "plt");
4572 emit_section_change (acfg, ".text", 0);
4573 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
4574 emit_label (acfg, symbol);
4575 emit_label (acfg, acfg->plt_symbol);
4577 for (i = 0; i < acfg->plt_offset; ++i) {
4578 char *debug_sym = NULL;
4579 MonoPltEntry *plt_entry = NULL;
4584 * The first plt entry is unused.
4588 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4593 * If the target is directly callable, alias the plt symbol to point to
4595 * FIXME: Use this to simplify emit_and_reloc_code ().
4596 * FIXME: Avoid the got slot.
4597 * FIXME: Add support to the binary writer.
4599 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
4600 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
4602 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
4603 /* LLVM calls the PLT entries using bl, so emit a stub */
4604 fprintf (acfg->fp, "\n.thumb_func\n");
4605 emit_label (acfg, plt_entry->llvm_symbol);
4606 fprintf (acfg->fp, "bx pc\n");
4607 fprintf (acfg->fp, "nop\n");
4608 fprintf (acfg->fp, ".arm\n");
4609 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
4611 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
4617 debug_sym = plt_entry->debug_sym;
4619 if (acfg->thumb_mixed && !plt_entry->jit_used)
4620 /* Emit only a thumb version */
4623 if (!acfg->thumb_mixed)
4624 emit_label (acfg, plt_entry->llvm_symbol);
4627 if (acfg->need_no_dead_strip)
4628 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4629 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4630 emit_label (acfg, debug_sym);
4633 emit_label (acfg, plt_entry->symbol);
4635 arch_emit_plt_entry (acfg, i);
4638 emit_symbol_size (acfg, debug_sym, ".");
4641 if (acfg->thumb_mixed) {
4642 /* Make sure the ARM symbols don't alias the thumb ones */
4643 emit_zero_bytes (acfg, 16);
4646 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
4649 for (i = 0; i < acfg->plt_offset; ++i) {
4650 char *debug_sym = NULL;
4651 MonoPltEntry *plt_entry = NULL;
4657 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
4660 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
4663 /* Skip plt entries not actually called by LLVM code */
4664 if (!plt_entry->llvm_used)
4667 if (acfg->aot_opts.write_symbols) {
4668 if (plt_entry->debug_sym)
4669 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
4673 #if defined(__APPLE__)
4674 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
4675 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4677 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
4678 emit_label (acfg, debug_sym);
4680 fprintf (acfg->fp, "\n.thumb_func\n");
4682 emit_label (acfg, plt_entry->llvm_symbol);
4684 arch_emit_llvm_plt_entry (acfg, i);
4687 emit_symbol_size (acfg, debug_sym, ".");
4693 emit_symbol_size (acfg, acfg->plt_symbol, ".");
4695 sprintf (symbol, "plt_end");
4696 emit_label (acfg, symbol);
4699 static G_GNUC_UNUSED void
4700 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
4702 char start_symbol [256];
4704 guint32 buf_size, info_offset;
4705 MonoJumpInfo *patch_info;
4716 code_size = info->code_size;
4718 unwind_ops = info->unwind_ops;
4720 #ifdef __native_client_codegen__
4721 mono_nacl_fix_patches (code, ji);
4726 sprintf (start_symbol, "%s", name);
4728 emit_section_change (acfg, ".text", 0);
4729 emit_global (acfg, start_symbol, TRUE);
4730 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4731 emit_label (acfg, start_symbol);
4733 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
4734 emit_label (acfg, symbol);
4737 * The code should access everything through the GOT, so we pass
4740 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
4742 emit_symbol_size (acfg, start_symbol, ".");
4746 /* Sort relocations */
4747 patches = g_ptr_array_new ();
4748 for (patch_info = ji; patch_info; patch_info = patch_info->next)
4749 if (patch_info->type != MONO_PATCH_INFO_NONE)
4750 g_ptr_array_add (patches, patch_info);
4751 g_ptr_array_sort (patches, compare_patches);
4753 buf_size = patches->len * 128 + 128;
4754 buf = g_malloc (buf_size);
4757 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
4758 g_assert (p - buf < buf_size);
4760 sprintf (symbol, "%s_p", name);
4762 info_offset = add_to_blob (acfg, buf, p - buf);
4764 emit_section_change (acfg, RODATA_SECT, 0);
4765 emit_global (acfg, symbol, FALSE);
4766 emit_label (acfg, symbol);
4768 emit_int32 (acfg, info_offset);
4770 /* Emit debug info */
4774 sprintf (symbol, "%s", name);
4775 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
4778 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
4783 emit_trampolines (MonoAotCompile *acfg)
4786 char end_symbol [256];
4787 int i, tramp_got_offset;
4788 MonoAotTrampoline ntype;
4789 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4793 if (!acfg->aot_opts.full_aot)
4796 g_assert (acfg->image->assembly);
4798 /* Currently, we emit most trampolines into the mscorlib AOT image. */
4799 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
4800 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
4801 MonoTrampInfo *info;
4804 * Emit the generic trampolines.
4806 * We could save some code by treating the generic trampolines as a wrapper
4807 * method, but that approach has its own complexities, so we choose the simpler
4810 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
4811 mono_arch_create_generic_trampoline (tramp_type, &info, TRUE);
4812 emit_trampoline (acfg, acfg->got_offset, info);
4815 mono_arch_get_nullified_class_init_trampoline (&info);
4816 emit_trampoline (acfg, acfg->got_offset, info);
4817 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
4818 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
4819 emit_trampoline (acfg, acfg->got_offset, info);
4820 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
4821 emit_trampoline (acfg, acfg->got_offset, info);
4824 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
4825 emit_trampoline (acfg, acfg->got_offset, info);
4827 /* Emit the exception related code pieces */
4828 mono_arch_get_restore_context (&info, TRUE);
4829 emit_trampoline (acfg, acfg->got_offset, info);
4830 mono_arch_get_call_filter (&info, TRUE);
4831 emit_trampoline (acfg, acfg->got_offset, info);
4832 mono_arch_get_throw_exception (&info, TRUE);
4833 emit_trampoline (acfg, acfg->got_offset, info);
4834 mono_arch_get_rethrow_exception (&info, TRUE);
4835 emit_trampoline (acfg, acfg->got_offset, info);
4836 mono_arch_get_throw_corlib_exception (&info, TRUE);
4837 emit_trampoline (acfg, acfg->got_offset, info);
4839 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
4841 GSList *l = mono_arch_get_trampolines (TRUE);
4844 MonoTrampInfo *info = l->data;
4846 emit_trampoline (acfg, acfg->got_offset, info);
4852 for (i = 0; i < 128; ++i) {
4855 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
4856 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4857 emit_trampoline (acfg, acfg->got_offset, info);
4859 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
4860 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
4861 emit_trampoline (acfg, acfg->got_offset, info);
4867 /* delegate_invoke_impl trampolines */
4868 l = mono_arch_get_delegate_invoke_impls ();
4870 MonoTrampInfo *info = l->data;
4872 emit_trampoline (acfg, acfg->got_offset, info);
4877 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
4879 /* Emit trampolines which are numerous */
4882 * These include the following:
4883 * - specific trampolines
4884 * - static rgctx invoke trampolines
4886 * These trampolines have the same code, they are parameterized by GOT
4888 * They are defined in this file, in the arch_... routines instead of
4889 * in tramp-<ARCH>.c, since it is easier to do it this way.
4893 * When running in aot-only mode, we can't create specific trampolines at
4894 * runtime, so we create a few, and save them in the AOT file.
4895 * Normal trampolines embed their argument as a literal inside the
4896 * trampoline code, we can't do that here, so instead we embed an offset
4897 * which needs to be added to the trampoline address to get the address of
4898 * the GOT slot which contains the argument value.
4899 * The generated trampolines jump to the generic trampolines using another
4900 * GOT slot, which will be setup by the AOT loader to point to the
4901 * generic trampoline code of the given type.
4905 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
4909 emit_section_change (acfg, ".text", 0);
4911 tramp_got_offset = acfg->got_offset;
4913 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
4915 case MONO_AOT_TRAMP_SPECIFIC:
4916 sprintf (symbol, "specific_trampolines");
4918 case MONO_AOT_TRAMP_STATIC_RGCTX:
4919 sprintf (symbol, "static_rgctx_trampolines");
4921 case MONO_AOT_TRAMP_IMT_THUNK:
4922 sprintf (symbol, "imt_thunks");
4925 g_assert_not_reached ();
4928 sprintf (end_symbol, "%s_e", symbol);
4930 if (acfg->aot_opts.write_symbols)
4931 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
4933 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4934 emit_label (acfg, symbol);
4936 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
4938 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
4942 case MONO_AOT_TRAMP_SPECIFIC:
4943 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
4944 tramp_got_offset += 2;
4946 case MONO_AOT_TRAMP_STATIC_RGCTX:
4947 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
4948 tramp_got_offset += 2;
4950 case MONO_AOT_TRAMP_IMT_THUNK:
4951 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
4952 tramp_got_offset += 1;
4955 g_assert_not_reached ();
4957 #ifdef __native_client_codegen__
4958 /* align to avoid 32-byte boundary crossings */
4959 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
4962 if (!acfg->trampoline_size [ntype]) {
4963 g_assert (tramp_size);
4964 acfg->trampoline_size [ntype] = tramp_size;
4968 emit_label (acfg, end_symbol);
4971 /* Reserve some entries at the end of the GOT for our use */
4972 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
4975 acfg->got_offset += acfg->num_trampoline_got_entries;
4979 str_begins_with (const char *str1, const char *str2)
4981 int len = strlen (str2);
4982 return strncmp (str1, str2, len) == 0;
4986 mono_aot_readonly_field_override (MonoClassField *field)
4989 for (rdv = readonly_values; rdv; rdv = rdv->next) {
4990 char *p = rdv->name;
4992 len = strlen (field->parent->name_space);
4993 if (strncmp (p, field->parent->name_space, len))
4998 len = strlen (field->parent->name);
4999 if (strncmp (p, field->parent->name, len))
5004 if (strcmp (p, field->name))
5006 switch (rdv->type) {
5008 return &rdv->value.i1;
5010 return &rdv->value.i2;
5012 return &rdv->value.i4;
5021 add_readonly_value (MonoAotOptions *opts, const char *val)
5026 /* the format of val is:
5027 * namespace.typename.fieldname=type/value
5028 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
5030 fval = strrchr (val, '/');
5032 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
5035 tval = strrchr (val, '=');
5037 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
5040 rdv = g_new0 (ReadOnlyValue, 1);
5041 rdv->name = g_malloc0 (tval - val + 1);
5042 memcpy (rdv->name, val, tval - val);
5045 if (strncmp (tval, "i1", 2) == 0) {
5046 rdv->value.i1 = atoi (fval);
5047 rdv->type = MONO_TYPE_I1;
5048 } else if (strncmp (tval, "i2", 2) == 0) {
5049 rdv->value.i2 = atoi (fval);
5050 rdv->type = MONO_TYPE_I2;
5051 } else if (strncmp (tval, "i4", 2) == 0) {
5052 rdv->value.i4 = atoi (fval);
5053 rdv->type = MONO_TYPE_I4;
5055 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
5058 rdv->next = readonly_values;
5059 readonly_values = rdv;
5063 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
5065 gchar **args, **ptr;
5067 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
5068 for (ptr = args; ptr && *ptr; ptr ++) {
5069 const char *arg = *ptr;
5071 if (str_begins_with (arg, "outfile=")) {
5072 opts->outfile = g_strdup (arg + strlen ("outfile="));
5073 } else if (str_begins_with (arg, "save-temps")) {
5074 opts->save_temps = TRUE;
5075 } else if (str_begins_with (arg, "keep-temps")) {
5076 opts->save_temps = TRUE;
5077 } else if (str_begins_with (arg, "write-symbols")) {
5078 opts->write_symbols = TRUE;
5079 } else if (str_begins_with (arg, "no-write-symbols")) {
5080 opts->write_symbols = FALSE;
5081 } else if (str_begins_with (arg, "metadata-only")) {
5082 opts->metadata_only = TRUE;
5083 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
5084 opts->bind_to_runtime_version = TRUE;
5085 } else if (str_begins_with (arg, "full")) {
5086 opts->full_aot = TRUE;
5087 } else if (str_begins_with (arg, "threads=")) {
5088 opts->nthreads = atoi (arg + strlen ("threads="));
5089 } else if (str_begins_with (arg, "static")) {
5090 opts->static_link = TRUE;
5091 opts->no_dlsym = TRUE;
5092 } else if (str_begins_with (arg, "asmonly")) {
5093 opts->asm_only = TRUE;
5094 } else if (str_begins_with (arg, "asmwriter")) {
5095 opts->asm_writer = TRUE;
5096 } else if (str_begins_with (arg, "nodebug")) {
5097 opts->nodebug = TRUE;
5098 } else if (str_begins_with (arg, "ntrampolines=")) {
5099 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
5100 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
5101 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
5102 } else if (str_begins_with (arg, "nimt-trampolines=")) {
5103 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
5104 } else if (str_begins_with (arg, "autoreg")) {
5105 opts->autoreg = TRUE;
5106 } else if (str_begins_with (arg, "tool-prefix=")) {
5107 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
5108 } else if (str_begins_with (arg, "soft-debug")) {
5109 opts->soft_debug = TRUE;
5110 } else if (str_begins_with (arg, "print-skipped")) {
5111 opts->print_skipped_methods = TRUE;
5112 } else if (str_begins_with (arg, "stats")) {
5114 } else if (str_begins_with (arg, "mtriple=")) {
5115 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
5116 } else if (str_begins_with (arg, "llvm-path=")) {
5117 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
5118 } else if (str_begins_with (arg, "readonly-value=")) {
5119 add_readonly_value (opts, arg + strlen ("readonly-value="));
5120 } else if (str_begins_with (arg, "info")) {
5121 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
5123 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
5124 printf ("Supported options for --aot:\n");
5125 printf (" outfile=\n");
5126 printf (" save-temps\n");
5127 printf (" keep-temps\n");
5128 printf (" write-symbols\n");
5129 printf (" metadata-only\n");
5130 printf (" bind-to-runtime-version\n");
5132 printf (" threads=\n");
5133 printf (" static\n");
5134 printf (" asmonly\n");
5135 printf (" asmwriter\n");
5136 printf (" nodebug\n");
5137 printf (" ntrampolines=\n");
5138 printf (" nrgctx-trampolines=\n");
5139 printf (" nimt-trampolines=\n");
5140 printf (" autoreg\n");
5141 printf (" tool-prefix=\n");
5142 printf (" readonly-value=\n");
5143 printf (" soft-debug\n");
5144 printf (" print-skipped\n");
5145 printf (" stats\n");
5147 printf (" help/?\n");
5150 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
5159 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
5161 MonoMethod *method = (MonoMethod*)key;
5162 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
5163 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
5164 MonoAotCompile *acfg = user_data;
5166 new_ji->image = ji->image;
5167 new_ji->token = ji->token;
5168 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
5172 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
5174 if (klass->type_token)
5176 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
5179 return can_encode_class (acfg, klass->element_class);
5184 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
5186 switch (patch_info->type) {
5187 case MONO_PATCH_INFO_METHOD:
5188 case MONO_PATCH_INFO_METHODCONST: {
5189 MonoMethod *method = patch_info->data.method;
5191 if (method->wrapper_type) {
5192 switch (method->wrapper_type) {
5193 case MONO_WRAPPER_NONE:
5194 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5195 case MONO_WRAPPER_XDOMAIN_INVOKE:
5196 case MONO_WRAPPER_STFLD:
5197 case MONO_WRAPPER_LDFLD:
5198 case MONO_WRAPPER_LDFLDA:
5199 case MONO_WRAPPER_LDFLD_REMOTE:
5200 case MONO_WRAPPER_STFLD_REMOTE:
5201 case MONO_WRAPPER_STELEMREF:
5202 case MONO_WRAPPER_ISINST:
5203 case MONO_WRAPPER_PROXY_ISINST:
5204 case MONO_WRAPPER_ALLOC:
5205 case MONO_WRAPPER_REMOTING_INVOKE:
5206 case MONO_WRAPPER_UNKNOWN:
5207 case MONO_WRAPPER_WRITE_BARRIER:
5209 case MONO_WRAPPER_MANAGED_TO_MANAGED:
5210 if (!strcmp (method->name, "ElementAddr"))
5214 case MONO_WRAPPER_CASTCLASS:
5215 if (!strcmp (method->name, "__castclass_with_cache"))
5217 else if (!strcmp (method->name, "__isinst_with_cache"))
5222 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
5226 if (!method->token) {
5227 /* The method is part of a constructed type like Int[,].Set (). */
5228 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
5229 if (method->klass->rank)
5237 case MONO_PATCH_INFO_VTABLE:
5238 case MONO_PATCH_INFO_CLASS_INIT:
5239 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5240 case MONO_PATCH_INFO_CLASS:
5241 case MONO_PATCH_INFO_IID:
5242 case MONO_PATCH_INFO_ADJUSTED_IID:
5243 if (!can_encode_class (acfg, patch_info->data.klass)) {
5244 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
5248 case MONO_PATCH_INFO_RGCTX_FETCH: {
5249 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5251 if (!can_encode_patch (acfg, entry->data))
5265 * AOT compile a given method.
5266 * This function might be called by multiple threads, so it must be thread-safe.
5269 compile_method (MonoAotCompile *acfg, MonoMethod *method)
5272 MonoJumpInfo *patch_info;
5275 MonoMethod *wrapped;
5277 if (acfg->aot_opts.metadata_only)
5280 mono_acfg_lock (acfg);
5281 index = get_method_index (acfg, method);
5282 mono_acfg_unlock (acfg);
5284 /* fixme: maybe we can also precompile wrapper methods */
5285 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
5286 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
5287 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
5288 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
5292 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
5295 wrapped = mono_marshal_method_from_wrapper (method);
5296 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
5297 // FIXME: The wrapper should be generic too, but it is not
5300 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
5303 InterlockedIncrement (&acfg->stats.mcount);
5306 if (method->is_generic || method->klass->generic_container) {
5307 InterlockedIncrement (&acfg->stats.genericcount);
5312 //acfg->aot_opts.print_skipped_methods = TRUE;
5315 * Since these methods are the only ones which are compiled with
5316 * AOT support, and they are not used by runtime startup/shutdown code,
5317 * the runtime will not see AOT methods during AOT compilation,so it
5318 * does not need to support them by creating a fake GOT etc.
5320 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
5321 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
5322 //printf ("F: %s\n", mono_method_full_name (method, TRUE));
5323 InterlockedIncrement (&acfg->stats.genericcount);
5326 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
5327 if (acfg->aot_opts.print_skipped_methods)
5328 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
5329 /* Let the exception happen at runtime */
5333 if (cfg->disable_aot) {
5334 if (acfg->aot_opts.print_skipped_methods)
5335 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
5336 InterlockedIncrement (&acfg->stats.ocount);
5337 mono_destroy_compile (cfg);
5341 /* Nullify patches which need no aot processing */
5342 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5343 switch (patch_info->type) {
5344 case MONO_PATCH_INFO_LABEL:
5345 case MONO_PATCH_INFO_BB:
5346 patch_info->type = MONO_PATCH_INFO_NONE;
5353 /* Collect method->token associations from the cfg */
5354 mono_acfg_lock (acfg);
5355 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
5356 mono_acfg_unlock (acfg);
5359 * Check for absolute addresses.
5362 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5363 switch (patch_info->type) {
5364 case MONO_PATCH_INFO_ABS:
5365 /* unable to handle this */
5374 if (acfg->aot_opts.print_skipped_methods)
5375 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
5376 InterlockedIncrement (&acfg->stats.abscount);
5377 mono_destroy_compile (cfg);
5381 /* Lock for the rest of the code */
5382 mono_acfg_lock (acfg);
5385 * Check for methods/klasses we can't encode.
5388 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5389 if (!can_encode_patch (acfg, patch_info))
5394 if (acfg->aot_opts.print_skipped_methods)
5395 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
5396 acfg->stats.ocount++;
5397 mono_destroy_compile (cfg);
5398 mono_acfg_unlock (acfg);
5402 /* Adds generic instances referenced by this method */
5404 * The depth is used to avoid infinite loops when generic virtual recursion is
5407 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
5409 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5410 switch (patch_info->type) {
5411 case MONO_PATCH_INFO_METHOD: {
5412 MonoMethod *m = patch_info->data.method;
5413 if (m->is_inflated) {
5414 if (!(mono_class_generic_sharing_enabled (m->klass) &&
5415 mono_method_is_generic_sharable_impl (m, FALSE)) &&
5416 !method_has_type_vars (m)) {
5417 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
5418 if (acfg->aot_opts.full_aot)
5419 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
5421 add_extra_method_with_depth (acfg, m, depth + 1);
5424 add_generic_class_with_depth (acfg, m->klass, depth + 5);
5426 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
5427 add_extra_method_with_depth (acfg, m, depth + 1);
5430 case MONO_PATCH_INFO_VTABLE: {
5431 MonoClass *klass = patch_info->data.klass;
5433 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE))
5434 add_generic_class_with_depth (acfg, klass, depth + 5);
5437 case MONO_PATCH_INFO_SFLDA: {
5438 MonoClass *klass = patch_info->data.field->parent;
5440 /* The .cctor needs to run at runtime. */
5441 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
5442 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
5451 /* Determine whenever the method has GOT slots */
5452 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5453 switch (patch_info->type) {
5454 case MONO_PATCH_INFO_GOT_OFFSET:
5455 case MONO_PATCH_INFO_NONE:
5456 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
5458 case MONO_PATCH_INFO_IMAGE:
5459 /* The assembly is stored in GOT slot 0 */
5460 if (patch_info->data.image != acfg->image)
5461 cfg->has_got_slots = TRUE;
5464 if (!is_plt_patch (patch_info))
5465 cfg->has_got_slots = TRUE;
5470 if (!cfg->has_got_slots)
5471 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
5474 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
5476 /* Make a copy of the patch info which is in the mempool */
5478 MonoJumpInfo *patches = NULL, *patches_end = NULL;
5480 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
5481 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
5484 patches = new_patch_info;
5486 patches_end->next = new_patch_info;
5487 patches_end = new_patch_info;
5489 cfg->patch_info = patches;
5491 /* Make a copy of the unwind info */
5493 GSList *l, *unwind_ops;
5497 for (l = cfg->unwind_ops; l; l = l->next) {
5498 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
5499 memcpy (op, l->data, sizeof (MonoUnwindOp));
5500 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
5502 cfg->unwind_ops = g_slist_reverse (unwind_ops);
5504 /* Make a copy of the argument/local info */
5506 MonoInst **args, **locals;
5507 MonoMethodSignature *sig;
5508 MonoMethodHeader *header;
5511 sig = mono_method_signature (method);
5512 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
5513 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
5514 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5515 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
5519 header = mono_method_get_header (method);
5520 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
5521 for (i = 0; i < header->num_locals; ++i) {
5522 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
5523 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
5525 cfg->locals = locals;
5528 /* Free some fields used by cfg to conserve memory */
5529 mono_mempool_destroy (cfg->mempool);
5530 cfg->mempool = NULL;
5531 g_free (cfg->varinfo);
5532 cfg->varinfo = NULL;
5536 mono_regstate_free (cfg->rs);
5540 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
5542 while (index >= acfg->cfgs_size) {
5543 MonoCompile **new_cfgs;
5546 new_size = acfg->cfgs_size * 2;
5547 new_cfgs = g_new0 (MonoCompile*, new_size);
5548 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
5549 g_free (acfg->cfgs);
5550 acfg->cfgs = new_cfgs;
5551 acfg->cfgs_size = new_size;
5553 acfg->cfgs [index] = cfg;
5555 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
5558 if (cfg->orig_method->wrapper_type)
5559 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
5562 mono_acfg_unlock (acfg);
5564 InterlockedIncrement (&acfg->stats.ccount);
5568 compile_thread_main (gpointer *user_data)
5570 MonoDomain *domain = user_data [0];
5571 MonoAotCompile *acfg = user_data [1];
5572 GPtrArray *methods = user_data [2];
5575 mono_thread_attach (domain);
5577 for (i = 0; i < methods->len; ++i)
5578 compile_method (acfg, g_ptr_array_index (methods, i));
5582 load_profile_files (MonoAotCompile *acfg)
5586 int file_index, res, method_index, i;
5589 GList *unordered, *l;
5594 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
5596 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
5601 infile = fopen (tmp, "r");
5604 printf ("Using profile data file '%s'\n", tmp);
5609 res = fscanf (infile, "%32s\n", ver);
5610 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
5611 printf ("Profile file has wrong version or invalid.\n");
5618 MonoMethodDesc *desc;
5621 if (fgets (name, 1023, infile) == NULL)
5624 /* Kill the newline */
5625 if (strlen (name) > 0)
5626 name [strlen (name) - 1] = '\0';
5628 desc = mono_method_desc_new (name, TRUE);
5630 method = mono_method_desc_search_in_image (desc, acfg->image);
5632 if (method && mono_method_get_token (method)) {
5633 token = mono_method_get_token (method);
5634 method_index = mono_metadata_token_index (token) - 1;
5637 for (i = 0; i < acfg->method_order->len; ++i) {
5638 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5644 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
5646 //printf ("No method found matching '%s'.\n", name);
5652 /* Add missing methods */
5654 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
5656 for (i = 0; i < acfg->method_order->len; ++i) {
5657 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
5663 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
5665 unordered = g_list_reverse (unordered);
5666 for (l = unordered; l; l = l->next)
5667 g_ptr_array_add (acfg->method_order, l->data);
5670 /* Used by the LLVM backend */
5672 mono_aot_get_got_offset (MonoJumpInfo *ji)
5674 return get_got_offset (llvm_acfg, ji);
5678 mono_aot_get_method_name (MonoCompile *cfg)
5680 if (llvm_acfg->aot_opts.static_link)
5681 /* Include the assembly name too to avoid duplicate symbol errors */
5682 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
5684 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
5688 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
5690 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
5691 MonoPltEntry *plt_entry;
5694 ji->data.target = data;
5696 if (!can_encode_patch (llvm_acfg, ji))
5699 plt_entry = get_plt_entry (llvm_acfg, ji);
5700 plt_entry->llvm_used = TRUE;
5702 #if defined(__APPLE__)
5703 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
5705 return g_strdup_printf (plt_entry->llvm_symbol);
5710 mono_aot_patch_info_dup (MonoJumpInfo* ji)
5714 mono_acfg_lock (llvm_acfg);
5715 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
5716 mono_acfg_unlock (llvm_acfg);
5726 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
5730 emit_llvm_file (MonoAotCompile *acfg)
5732 char *command, *opts;
5734 MonoJumpInfo *patch_info;
5737 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
5741 /* Compute the final size of the got */
5742 for (i = 0; i < acfg->nmethods; ++i) {
5743 if (acfg->cfgs [i]) {
5744 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
5745 if (patch_info->type != MONO_PATCH_INFO_NONE) {
5746 if (!is_plt_patch (patch_info))
5747 get_got_offset (acfg, patch_info);
5749 get_plt_entry (acfg, patch_info);
5755 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
5757 if (acfg->aot_opts.full_aot) {
5761 * Need to add the got entries used by the trampolines.
5762 * This is only a conservative approximation.
5764 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5765 /* For the generic + rgctx trampolines */
5766 acfg->final_got_size += 200;
5767 /* For the specific trampolines */
5768 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
5769 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
5774 mono_llvm_emit_aot_module ("temp.bc", acfg->final_got_size);
5777 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
5778 * a lot of time, and doesn't seem to save much space.
5779 * The following optimizations cannot be enabled:
5781 * - 'jump-threading' changes our blockaddress references to int constants.
5782 * - 'basiccg' fails because it contains:
5783 * if (CS && !isa<IntrinsicInst>(II)) {
5784 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
5785 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
5786 * The opt list below was produced by taking the output of:
5787 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
5788 * then removing tailcallelim + the global opts, and adding a second gvn.
5790 opts = g_strdup ("-instcombine -simplifycfg");
5791 opts = g_strdup ("-simplifycfg -domtree -domfrontier -scalarrepl -instcombine -simplifycfg -domtree -domfrontier -scalarrepl -simplify-libcalls -instcombine -simplifycfg -instcombine -simplifycfg -reassociate -domtree -loops -loop-simplify -domfrontier -loop-simplify -lcssa -loop-rotate -licm -lcssa -loop-unswitch -instcombine -scalar-evolution -loop-simplify -lcssa -iv-users -indvars -loop-deletion -loop-simplify -lcssa -loop-unroll -instcombine -memdep -gvn -memdep -memcpyopt -sccp -instcombine -domtree -memdep -dse -adce -simplifycfg -preverify -domtree -verify");
5793 command = g_strdup_printf ("%sopt -f %s -o temp.opt.bc temp.bc", acfg->aot_opts.llvm_path, opts);
5794 printf ("Executing opt: %s\n", command);
5795 if (system (command) != 0) {
5801 if (!acfg->llc_args)
5802 acfg->llc_args = g_string_new ("");
5804 /* Verbose asm slows down llc greatly */
5805 g_string_append (acfg->llc_args, " -asm-verbose=false");
5807 if (acfg->aot_opts.mtriple)
5808 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
5810 if (llvm_acfg->aot_opts.static_link)
5811 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
5813 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
5814 unlink (acfg->tmpfname);
5816 command = g_strdup_printf ("%sllc %s -disable-gnu-eh-frame -enable-mono-eh-frame -o %s temp.opt.bc", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname);
5818 printf ("Executing llc: %s\n", command);
5820 if (system (command) != 0) {
5827 emit_code (MonoAotCompile *acfg)
5829 int oindex, i, prev_index;
5831 char end_symbol [256];
5833 #if defined(TARGET_POWERPC64)
5834 sprintf (symbol, ".Lgot_addr");
5835 emit_section_change (acfg, ".text", 0);
5836 emit_alignment (acfg, 8);
5837 emit_label (acfg, symbol);
5838 emit_pointer (acfg, acfg->got_symbol);
5842 * This global symbol is used to compute the address of each method using the
5843 * code_offsets array. It is also used to compute the memory ranges occupied by
5844 * AOT code, so it must be equal to the address of the first emitted method.
5846 sprintf (symbol, "methods");
5847 emit_section_change (acfg, ".text", 0);
5848 emit_alignment (acfg, 8);
5850 for (i = 0; i < acfg->nmethods; ++i) {
5851 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
5852 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
5856 if (i == acfg->nmethods)
5857 /* No LLVM compiled methods */
5858 emit_label (acfg, symbol);
5860 emit_label (acfg, symbol);
5864 * Emit some padding so the local symbol for the first method doesn't have the
5865 * same address as 'methods'.
5867 #if defined(__default_codegen__)
5868 emit_zero_bytes (acfg, 16);
5869 #elif defined(__native_client_codegen__)
5871 const int kPaddingSize = 16;
5872 guint8 pad_buffer[kPaddingSize];
5873 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
5874 emit_bytes (acfg, pad_buffer, kPaddingSize);
5878 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
5882 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
5884 cfg = acfg->cfgs [i];
5889 method = cfg->orig_method;
5891 /* Emit unbox trampoline */
5892 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
5893 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
5895 emit_section_change (acfg, ".text", 0);
5896 #ifdef __native_client_codegen__
5897 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5900 if (acfg->thumb_mixed && cfg->compile_llvm)
5901 fprintf (acfg->fp, "\n.thumb_func\n");
5903 emit_label (acfg, symbol);
5905 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
5908 if (cfg->compile_llvm)
5909 acfg->stats.llvm_count ++;
5911 emit_method_code (acfg, cfg);
5914 sprintf (symbol, "methods_end");
5915 emit_section_change (acfg, ".text", 0);
5916 emit_alignment (acfg, 8);
5917 emit_label (acfg, symbol);
5920 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
5921 * from optimizing them away, since it doesn't see that code_offsets references them.
5922 * JITted methods don't need this since they are referenced using assembler local
5924 * FIXME: This is why write-symbols doesn't work on OSX ?
5926 if (acfg->llvm && acfg->need_no_dead_strip) {
5927 fprintf (acfg->fp, "\n");
5928 for (i = 0; i < acfg->nmethods; ++i) {
5929 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
5930 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
5934 sprintf (symbol, "code_offsets");
5935 emit_section_change (acfg, RODATA_SECT, 1);
5936 emit_alignment (acfg, 8);
5937 emit_label (acfg, symbol);
5939 acfg->stats.offsets_size += acfg->nmethods * 4;
5941 sprintf (end_symbol, "methods");
5942 for (i = 0; i < acfg->nmethods; ++i) {
5943 if (acfg->cfgs [i]) {
5944 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
5946 emit_int32 (acfg, 0xffffffff);
5951 /* Emit a sorted table mapping methods to their unbox trampolines */
5952 sprintf (symbol, "unbox_trampolines");
5953 emit_section_change (acfg, RODATA_SECT, 1);
5954 emit_alignment (acfg, 8);
5955 emit_label (acfg, symbol);
5957 sprintf (end_symbol, "methods");
5959 for (i = 0; i < acfg->nmethods; ++i) {
5964 cfg = acfg->cfgs [i];
5968 method = cfg->orig_method;
5970 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) {
5971 index = get_method_index (acfg, method);
5972 sprintf (symbol, "ut_%d", index);
5974 emit_int32 (acfg, index);
5975 emit_symbol_diff (acfg, symbol, end_symbol, 0);
5976 /* Make sure the table is sorted by index */
5977 g_assert (index > prev_index);
5981 sprintf (symbol, "unbox_trampolines_end");
5982 emit_label (acfg, symbol);
5986 emit_info (MonoAotCompile *acfg)
5992 offsets = g_new0 (gint32, acfg->nmethods);
5994 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
5995 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
5997 if (acfg->cfgs [i]) {
5998 emit_method_info (acfg, acfg->cfgs [i]);
5999 offsets [i] = acfg->cfgs [i]->method_info_offset;
6005 sprintf (symbol, "method_info_offsets");
6006 emit_section_change (acfg, RODATA_SECT, 1);
6007 emit_alignment (acfg, 8);
6008 emit_label (acfg, symbol);
6010 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6015 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
6017 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
6018 #define mix(a,b,c) { \
6019 a -= c; a ^= rot(c, 4); c += b; \
6020 b -= a; b ^= rot(a, 6); a += c; \
6021 c -= b; c ^= rot(b, 8); b += a; \
6022 a -= c; a ^= rot(c,16); c += b; \
6023 b -= a; b ^= rot(a,19); a += c; \
6024 c -= b; c ^= rot(b, 4); b += a; \
6026 #define final(a,b,c) { \
6027 c ^= b; c -= rot(b,14); \
6028 a ^= c; a -= rot(c,11); \
6029 b ^= a; b -= rot(a,25); \
6030 c ^= b; c -= rot(b,16); \
6031 a ^= c; a -= rot(c,4); \
6032 b ^= a; b -= rot(a,14); \
6033 c ^= b; c -= rot(b,24); \
6037 mono_aot_type_hash (MonoType *t1)
6039 guint hash = t1->type;
6041 hash |= t1->byref << 6; /* do not collide with t1->type values */
6043 case MONO_TYPE_VALUETYPE:
6044 case MONO_TYPE_CLASS:
6045 case MONO_TYPE_SZARRAY:
6046 /* check if the distribution is good enough */
6047 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
6049 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
6050 case MONO_TYPE_ARRAY:
6051 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
6052 case MONO_TYPE_GENERICINST:
6053 return ((hash << 5) - hash) ^ 0;
6060 * mono_aot_method_hash:
6062 * Return a hash code for methods which only depends on metadata.
6065 mono_aot_method_hash (MonoMethod *method)
6067 MonoMethodSignature *sig;
6071 guint32 *hashes_start, *hashes;
6073 MonoGenericInst *ginst = NULL;
6075 /* Similar to the hash in mono_method_get_imt_slot () */
6077 sig = mono_method_signature (method);
6079 if (method->is_inflated)
6080 ginst = ((MonoMethodInflated*)method)->context.method_inst;
6082 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
6083 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
6084 hashes = hashes_start;
6086 /* Some wrappers are assigned to random classes */
6087 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
6088 klass = method->klass;
6090 klass = mono_defaults.object_class;
6092 if (!method->wrapper_type) {
6093 char *full_name = mono_type_full_name (&klass->byval_arg);
6095 hashes [0] = mono_metadata_str_hash (full_name);
6099 hashes [0] = mono_metadata_str_hash (klass->name);
6100 hashes [1] = mono_metadata_str_hash (klass->name_space);
6102 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
6103 /* The method name includes a stringified pointer */
6106 hashes [2] = mono_metadata_str_hash (method->name);
6107 hashes [3] = method->wrapper_type;
6108 hashes [4] = mono_aot_type_hash (sig->ret);
6110 for (i = 0; i < sig->param_count; i++) {
6111 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
6114 for (i = 0; i < ginst->type_argc; ++i)
6115 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
6117 g_assert (hindex == hashes_count);
6119 /* Setup internal state */
6120 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
6122 /* Handle most of the hashes */
6123 while (hashes_count > 3) {
6132 /* Handle the last 3 hashes (all the case statements fall through) */
6133 switch (hashes_count) {
6134 case 3 : c += hashes [2];
6135 case 2 : b += hashes [1];
6136 case 1 : a += hashes [0];
6138 case 0: /* nothing left to add */
6142 free (hashes_start);
6151 * mono_aot_wrapper_name:
6153 * Return a string which uniqely identifies the given wrapper method.
6156 mono_aot_wrapper_name (MonoMethod *method)
6158 char *name, *tmpsig, *klass_desc;
6160 tmpsig = mono_signature_get_desc (mono_method_signature (method), TRUE);
6162 switch (method->wrapper_type) {
6163 case MONO_WRAPPER_RUNTIME_INVOKE:
6164 if (!strcmp (method->name, "runtime_invoke_dynamic"))
6165 name = g_strdup_printf ("(wrapper runtime-invoke-dynamic)");
6167 name = g_strdup_printf ("%s (%s)", method->name, tmpsig);
6170 klass_desc = mono_type_full_name (&method->klass->byval_arg);
6171 name = g_strdup_printf ("%s:%s (%s)", klass_desc, method->name, tmpsig);
6172 g_free (klass_desc);
6182 * mono_aot_get_array_helper_from_wrapper;
6184 * Get the helper method in Array called by an array wrapper method.
6187 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
6191 MonoGenericContext ctx;
6192 MonoType *args [16];
6193 char *mname, *iname, *s, *s2, *helper_name = NULL;
6195 prefix = "System.Collections.Generic";
6196 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
6197 s2 = strstr (s, "`1.");
6203 //printf ("X: %s %s\n", iname, mname);
6205 if (!strcmp (iname, "IList"))
6206 helper_name = g_strdup_printf ("InternalArray__%s", mname);
6208 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
6209 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
6211 g_free (helper_name);
6214 if (m->is_generic) {
6215 memset (&ctx, 0, sizeof (ctx));
6216 args [0] = &method->klass->element_class->byval_arg;
6217 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
6218 m = mono_class_inflate_generic_method (m, &ctx);
6224 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
6226 typedef struct HashEntry {
6227 guint32 key, value, index;
6228 struct HashEntry *next;
6232 * emit_extra_methods:
6234 * Emit methods which are not in the METHOD table, like wrappers.
6237 emit_extra_methods (MonoAotCompile *acfg)
6239 int i, table_size, buf_size;
6242 guint32 *info_offsets;
6245 HashEntry *entry, *new_entry;
6246 int nmethods, max_chain_length;
6249 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
6251 /* Emit method info */
6253 for (i = 0; i < acfg->extra_methods->len; ++i) {
6254 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6255 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6261 p = buf = g_malloc (buf_size);
6265 method = cfg->method_to_register;
6267 encode_method_ref (acfg, method, p, &p);
6269 g_assert ((p - buf) < buf_size);
6271 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6276 * Construct a chained hash table for mapping indexes in extra_method_info to
6279 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
6280 table = g_ptr_array_sized_new (table_size);
6281 for (i = 0; i < table_size; ++i)
6282 g_ptr_array_add (table, NULL);
6283 chain_lengths = g_new0 (int, table_size);
6284 max_chain_length = 0;
6285 for (i = 0; i < acfg->extra_methods->len; ++i) {
6286 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6287 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
6293 key = info_offsets [i];
6294 value = get_method_index (acfg, method);
6296 hash = mono_aot_method_hash (method) % table_size;
6298 chain_lengths [hash] ++;
6299 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
6301 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
6302 new_entry->key = key;
6303 new_entry->value = value;
6305 entry = g_ptr_array_index (table, hash);
6306 if (entry == NULL) {
6307 new_entry->index = hash;
6308 g_ptr_array_index (table, hash) = new_entry;
6311 entry = entry->next;
6313 entry->next = new_entry;
6314 new_entry->index = table->len;
6315 g_ptr_array_add (table, new_entry);
6319 //printf ("MAX: %d\n", max_chain_length);
6321 /* Emit the table */
6322 sprintf (symbol, "extra_method_table");
6323 emit_section_change (acfg, RODATA_SECT, 0);
6324 emit_alignment (acfg, 8);
6325 emit_label (acfg, symbol);
6327 emit_int32 (acfg, table_size);
6328 for (i = 0; i < table->len; ++i) {
6329 HashEntry *entry = g_ptr_array_index (table, i);
6331 if (entry == NULL) {
6332 emit_int32 (acfg, 0);
6333 emit_int32 (acfg, 0);
6334 emit_int32 (acfg, 0);
6336 //g_assert (entry->key > 0);
6337 emit_int32 (acfg, entry->key);
6338 emit_int32 (acfg, entry->value);
6340 emit_int32 (acfg, entry->next->index);
6342 emit_int32 (acfg, 0);
6347 * Emit a table reverse mapping method indexes to their index in extra_method_info.
6348 * This is used by mono_aot_find_jit_info ().
6350 sprintf (symbol, "extra_method_info_offsets");
6351 emit_section_change (acfg, RODATA_SECT, 0);
6352 emit_alignment (acfg, 8);
6353 emit_label (acfg, symbol);
6355 emit_int32 (acfg, acfg->extra_methods->len);
6356 for (i = 0; i < acfg->extra_methods->len; ++i) {
6357 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
6359 emit_int32 (acfg, get_method_index (acfg, method));
6360 emit_int32 (acfg, info_offsets [i]);
6365 emit_exception_info (MonoAotCompile *acfg)
6371 offsets = g_new0 (gint32, acfg->nmethods);
6372 for (i = 0; i < acfg->nmethods; ++i) {
6373 if (acfg->cfgs [i]) {
6374 emit_exception_debug_info (acfg, acfg->cfgs [i]);
6375 offsets [i] = acfg->cfgs [i]->ex_info_offset;
6381 sprintf (symbol, "ex_info_offsets");
6382 emit_section_change (acfg, RODATA_SECT, 1);
6383 emit_alignment (acfg, 8);
6384 emit_label (acfg, symbol);
6386 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6391 emit_unwind_info (MonoAotCompile *acfg)
6397 * The unwind info contains a lot of duplicates so we emit each unique
6398 * entry once, and only store the offset from the start of the table in the
6402 sprintf (symbol, "unwind_info");
6403 emit_section_change (acfg, RODATA_SECT, 1);
6404 emit_alignment (acfg, 8);
6405 emit_label (acfg, symbol);
6407 for (i = 0; i < acfg->unwind_ops->len; ++i) {
6408 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
6409 guint8 *unwind_info;
6410 guint32 unwind_info_len;
6414 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
6417 encode_value (unwind_info_len, p, &p);
6418 emit_bytes (acfg, buf, p - buf);
6419 emit_bytes (acfg, unwind_info, unwind_info_len);
6421 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
6426 emit_class_info (MonoAotCompile *acfg)
6432 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
6433 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
6434 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
6436 sprintf (symbol, "class_info_offsets");
6437 emit_section_change (acfg, RODATA_SECT, 1);
6438 emit_alignment (acfg, 8);
6439 emit_label (acfg, symbol);
6441 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
6445 typedef struct ClassNameTableEntry {
6446 guint32 token, index;
6447 struct ClassNameTableEntry *next;
6448 } ClassNameTableEntry;
6451 emit_class_name_table (MonoAotCompile *acfg)
6454 guint32 token, hash;
6459 ClassNameTableEntry *entry, *new_entry;
6462 * Construct a chained hash table for mapping class names to typedef tokens.
6464 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
6465 table = g_ptr_array_sized_new (table_size);
6466 for (i = 0; i < table_size; ++i)
6467 g_ptr_array_add (table, NULL);
6468 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
6469 token = MONO_TOKEN_TYPE_DEF | (i + 1);
6470 klass = mono_class_get (acfg->image, token);
6472 mono_loader_clear_error ();
6475 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
6476 hash = mono_metadata_str_hash (full_name) % table_size;
6479 /* FIXME: Allocate from the mempool */
6480 new_entry = g_new0 (ClassNameTableEntry, 1);
6481 new_entry->token = token;
6483 entry = g_ptr_array_index (table, hash);
6484 if (entry == NULL) {
6485 new_entry->index = hash;
6486 g_ptr_array_index (table, hash) = new_entry;
6489 entry = entry->next;
6491 entry->next = new_entry;
6492 new_entry->index = table->len;
6493 g_ptr_array_add (table, new_entry);
6497 /* Emit the table */
6498 sprintf (symbol, "class_name_table");
6499 emit_section_change (acfg, RODATA_SECT, 0);
6500 emit_alignment (acfg, 8);
6501 emit_label (acfg, symbol);
6503 /* FIXME: Optimize memory usage */
6504 g_assert (table_size < 65000);
6505 emit_int16 (acfg, table_size);
6506 g_assert (table->len < 65000);
6507 for (i = 0; i < table->len; ++i) {
6508 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
6510 if (entry == NULL) {
6511 emit_int16 (acfg, 0);
6512 emit_int16 (acfg, 0);
6514 emit_int16 (acfg, mono_metadata_token_index (entry->token));
6516 emit_int16 (acfg, entry->next->index);
6518 emit_int16 (acfg, 0);
6524 emit_image_table (MonoAotCompile *acfg)
6530 * The image table is small but referenced in a lot of places.
6531 * So we emit it at once, and reference its elements by an index.
6534 sprintf (symbol, "image_table");
6535 emit_section_change (acfg, RODATA_SECT, 1);
6536 emit_alignment (acfg, 8);
6537 emit_label (acfg, symbol);
6539 emit_int32 (acfg, acfg->image_table->len);
6540 for (i = 0; i < acfg->image_table->len; i++) {
6541 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
6542 MonoAssemblyName *aname = &image->assembly->aname;
6544 /* FIXME: Support multi-module assemblies */
6545 g_assert (image->assembly->image == image);
6547 emit_string (acfg, image->assembly_name);
6548 emit_string (acfg, image->guid);
6549 emit_string (acfg, aname->culture ? aname->culture : "");
6550 emit_string (acfg, (const char*)aname->public_key_token);
6552 emit_alignment (acfg, 8);
6553 emit_int32 (acfg, aname->flags);
6554 emit_int32 (acfg, aname->major);
6555 emit_int32 (acfg, aname->minor);
6556 emit_int32 (acfg, aname->build);
6557 emit_int32 (acfg, aname->revision);
6562 emit_got_info (MonoAotCompile *acfg)
6565 int i, first_plt_got_patch, buf_size;
6567 guint32 *got_info_offsets;
6569 /* Add the patches needed by the PLT to the GOT */
6570 acfg->plt_got_offset_base = acfg->got_offset;
6571 first_plt_got_patch = acfg->got_patches->len;
6572 for (i = 1; i < acfg->plt_offset; ++i) {
6573 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
6575 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
6577 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
6580 acfg->got_offset += acfg->plt_offset;
6584 * - optimize offsets table.
6585 * - reduce number of exported symbols.
6586 * - emit info for a klass only once.
6587 * - determine when a method uses a GOT slot which is guaranteed to be already
6589 * - clean up and document the code.
6590 * - use String.Empty in class libs.
6593 /* Encode info required to decode shared GOT entries */
6594 buf_size = acfg->got_patches->len * 128;
6595 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
6596 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
6597 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
6599 if (acfg->plt_offset)
6600 acfg->plt_got_info_offsets [0] = 0;
6601 for (i = 0; i < acfg->got_patches->len; ++i) {
6602 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
6607 encode_value (ji->type, p, &p);
6609 encode_patch (acfg, ji, p, &p);
6610 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
6611 g_assert (p - buf <= buf_size);
6612 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
6614 if (i >= first_plt_got_patch)
6615 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
6616 acfg->stats.got_info_size += p - buf;
6619 /* Emit got_info_offsets table */
6620 sprintf (symbol, "got_info_offsets");
6621 emit_section_change (acfg, RODATA_SECT, 1);
6622 emit_alignment (acfg, 8);
6623 emit_label (acfg, symbol);
6625 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
6626 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
6630 emit_got (MonoAotCompile *acfg)
6635 /* Don't make GOT global so accesses to it don't need relocations */
6636 sprintf (symbol, "%s", acfg->got_symbol);
6637 emit_section_change (acfg, ".bss", 0);
6638 emit_alignment (acfg, 8);
6639 emit_local_symbol (acfg, symbol, "got_end", FALSE);
6640 emit_label (acfg, symbol);
6641 if (acfg->got_offset > 0)
6642 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6644 sprintf (symbol, "got_end");
6645 emit_label (acfg, symbol);
6649 typedef struct GlobalsTableEntry {
6650 guint32 value, index;
6651 struct GlobalsTableEntry *next;
6652 } GlobalsTableEntry;
6655 emit_globals (MonoAotCompile *acfg)
6661 GlobalsTableEntry *entry, *new_entry;
6663 if (!acfg->aot_opts.static_link)
6667 * When static linking, we emit a table containing our globals.
6671 * Construct a chained hash table for mapping global names to their index in
6672 * the globals table.
6674 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
6675 table = g_ptr_array_sized_new (table_size);
6676 for (i = 0; i < table_size; ++i)
6677 g_ptr_array_add (table, NULL);
6678 for (i = 0; i < acfg->globals->len; ++i) {
6679 char *name = g_ptr_array_index (acfg->globals, i);
6681 hash = mono_metadata_str_hash (name) % table_size;
6683 /* FIXME: Allocate from the mempool */
6684 new_entry = g_new0 (GlobalsTableEntry, 1);
6685 new_entry->value = i;
6687 entry = g_ptr_array_index (table, hash);
6688 if (entry == NULL) {
6689 new_entry->index = hash;
6690 g_ptr_array_index (table, hash) = new_entry;
6693 entry = entry->next;
6695 entry->next = new_entry;
6696 new_entry->index = table->len;
6697 g_ptr_array_add (table, new_entry);
6701 /* Emit the table */
6702 sprintf (symbol, ".Lglobals_hash");
6703 emit_section_change (acfg, RODATA_SECT, 0);
6704 emit_alignment (acfg, 8);
6705 emit_label (acfg, symbol);
6707 /* FIXME: Optimize memory usage */
6708 g_assert (table_size < 65000);
6709 emit_int16 (acfg, table_size);
6710 for (i = 0; i < table->len; ++i) {
6711 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
6713 if (entry == NULL) {
6714 emit_int16 (acfg, 0);
6715 emit_int16 (acfg, 0);
6717 emit_int16 (acfg, entry->value + 1);
6719 emit_int16 (acfg, entry->next->index);
6721 emit_int16 (acfg, 0);
6725 /* Emit the names */
6726 for (i = 0; i < acfg->globals->len; ++i) {
6727 char *name = g_ptr_array_index (acfg->globals, i);
6729 sprintf (symbol, "name_%d", i);
6730 emit_section_change (acfg, RODATA_SECT, 1);
6732 emit_alignment (acfg, 4);
6734 emit_label (acfg, symbol);
6735 emit_string (acfg, name);
6738 /* Emit the globals table */
6739 sprintf (symbol, "globals");
6740 emit_section_change (acfg, ".data", 0);
6741 /* This is not a global, since it is accessed by the init function */
6742 emit_alignment (acfg, 8);
6743 emit_label (acfg, symbol);
6745 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
6746 emit_pointer (acfg, symbol);
6748 for (i = 0; i < acfg->globals->len; ++i) {
6749 char *name = g_ptr_array_index (acfg->globals, i);
6751 sprintf (symbol, "name_%d", i);
6752 emit_pointer (acfg, symbol);
6754 sprintf (symbol, "%s", name);
6755 emit_pointer (acfg, symbol);
6757 /* Null terminate the table */
6758 emit_int32 (acfg, 0);
6759 emit_int32 (acfg, 0);
6763 emit_autoreg (MonoAotCompile *acfg)
6768 * Emit a function into the .ctor section which will be called by the ELF
6769 * loader to register this module with the runtime.
6771 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
6774 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
6776 arch_emit_autoreg (acfg, symbol);
6782 emit_mem_end (MonoAotCompile *acfg)
6786 sprintf (symbol, "mem_end");
6787 emit_section_change (acfg, ".text", 1);
6788 emit_alignment (acfg, 8);
6789 emit_label (acfg, symbol);
6793 * Emit a structure containing all the information not stored elsewhere.
6796 emit_file_info (MonoAotCompile *acfg)
6801 const char *gc_name;
6804 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
6806 if (acfg->aot_opts.bind_to_runtime_version) {
6807 build_info = mono_get_runtime_build_info ();
6808 emit_string_symbol (acfg, "runtime_version", build_info);
6809 g_free (build_info);
6811 emit_string_symbol (acfg, "runtime_version", "");
6814 /* Emit a string holding the assembly name */
6815 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
6818 * The managed allocators are GC specific, so can't use an AOT image created by one GC
6821 gc_name = mono_gc_get_gc_name ();
6822 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
6824 sprintf (symbol, "mono_aot_file_info");
6825 emit_section_change (acfg, ".data", 0);
6826 emit_alignment (acfg, 8);
6827 emit_label (acfg, symbol);
6828 if (!acfg->aot_opts.static_link)
6829 emit_global (acfg, symbol, FALSE);
6831 /* The data emitted here must match MonoAotFileInfo. */
6833 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
6834 emit_int32 (acfg, 0);
6837 * We emit pointers to our data structures instead of emitting global symbols which
6838 * point to them, to reduce the number of globals, and because using globals leads to
6839 * various problems (i.e. arm/thumb).
6841 emit_pointer (acfg, acfg->got_symbol);
6842 emit_pointer (acfg, "methods");
6845 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
6847 emit_pointer (acfg, "mono_eh_frame");
6849 emit_pointer (acfg, NULL);
6851 emit_pointer (acfg, "blob");
6852 emit_pointer (acfg, "class_name_table");
6853 emit_pointer (acfg, "class_info_offsets");
6854 emit_pointer (acfg, "method_info_offsets");
6855 emit_pointer (acfg, "ex_info_offsets");
6856 emit_pointer (acfg, "code_offsets");
6857 emit_pointer (acfg, "extra_method_info_offsets");
6858 emit_pointer (acfg, "extra_method_table");
6859 emit_pointer (acfg, "got_info_offsets");
6860 emit_pointer (acfg, "methods_end");
6861 emit_pointer (acfg, "unwind_info");
6862 emit_pointer (acfg, "mem_end");
6863 emit_pointer (acfg, "image_table");
6864 emit_pointer (acfg, "plt");
6865 emit_pointer (acfg, "plt_end");
6866 emit_pointer (acfg, "assembly_guid");
6867 emit_pointer (acfg, "runtime_version");
6868 if (acfg->num_trampoline_got_entries) {
6869 emit_pointer (acfg, "specific_trampolines");
6870 emit_pointer (acfg, "static_rgctx_trampolines");
6871 emit_pointer (acfg, "imt_thunks");
6873 emit_pointer (acfg, NULL);
6874 emit_pointer (acfg, NULL);
6875 emit_pointer (acfg, NULL);
6877 if (acfg->thumb_mixed) {
6878 emit_pointer (acfg, "thumb_end");
6880 emit_pointer (acfg, NULL);
6882 if (acfg->aot_opts.static_link) {
6883 emit_pointer (acfg, "globals");
6885 emit_pointer (acfg, NULL);
6887 emit_pointer (acfg, "assembly_name");
6888 emit_pointer (acfg, "unbox_trampolines");
6889 emit_pointer (acfg, "unbox_trampolines_end");
6891 emit_int32 (acfg, acfg->plt_got_offset_base);
6892 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
6893 emit_int32 (acfg, acfg->plt_offset);
6894 emit_int32 (acfg, acfg->nmethods);
6895 emit_int32 (acfg, acfg->flags);
6896 emit_int32 (acfg, acfg->opts);
6897 emit_int32 (acfg, gc_name_offset);
6899 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6900 emit_int32 (acfg, acfg->num_trampolines [i]);
6901 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6902 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
6903 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
6904 emit_int32 (acfg, acfg->trampoline_size [i]);
6906 #if defined (TARGET_ARM) && defined (__APPLE__)
6911 t.type = MONO_TYPE_R8;
6912 mono_type_size (&t, &align);
6914 emit_int32 (acfg, align);
6916 t.type = MONO_TYPE_I8;
6917 mono_type_size (&t, &align);
6919 emit_int32 (acfg, align);
6922 emit_int32 (acfg, __alignof__ (double));
6923 emit_int32 (acfg, __alignof__ (gint64));
6926 if (acfg->aot_opts.static_link) {
6930 * Emit a global symbol which can be passed by an embedding app to
6931 * mono_aot_register_module (). The symbol points to a pointer to the the file info
6934 #if defined(__APPLE__) && !defined(__native_client_codegen__)
6935 sprintf (symbol, "_mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6937 sprintf (symbol, "mono_aot_module_%s_info", acfg->image->assembly->aname.name);
6940 /* Get rid of characters which cannot occur in symbols */
6942 for (p = symbol; *p; ++p) {
6943 if (!(isalnum (*p) || *p == '_'))
6946 acfg->static_linking_symbol = g_strdup (symbol);
6947 emit_global_inner (acfg, symbol, FALSE);
6948 emit_label (acfg, symbol);
6949 emit_pointer (acfg, "mono_aot_file_info");
6954 emit_blob (MonoAotCompile *acfg)
6958 sprintf (symbol, "blob");
6959 emit_section_change (acfg, RODATA_SECT, 1);
6960 emit_alignment (acfg, 8);
6961 emit_label (acfg, symbol);
6963 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
6967 emit_dwarf_info (MonoAotCompile *acfg)
6969 #ifdef EMIT_DWARF_INFO
6971 char symbol [128], symbol2 [128];
6973 /* DIEs for methods */
6974 for (i = 0; i < acfg->nmethods; ++i) {
6975 MonoCompile *cfg = acfg->cfgs [i];
6980 // FIXME: LLVM doesn't define .Lme_...
6981 if (cfg->compile_llvm)
6984 sprintf (symbol, "%s", cfg->asm_symbol);
6985 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
6987 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 ()));
6993 collect_methods (MonoAotCompile *acfg)
6996 MonoImage *image = acfg->image;
6998 /* Collect methods */
6999 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
7001 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
7003 method = mono_get_method (acfg->image, token, NULL);
7006 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
7010 /* Load all methods eagerly to skip the slower lazy loading code */
7011 mono_class_setup_methods (method->klass);
7013 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7014 /* Compile the wrapper instead */
7015 /* We do this here instead of add_wrappers () because it is easy to do it here */
7016 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
7020 /* FIXME: Some mscorlib methods don't have debug info */
7022 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
7023 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7024 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7025 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
7026 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
7027 if (!mono_debug_lookup_method (method)) {
7028 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
7035 /* Since we add the normal methods first, their index will be equal to their zero based token index */
7036 add_method_with_index (acfg, method, i, FALSE);
7037 acfg->method_index ++;
7040 add_generic_instances (acfg);
7042 if (acfg->aot_opts.full_aot)
7043 add_wrappers (acfg);
7047 compile_methods (MonoAotCompile *acfg)
7051 if (acfg->aot_opts.nthreads > 0) {
7056 gpointer *user_data;
7057 MonoMethod **methods;
7059 methods_len = acfg->methods->len;
7061 len = acfg->methods->len / acfg->aot_opts.nthreads;
7064 * Partition the list of methods into fragments, and hand it to threads to
7067 threads = g_ptr_array_new ();
7068 /* Make a copy since acfg->methods is modified by compile_method () */
7069 methods = g_new0 (MonoMethod*, methods_len);
7070 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
7071 for (i = 0; i < methods_len; ++i)
7072 methods [i] = g_ptr_array_index (acfg->methods, i);
7074 while (i < methods_len) {
7075 frag = g_ptr_array_new ();
7076 for (j = 0; j < len; ++j) {
7077 if (i < methods_len) {
7078 g_ptr_array_add (frag, methods [i]);
7083 user_data = g_new0 (gpointer, 3);
7084 user_data [0] = mono_domain_get ();
7085 user_data [1] = acfg;
7086 user_data [2] = frag;
7088 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
7089 g_ptr_array_add (threads, handle);
7093 for (i = 0; i < threads->len; ++i) {
7094 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
7100 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
7101 for (i = methods_len; i < acfg->methods->len; ++i) {
7102 /* This can new methods to acfg->methods */
7103 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
7108 compile_asm (MonoAotCompile *acfg)
7110 char *command, *objfile;
7111 char *outfile_name, *tmp_outfile_name;
7112 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
7114 #if defined(TARGET_AMD64)
7115 #define AS_OPTIONS "--64"
7116 #elif defined(TARGET_POWERPC64)
7117 #define AS_OPTIONS "-a64 -mppc64"
7118 #define LD_OPTIONS "-m elf64ppc"
7119 #elif defined(sparc) && SIZEOF_VOID_P == 8
7120 #define AS_OPTIONS "-xarch=v9"
7121 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
7122 #define AS_OPTIONS "-arch i386 -W"
7124 #define AS_OPTIONS ""
7127 #ifdef __native_client_codegen__
7128 #if defined(TARGET_AMD64)
7129 #define AS_NAME "nacl64-as"
7131 #define AS_NAME "nacl-as"
7134 #define AS_NAME "as"
7138 #define LD_OPTIONS ""
7141 #define EH_LD_OPTIONS ""
7143 if (acfg->aot_opts.asm_only) {
7144 printf ("Output file: '%s'.\n", acfg->tmpfname);
7145 if (acfg->aot_opts.static_link)
7146 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7150 if (acfg->aot_opts.static_link) {
7151 if (acfg->aot_opts.outfile)
7152 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7154 objfile = g_strdup_printf ("%s.o", acfg->image->name);
7156 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
7158 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);
7159 printf ("Executing the native assembler: %s\n", command);
7160 if (system (command) != 0) {
7168 if (acfg->aot_opts.static_link) {
7169 printf ("Output file: '%s'.\n", objfile);
7170 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7175 if (acfg->aot_opts.outfile)
7176 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7178 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7180 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7183 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7184 #elif defined(__ppc__) && defined(__APPLE__)
7185 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7186 #elif defined(HOST_WIN32)
7187 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7188 #elif defined(TARGET_X86) && defined(__APPLE__) && !defined(__native_client_codegen__)
7189 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7191 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
7193 printf ("Executing the native linker: %s\n", command);
7194 if (system (command) != 0) {
7195 g_free (tmp_outfile_name);
7196 g_free (outfile_name);
7204 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
7205 printf ("Stripping the binary: %s\n", com);
7209 #if defined(TARGET_ARM) && !defined(__APPLE__)
7211 * gas generates 'mapping symbols' each time code and data is mixed, which
7212 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
7214 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
7215 printf ("Stripping the binary: %s\n", command);
7216 if (system (command) != 0) {
7217 g_free (tmp_outfile_name);
7218 g_free (outfile_name);
7225 rename (tmp_outfile_name, outfile_name);
7227 g_free (tmp_outfile_name);
7228 g_free (outfile_name);
7231 if (acfg->aot_opts.save_temps)
7232 printf ("Retained input file.\n");
7234 unlink (acfg->tmpfname);
7239 static MonoAotCompile*
7240 acfg_create (MonoAssembly *ass, guint32 opts)
7242 MonoImage *image = ass->image;
7243 MonoAotCompile *acfg;
7246 acfg = g_new0 (MonoAotCompile, 1);
7247 acfg->methods = g_ptr_array_new ();
7248 acfg->method_indexes = g_hash_table_new (NULL, NULL);
7249 acfg->method_depth = g_hash_table_new (NULL, NULL);
7250 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
7251 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7252 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7253 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
7254 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7255 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
7256 acfg->got_patches = g_ptr_array_new ();
7257 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
7258 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
7259 acfg->image_hash = g_hash_table_new (NULL, NULL);
7260 acfg->image_table = g_ptr_array_new ();
7261 acfg->globals = g_ptr_array_new ();
7262 acfg->image = image;
7264 acfg->mempool = mono_mempool_new ();
7265 acfg->extra_methods = g_ptr_array_new ();
7266 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
7267 acfg->unwind_ops = g_ptr_array_new ();
7268 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
7269 acfg->method_order = g_ptr_array_new ();
7270 acfg->export_names = g_hash_table_new (NULL, NULL);
7271 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
7272 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
7273 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
7274 InitializeCriticalSection (&acfg->mutex);
7280 acfg_free (MonoAotCompile *acfg)
7284 img_writer_destroy (acfg->w);
7285 for (i = 0; i < acfg->nmethods; ++i)
7287 g_free (acfg->cfgs [i]);
7288 g_free (acfg->cfgs);
7289 g_free (acfg->static_linking_symbol);
7290 g_free (acfg->got_symbol);
7291 g_free (acfg->plt_symbol);
7292 g_ptr_array_free (acfg->methods, TRUE);
7293 g_ptr_array_free (acfg->got_patches, TRUE);
7294 g_ptr_array_free (acfg->image_table, TRUE);
7295 g_ptr_array_free (acfg->globals, TRUE);
7296 g_ptr_array_free (acfg->unwind_ops, TRUE);
7297 g_hash_table_destroy (acfg->method_indexes);
7298 g_hash_table_destroy (acfg->method_depth);
7299 g_hash_table_destroy (acfg->plt_offset_to_entry);
7300 g_hash_table_destroy (acfg->patch_to_plt_entry);
7301 g_hash_table_destroy (acfg->patch_to_got_offset);
7302 g_hash_table_destroy (acfg->method_to_cfg);
7303 g_hash_table_destroy (acfg->token_info_hash);
7304 g_hash_table_destroy (acfg->image_hash);
7305 g_hash_table_destroy (acfg->unwind_info_offsets);
7306 g_hash_table_destroy (acfg->method_label_hash);
7307 g_hash_table_destroy (acfg->export_names);
7308 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
7309 g_hash_table_destroy (acfg->klass_blob_hash);
7310 g_hash_table_destroy (acfg->method_blob_hash);
7311 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
7312 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
7313 g_free (acfg->patch_to_got_offset_by_type);
7314 mono_mempool_destroy (acfg->mempool);
7319 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
7321 MonoImage *image = ass->image;
7323 MonoAotCompile *acfg;
7324 char *outfile_name, *tmp_outfile_name, *p;
7328 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
7330 acfg = acfg_create (ass, opts);
7332 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
7333 acfg->aot_opts.write_symbols = TRUE;
7334 acfg->aot_opts.ntrampolines = 1024;
7335 acfg->aot_opts.nrgctx_trampolines = 1024;
7336 acfg->aot_opts.nimt_trampolines = 128;
7337 acfg->aot_opts.llvm_path = g_strdup ("");
7339 mono_aot_parse_options (aot_options, &acfg->aot_opts);
7341 if (acfg->aot_opts.static_link)
7342 acfg->aot_opts.autoreg = TRUE;
7344 //acfg->aot_opts.print_skipped_methods = TRUE;
7346 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
7347 if (acfg->aot_opts.full_aot) {
7348 printf ("--aot=full is not supported on this platform.\n");
7353 if (acfg->aot_opts.static_link)
7354 acfg->aot_opts.asm_writer = TRUE;
7356 if (acfg->aot_opts.soft_debug) {
7357 MonoDebugOptions *opt = mini_get_debug_options ();
7359 opt->mdb_optimizations = TRUE;
7360 opt->gen_seq_points = TRUE;
7362 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
7363 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
7366 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
7369 if (mono_use_llvm) {
7371 acfg->aot_opts.asm_writer = TRUE;
7372 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
7374 if (acfg->aot_opts.soft_debug) {
7375 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
7380 if (acfg->aot_opts.full_aot)
7381 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
7383 load_profile_files (acfg);
7385 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
7386 #ifdef MONO_ARCH_GSHARED_SUPPORTED
7387 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
7389 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
7391 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
7395 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
7396 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
7397 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
7399 /* Get rid of characters which cannot occur in symbols */
7400 for (p = acfg->got_symbol_base; *p; ++p) {
7401 if (!(isalnum (*p) || *p == '_'))
7404 for (p = acfg->plt_symbol; *p; ++p) {
7405 if (!(isalnum (*p) || *p == '_'))
7408 for (p = acfg->assembly_name_sym; *p; ++p) {
7409 if (!(isalnum (*p) || *p == '_'))
7413 acfg->method_index = 1;
7415 collect_methods (acfg);
7417 acfg->cfgs_size = acfg->methods->len + 32;
7418 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
7420 /* PLT offset 0 is reserved for the PLT trampoline */
7421 acfg->plt_offset = 1;
7426 mono_llvm_create_aot_module (acfg->got_symbol_base);
7430 /* GOT offset 0 is reserved for the address of the current assembly */
7434 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7435 ji->type = MONO_PATCH_INFO_IMAGE;
7436 ji->data.image = acfg->image;
7438 get_got_offset (acfg, ji);
7440 /* Slot 1 is reserved for the mscorlib got addr */
7441 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7442 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
7443 get_got_offset (acfg, ji);
7445 /* This is very common */
7446 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
7447 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
7448 get_got_offset (acfg, ji);
7453 compile_methods (acfg);
7457 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
7463 if (acfg->aot_opts.asm_only) {
7464 if (acfg->aot_opts.outfile)
7465 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7467 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7469 acfg->tmpfname = g_strdup ("temp.s");
7472 emit_llvm_file (acfg);
7476 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
7477 if (acfg->aot_opts.outfile)
7478 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7480 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7483 * Can't use g_file_open_tmp () as it will be deleted at exit, and
7484 * it might be in another file system so the rename () won't work.
7486 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7488 acfg->fp = fopen (tmp_outfile_name, "w");
7490 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
7494 acfg->w = img_writer_create (acfg->fp, TRUE);
7495 acfg->use_bin_writer = TRUE;
7498 /* Append to the .s file created by llvm */
7499 /* FIXME: Use multiple files instead */
7500 acfg->fp = fopen (acfg->tmpfname, "a+");
7502 if (acfg->aot_opts.asm_only) {
7503 if (acfg->aot_opts.outfile)
7504 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7506 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
7507 acfg->fp = fopen (acfg->tmpfname, "w+");
7509 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
7510 acfg->fp = fdopen (i, "w+");
7512 if (acfg->fp == 0) {
7513 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
7517 acfg->w = img_writer_create (acfg->fp, FALSE);
7519 tmp_outfile_name = NULL;
7520 outfile_name = NULL;
7523 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
7525 /* Compute symbols for methods */
7526 for (i = 0; i < acfg->nmethods; ++i) {
7527 if (acfg->cfgs [i]) {
7528 MonoCompile *cfg = acfg->cfgs [i];
7529 int method_index = get_method_index (acfg, cfg->orig_method);
7531 if (COMPILE_LLVM (cfg))
7532 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
7534 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
7538 if (!acfg->aot_opts.nodebug)
7539 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
7541 img_writer_emit_start (acfg->w);
7544 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
7546 if (acfg->thumb_mixed) {
7549 * This global symbol marks the end of THUMB code, and the beginning of ARM
7550 * code generated by our JIT.
7552 sprintf (symbol, "thumb_end");
7553 emit_section_change (acfg, ".text", 0);
7554 emit_label (acfg, symbol);
7555 emit_zero_bytes (acfg, 16);
7557 fprintf (acfg->fp, ".arm\n");
7564 emit_extra_methods (acfg);
7566 emit_trampolines (acfg);
7568 emit_class_name_table (acfg);
7570 emit_got_info (acfg);
7572 emit_exception_info (acfg);
7574 emit_unwind_info (acfg);
7576 emit_class_info (acfg);
7580 emit_image_table (acfg);
7584 emit_file_info (acfg);
7588 emit_globals (acfg);
7590 emit_autoreg (acfg);
7593 emit_dwarf_info (acfg);
7594 mono_dwarf_writer_close (acfg->dwarf);
7597 emit_mem_end (acfg);
7599 if (acfg->need_pt_gnu_stack) {
7600 /* This is required so the .so doesn't have an executable stack */
7601 /* The bin writer already emits this */
7602 if (!acfg->use_bin_writer)
7603 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
7608 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
7611 g_assert (acfg->got_offset <= acfg->final_got_size);
7613 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);
7616 res = img_writer_emit_writeout (acfg->w);
7621 if (acfg->use_bin_writer) {
7622 int err = rename (tmp_outfile_name, outfile_name);
7625 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
7629 res = compile_asm (acfg);
7636 acfg->stats.link_time = TV_ELAPSED (atv, btv);
7638 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);
7639 if (acfg->stats.genericcount)
7640 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
7641 if (acfg->stats.abscount)
7642 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
7643 if (acfg->stats.lmfcount)
7644 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
7645 if (acfg->stats.ocount)
7646 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
7648 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
7649 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);
7650 printf ("Direct calls: %d (%d%%)\n", acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
7652 if (acfg->aot_opts.stats) {
7655 printf ("GOT slot distribution:\n");
7656 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
7657 if (acfg->stats.got_slot_types [i])
7658 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
7661 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);
7673 mono_aot_readonly_field_override (MonoClassField *field)
7679 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)