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.
25 #include <sys/types.h>
46 #include <mono/metadata/tabledefs.h>
47 #include <mono/metadata/class.h>
48 #include <mono/metadata/object.h>
49 #include <mono/metadata/tokentype.h>
50 #include <mono/metadata/appdomain.h>
51 #include <mono/metadata/debug-helpers.h>
52 #include <mono/metadata/assembly.h>
53 #include <mono/metadata/metadata-internals.h>
54 #include <mono/metadata/marshal.h>
55 #include <mono/metadata/gc-internal.h>
56 #include <mono/metadata/monitor.h>
57 #include <mono/metadata/mempool-internals.h>
58 #include <mono/metadata/mono-endian.h>
59 #include <mono/metadata/threads-types.h>
60 #include <mono/utils/mono-logger-internal.h>
61 #include <mono/utils/mono-compiler.h>
62 #include <mono/utils/mono-time.h>
63 #include <mono/utils/mono-mmap.h>
66 #include "image-writer.h"
67 #include "dwarfwriter.h"
70 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
72 #if defined(__linux__) || defined(__native_client_codegen__)
73 #define RODATA_SECT ".rodata"
75 #define RODATA_SECT ".text"
78 #define TV_DECLARE(name) gint64 name
79 #define TV_GETTIME(tv) tv = mono_100ns_ticks ()
80 #define TV_ELAPSED(start,end) (((end) - (start)) / 10)
83 #define SHARED_EXT ".dll"
84 #elif defined(__ppc__) && defined(TARGET_MACH)
85 #define SHARED_EXT ".dylib"
86 #elif defined(TARGET_MACH) && defined(TARGET_X86) && !defined(__native_client_codegen__)
87 #define SHARED_EXT ".dylib"
88 #elif defined(TARGET_MACH) && defined(TARGET_AMD64) && !defined(__native_client_codegen__)
89 #define SHARED_EXT ".dylib"
91 #define SHARED_EXT ".so"
94 #define ALIGN_TO(val,align) ((((guint64)val) + ((align) - 1)) & ~((align) - 1))
95 #define ALIGN_PTR_TO(ptr,align) (gpointer)((((gssize)(ptr)) + (align - 1)) & (~(align - 1)))
96 #define ROUND_DOWN(VALUE,SIZE) ((VALUE) & ~((SIZE) - 1))
98 /* predefined values for static readonly fields without needed to run the .cctor */
99 typedef struct _ReadOnlyValue ReadOnlyValue;
100 struct _ReadOnlyValue {
103 int type; /* to be used later for typechecking to prevent user errors */
112 static ReadOnlyValue *readonly_values = NULL;
114 typedef struct MonoAotOptions {
117 gboolean write_symbols;
118 gboolean metadata_only;
119 gboolean bind_to_runtime_version;
122 gboolean static_link;
126 gboolean dwarf_debug;
128 gboolean log_generics;
129 gboolean direct_pinvoke;
130 gboolean direct_icalls;
131 gboolean no_direct_calls;
132 gboolean use_trampolines_page;
133 gboolean no_instances;
136 int nrgctx_trampolines;
137 int nimt_trampolines;
138 int ngsharedvt_arg_trampolines;
139 int nrgctx_fetch_trampolines;
140 gboolean print_skipped_methods;
148 typedef struct MonoAotStats {
149 int ccount, mcount, lmfcount, abscount, gcount, ocount, genericcount;
150 int code_size, info_size, ex_info_size, unwind_info_size, got_size, class_info_size, got_info_size;
151 int methods_without_got_slots, direct_calls, all_calls, llvm_count;
152 int got_slots, offsets_size;
153 int got_slot_types [MONO_PATCH_INFO_NONE];
154 int got_slot_info_sizes [MONO_PATCH_INFO_NONE];
155 int jit_time, gen_time, link_time;
158 typedef struct MonoAotCompile {
161 GHashTable *method_indexes;
162 GHashTable *method_depth;
165 GHashTable *patch_to_plt_entry;
166 GHashTable *plt_offset_to_entry;
167 GHashTable *patch_to_got_offset;
168 GHashTable **patch_to_got_offset_by_type;
169 GPtrArray *got_patches;
170 GHashTable *image_hash;
171 GHashTable *method_to_cfg;
172 GHashTable *token_info_hash;
173 GHashTable *method_to_pinvoke_import;
174 GPtrArray *extra_methods;
175 GPtrArray *image_table;
177 GPtrArray *method_order;
178 GHashTable *export_names;
179 /* Maps MonoClass* -> blob offset */
180 GHashTable *klass_blob_hash;
181 /* Maps MonoMethod* -> blob offset */
182 GHashTable *method_blob_hash;
183 guint32 *plt_got_info_offsets;
184 guint32 got_offset, plt_offset, plt_got_offset_base;
185 guint32 final_got_size;
186 /* Number of GOT entries reserved for trampolines */
187 guint32 num_trampoline_got_entries;
189 guint32 num_trampolines [MONO_AOT_TRAMP_NUM];
190 guint32 trampoline_got_offset_base [MONO_AOT_TRAMP_NUM];
191 guint32 trampoline_size [MONO_AOT_TRAMP_NUM];
193 MonoAotOptions aot_opts;
197 MonoMemPool *mempool;
200 char *static_linking_symbol;
201 CRITICAL_SECTION mutex;
202 gboolean use_bin_writer;
204 MonoDwarfWriter *dwarf;
208 GHashTable *unwind_info_offsets;
209 GPtrArray *unwind_ops;
210 guint32 unwind_info_offset;
211 char *got_symbol_base;
214 GHashTable *method_label_hash;
215 const char *temp_prefix;
216 const char *user_symbol_prefix;
217 const char *llvm_label_prefix;
218 guint32 label_generator;
220 MonoAotFileFlags flags;
221 MonoDynamicStream blob;
222 MonoClass **typespec_classes;
225 char *assembly_name_sym;
226 GHashTable *plt_entry_debug_sym_cache;
227 gboolean thumb_mixed, need_no_dead_strip, need_pt_gnu_stack;
228 GHashTable *ginst_hash;
229 gboolean global_symbols;
230 gboolean direct_method_addresses;
235 char *symbol, *llvm_symbol, *debug_sym;
237 gboolean jit_used, llvm_used;
240 #define mono_acfg_lock(acfg) EnterCriticalSection (&((acfg)->mutex))
241 #define mono_acfg_unlock(acfg) LeaveCriticalSection (&((acfg)->mutex))
243 /* This points to the current acfg in LLVM mode */
244 static MonoAotCompile *llvm_acfg;
246 #ifdef HAVE_ARRAY_ELEM_INIT
247 #define MSGSTRFIELD(line) MSGSTRFIELD1(line)
248 #define MSGSTRFIELD1(line) str##line
249 static const struct msgstr_t {
250 #define PATCH_INFO(a,b) char MSGSTRFIELD(__LINE__) [sizeof (b)];
251 #include "patch-info.h"
254 #define PATCH_INFO(a,b) b,
255 #include "patch-info.h"
258 static const gint16 opidx [] = {
259 #define PATCH_INFO(a,b) [MONO_PATCH_INFO_ ## a] = offsetof (struct msgstr_t, MSGSTRFIELD(__LINE__)),
260 #include "patch-info.h"
264 static G_GNUC_UNUSED const char*
265 get_patch_name (int info)
267 return (const char*)&opstr + opidx [info];
271 #define PATCH_INFO(a,b) b,
272 static const char* const
273 patch_types [MONO_PATCH_INFO_NUM + 1] = {
274 #include "patch-info.h"
278 static G_GNUC_UNUSED const char*
279 get_patch_name (int info)
281 return patch_types [info];
287 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache);
289 /* Wrappers around the image writer functions */
292 emit_section_change (MonoAotCompile *acfg, const char *section_name, int subsection_index)
294 img_writer_emit_section_change (acfg->w, section_name, subsection_index);
298 emit_push_section (MonoAotCompile *acfg, const char *section_name, int subsection)
300 img_writer_emit_push_section (acfg->w, section_name, subsection);
304 emit_pop_section (MonoAotCompile *acfg)
306 img_writer_emit_pop_section (acfg->w);
310 emit_local_symbol (MonoAotCompile *acfg, const char *name, const char *end_label, gboolean func)
312 img_writer_emit_local_symbol (acfg->w, name, end_label, func);
316 emit_label (MonoAotCompile *acfg, const char *name)
318 img_writer_emit_label (acfg->w, name);
322 emit_bytes (MonoAotCompile *acfg, const guint8* buf, int size)
324 img_writer_emit_bytes (acfg->w, buf, size);
328 emit_string (MonoAotCompile *acfg, const char *value)
330 img_writer_emit_string (acfg->w, value);
334 emit_line (MonoAotCompile *acfg)
336 img_writer_emit_line (acfg->w);
340 emit_alignment (MonoAotCompile *acfg, int size)
342 img_writer_emit_alignment (acfg->w, size);
346 emit_pointer_unaligned (MonoAotCompile *acfg, const char *target)
348 img_writer_emit_pointer_unaligned (acfg->w, target);
352 emit_pointer (MonoAotCompile *acfg, const char *target)
354 img_writer_emit_pointer (acfg->w, target);
358 emit_pointer_2 (MonoAotCompile *acfg, const char *prefix, const char *target)
360 if (prefix [0] != '\0') {
361 char *s = g_strdup_printf ("%s%s", prefix, target);
362 img_writer_emit_pointer (acfg->w, s);
365 img_writer_emit_pointer (acfg->w, target);
370 emit_int16 (MonoAotCompile *acfg, int value)
372 img_writer_emit_int16 (acfg->w, value);
376 emit_int32 (MonoAotCompile *acfg, int value)
378 img_writer_emit_int32 (acfg->w, value);
382 emit_symbol_diff (MonoAotCompile *acfg, const char *end, const char* start, int offset)
384 img_writer_emit_symbol_diff (acfg->w, end, start, offset);
388 emit_zero_bytes (MonoAotCompile *acfg, int num)
390 img_writer_emit_zero_bytes (acfg->w, num);
394 emit_byte (MonoAotCompile *acfg, guint8 val)
396 img_writer_emit_byte (acfg->w, val);
399 #ifdef __native_client_codegen__
401 emit_nacl_call_alignment (MonoAotCompile *acfg)
403 img_writer_emit_nacl_call_alignment (acfg->w);
407 static G_GNUC_UNUSED void
408 emit_global_inner (MonoAotCompile *acfg, const char *name, gboolean func)
410 img_writer_emit_global (acfg->w, name, func);
414 emit_global (MonoAotCompile *acfg, const char *name, gboolean func)
416 if (acfg->aot_opts.no_dlsym) {
417 g_ptr_array_add (acfg->globals, g_strdup (name));
418 img_writer_emit_local_symbol (acfg->w, name, NULL, func);
420 img_writer_emit_global (acfg->w, name, func);
425 emit_symbol_size (MonoAotCompile *acfg, const char *name, const char *end_label)
427 img_writer_emit_symbol_size (acfg->w, name, end_label);
431 emit_string_symbol (MonoAotCompile *acfg, const char *name, const char *value)
433 img_writer_emit_section_change (acfg->w, RODATA_SECT, 1);
435 /* On apple, all symbols need to be aligned to avoid warnings from ld */
436 emit_alignment (acfg, 4);
438 img_writer_emit_label (acfg->w, name);
439 img_writer_emit_string (acfg->w, value);
442 static G_GNUC_UNUSED void
443 emit_uleb128 (MonoAotCompile *acfg, guint32 value)
446 guint8 b = value & 0x7f;
448 if (value != 0) /* more bytes to come */
454 static G_GNUC_UNUSED void
455 emit_sleb128 (MonoAotCompile *acfg, gint64 value)
458 gboolean negative = (value < 0);
465 /* the following is unnecessary if the
466 * implementation of >>= uses an arithmetic rather
467 * than logical shift for a signed left operand
471 value |= - ((gint64)1 <<(size - 7));
472 /* sign bit of byte is second high order bit (0x40) */
473 if ((value == 0 && !(byte & 0x40)) ||
474 (value == -1 && (byte & 0x40)))
478 emit_byte (acfg, byte);
482 static G_GNUC_UNUSED void
483 encode_uleb128 (guint32 value, guint8 *buf, guint8 **endbuf)
488 guint8 b = value & 0x7f;
490 if (value != 0) /* more bytes to come */
498 static G_GNUC_UNUSED void
499 encode_sleb128 (gint32 value, guint8 *buf, guint8 **endbuf)
502 gboolean negative = (value < 0);
510 /* the following is unnecessary if the
511 * implementation of >>= uses an arithmetic rather
512 * than logical shift for a signed left operand
516 value |= - (1 <<(size - 7));
517 /* sign bit of byte is second high order bit (0x40) */
518 if ((value == 0 && !(byte & 0x40)) ||
519 (value == -1 && (byte & 0x40)))
529 /* ARCHITECTURE SPECIFIC CODE */
531 #if defined(TARGET_X86) || defined(TARGET_AMD64) || defined(TARGET_ARM) || defined(TARGET_POWERPC)
532 #define EMIT_DWARF_INFO 1
535 #if defined(TARGET_ARM)
536 #define AOT_FUNC_ALIGNMENT 4
538 #define AOT_FUNC_ALIGNMENT 16
540 #if (defined(TARGET_X86) || defined(TARGET_AMD64)) && defined(__native_client_codegen__)
541 #undef AOT_FUNC_ALIGNMENT
542 #define AOT_FUNC_ALIGNMENT 32
545 #if defined(TARGET_POWERPC64) && !defined(__mono_ilp32__)
546 #define PPC_LD_OP "ld"
547 #define PPC_LDX_OP "ldx"
549 #define PPC_LD_OP "lwz"
550 #define PPC_LDX_OP "lwzx"
554 #define AOT_TARGET_STR "AMD64"
559 #define AOT_TARGET_STR "ARM (MACH)"
561 #define AOT_TARGET_STR "ARM (!MACH)"
565 #ifdef TARGET_POWERPC64
566 #ifdef __mono_ilp32__
567 #define AOT_TARGET_STR "POWERPC64 (mono ilp32)"
569 #define AOT_TARGET_STR "POWERPC64 (!mono ilp32)"
572 #ifdef TARGET_POWERPC
573 #ifdef __mono_ilp32__
574 #define AOT_TARGET_STR "POWERPC (mono ilp32)"
576 #define AOT_TARGET_STR "POWERPC (!mono ilp32)"
583 #define AOT_TARGET_STR "X86 (WIN32)"
584 #elif defined(__native_client_codegen__)
585 #define AOT_TARGET_STR "X86 (native client codegen)"
587 #define AOT_TARGET_STR "X86 (!native client codegen)"
591 #ifndef AOT_TARGET_STR
592 #define AOT_TARGET_STR ""
596 arch_init (MonoAotCompile *acfg)
598 acfg->llc_args = g_string_new ("");
599 acfg->as_args = g_string_new ("");
602 * The prefix LLVM likes to put in front of symbol names on darwin.
603 * The mach-os specs require this for globals, but LLVM puts them in front of all
604 * symbols. We need to handle this, since we need to refer to LLVM generated
607 acfg->llvm_label_prefix = "";
608 acfg->user_symbol_prefix = "";
611 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "darwin")) {
612 g_string_append (acfg->llc_args, "-mattr=+v6");
615 g_string_append (acfg->llc_args, " -mattr=+vfp2,-neon,+d16");
616 g_string_append (acfg->as_args, " -mfpu=vfp3");
618 g_string_append (acfg->llc_args, " -soft-float");
621 if (acfg->aot_opts.mtriple && strstr (acfg->aot_opts.mtriple, "thumb"))
622 acfg->thumb_mixed = TRUE;
624 if (acfg->aot_opts.mtriple)
625 mono_arch_set_target (acfg->aot_opts.mtriple);
629 acfg->user_symbol_prefix = "_";
630 acfg->llvm_label_prefix = "_";
631 acfg->need_no_dead_strip = TRUE;
634 #if defined(__linux__) && !defined(TARGET_ARM)
635 acfg->need_pt_gnu_stack = TRUE;
639 acfg->direct_method_addresses = TRUE;
640 acfg->global_symbols = TRUE;
645 * arch_emit_direct_call:
647 * Emit a direct call to the symbol TARGET. CALL_SIZE is set to the size of the
651 arch_emit_direct_call (MonoAotCompile *acfg, const char *target, gboolean external, int *call_size)
653 #if defined(TARGET_X86) || defined(TARGET_AMD64)
654 /* Need to make sure this is exactly 5 bytes long */
655 if (external && !acfg->use_bin_writer) {
656 img_writer_emit_unset_mode (acfg->w);
657 fprintf (acfg->fp, "call %s\n", target);
659 emit_byte (acfg, '\xe8');
660 emit_symbol_diff (acfg, target, ".", -4);
663 #elif defined(TARGET_ARM)
664 if (acfg->use_bin_writer) {
671 img_writer_emit_reloc (acfg->w, R_ARM_CALL, target, -8);
672 emit_bytes (acfg, buf, 4);
674 img_writer_emit_unset_mode (acfg->w);
675 fprintf (acfg->fp, "bl %s\n", target);
678 #elif defined(TARGET_POWERPC)
679 if (acfg->use_bin_writer) {
680 g_assert_not_reached ();
682 img_writer_emit_unset_mode (acfg->w);
683 fprintf (acfg->fp, "bl %s\n", target);
687 g_assert_not_reached ();
693 * - we use an approach similar to the x86 abi: reserve a register (r30) to hold
695 * - The full-aot trampolines need access to the GOT of mscorlib, so we store
696 * in in the 2. slot of every GOT, and require every method to place the GOT
697 * address in r30, even when it doesn't access the GOT otherwise. This way,
698 * the trampolines can compute the mscorlib GOT address by loading 4(r30).
703 * PPC64 uses function descriptors which greatly complicate all code, since
704 * these are used very inconsistently in the runtime. Some functions like
705 * mono_compile_method () return ftn descriptors, while others like the
706 * trampoline creation functions do not.
707 * We assume that all GOT slots contain function descriptors, and create
708 * descriptors in aot-runtime.c when needed.
709 * The ppc64 abi uses r2 to hold the address of the TOC/GOT, which is loaded
710 * from function descriptors, we could do the same, but it would require
711 * rewriting all the ppc/aot code to handle function descriptors properly.
712 * So instead, we use the same approach as on PPC32.
713 * This is a horrible mess, but fixing it would probably lead to an even bigger
719 * - similar to the PPC32 design, we reserve EBX to hold the GOT pointer.
722 #ifdef MONO_ARCH_AOT_SUPPORTED
724 * arch_emit_got_offset:
726 * The memory pointed to by CODE should hold native code for computing the GOT
727 * address. Emit this code while patching it with the offset between code and
728 * the GOT. CODE_SIZE is set to the number of bytes emitted.
731 arch_emit_got_offset (MonoAotCompile *acfg, guint8 *code, int *code_size)
733 #if defined(TARGET_POWERPC64)
734 g_assert (!acfg->use_bin_writer);
735 img_writer_emit_unset_mode (acfg->w);
737 * The ppc32 code doesn't seem to work on ppc64, the assembler complains about
738 * unsupported relocations. So we store the got address into the .Lgot_addr
739 * symbol which is in the text segment, compute its address, and load it.
741 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
742 fprintf (acfg->fp, "lis 0, (.Lgot_addr + 4 - .L%d)@h\n", acfg->label_generator);
743 fprintf (acfg->fp, "ori 0, 0, (.Lgot_addr + 4 - .L%d)@l\n", acfg->label_generator);
744 fprintf (acfg->fp, "add 30, 30, 0\n");
745 fprintf (acfg->fp, "%s 30, 0(30)\n", PPC_LD_OP);
746 acfg->label_generator ++;
748 #elif defined(TARGET_POWERPC)
749 g_assert (!acfg->use_bin_writer);
750 img_writer_emit_unset_mode (acfg->w);
751 fprintf (acfg->fp, ".L%d:\n", acfg->label_generator);
752 fprintf (acfg->fp, "lis 0, (%s + 4 - .L%d)@h\n", acfg->got_symbol, acfg->label_generator);
753 fprintf (acfg->fp, "ori 0, 0, (%s + 4 - .L%d)@l\n", acfg->got_symbol, acfg->label_generator);
754 acfg->label_generator ++;
757 guint32 offset = mono_arch_get_patch_offset (code);
758 emit_bytes (acfg, code, offset);
759 emit_symbol_diff (acfg, acfg->got_symbol, ".", offset);
761 *code_size = offset + 4;
766 * arch_emit_got_access:
768 * The memory pointed to by CODE should hold native code for loading a GOT
769 * slot. Emit this code while patching it so it accesses the GOT slot GOT_SLOT.
770 * CODE_SIZE is set to the number of bytes emitted.
773 arch_emit_got_access (MonoAotCompile *acfg, guint8 *code, int got_slot, int *code_size)
775 /* Emit beginning of instruction */
776 emit_bytes (acfg, code, mono_arch_get_patch_offset (code));
778 /* Emit the offset */
780 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer)) - 4));
781 *code_size = mono_arch_get_patch_offset (code) + 4;
782 #elif defined(TARGET_X86)
783 emit_int32 (acfg, (unsigned int) ((got_slot * sizeof (gpointer))));
784 *code_size = mono_arch_get_patch_offset (code) + 4;
785 #elif defined(TARGET_ARM)
786 emit_symbol_diff (acfg, acfg->got_symbol, ".", (unsigned int) ((got_slot * sizeof (gpointer))) - 12);
787 *code_size = mono_arch_get_patch_offset (code) + 4;
788 #elif defined(TARGET_POWERPC)
794 ppc_load32 (code, ppc_r0, got_slot * sizeof (gpointer));
795 g_assert (code - buf == 8);
796 emit_bytes (acfg, buf, code - buf);
797 *code_size = code - buf;
800 g_assert_not_reached ();
807 * arch_emit_plt_entry:
809 * Emit code for the PLT entry with index INDEX.
812 arch_emit_plt_entry (MonoAotCompile *acfg, int index)
814 #if defined(TARGET_X86)
815 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
816 #if defined(__default_codegen__)
817 /* jmp *<offset>(%ebx) */
818 emit_byte (acfg, 0xff);
819 emit_byte (acfg, 0xa3);
820 emit_int32 (acfg, offset);
821 /* Used by mono_aot_get_plt_info_offset */
822 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
823 #elif defined(__native_client_codegen__)
824 const guint8 kSizeOfNaClJmp = 11;
825 guint8 bytes[kSizeOfNaClJmp];
826 guint8 *pbytes = &bytes[0];
828 x86_jump_membase32 (pbytes, X86_EBX, offset);
829 emit_bytes (acfg, bytes, kSizeOfNaClJmp);
830 /* four bytes of data, used by mono_arch_patch_plt_entry */
831 /* For Native Client, make this work with data embedded in push. */
832 emit_byte (acfg, 0x68); /* hide data in a push */
833 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
834 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
835 #endif /*__native_client_codegen__*/
836 #elif defined(TARGET_AMD64)
837 #if defined(__default_codegen__)
839 * We can't emit jumps because they are 32 bits only so they can't be patched.
840 * So we make indirect calls through GOT entries which are patched by the AOT
841 * loader to point to .Lpd entries.
843 /* jmpq *<offset>(%rip) */
844 emit_byte (acfg, '\xff');
845 emit_byte (acfg, '\x25');
846 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
847 /* Used by mono_aot_get_plt_info_offset */
848 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
849 #elif defined(__native_client_codegen__)
851 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
852 guint8 *code = buf_aligned;
854 /* mov <OFFSET>(%rip), %r11d */
855 emit_byte (acfg, '\x45');
856 emit_byte (acfg, '\x8b');
857 emit_byte (acfg, '\x1d');
858 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) -4);
860 amd64_jump_reg (code, AMD64_R11);
861 /* This should be constant for the plt patch */
862 g_assert ((size_t)(code-buf_aligned) == 10);
863 emit_bytes (acfg, buf_aligned, code - buf_aligned);
865 /* Hide data in a push imm32 so it passes validation */
866 emit_byte (acfg, 0x68); /* push */
867 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
868 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
869 #endif /*__native_client_codegen__*/
870 #elif defined(TARGET_ARM)
875 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 0);
876 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
877 emit_bytes (acfg, buf, code - buf);
878 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) - 4);
879 /* Used by mono_aot_get_plt_info_offset */
880 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
881 #elif defined(TARGET_POWERPC)
882 guint32 offset = (acfg->plt_got_offset_base + index) * sizeof (gpointer);
884 /* The GOT address is guaranteed to be in r30 by OP_LOAD_GOTADDR */
885 g_assert (!acfg->use_bin_writer);
886 img_writer_emit_unset_mode (acfg->w);
887 fprintf (acfg->fp, "lis 11, %d@h\n", offset);
888 fprintf (acfg->fp, "ori 11, 11, %d@l\n", offset);
889 fprintf (acfg->fp, "add 11, 11, 30\n");
890 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
891 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
892 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
893 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
895 fprintf (acfg->fp, "mtctr 11\n");
896 fprintf (acfg->fp, "bctr\n");
897 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
899 g_assert_not_reached ();
904 arch_emit_llvm_plt_entry (MonoAotCompile *acfg, int index)
906 #if defined(TARGET_ARM)
908 /* LLVM calls the PLT entries using bl, so emit a stub */
909 /* FIXME: Too much overhead on every call */
910 fprintf (acfg->fp, ".thumb_func\n");
911 fprintf (acfg->fp, "bx pc\n");
912 fprintf (acfg->fp, "nop\n");
913 fprintf (acfg->fp, ".arm\n");
915 /* LLVM calls the PLT entries using bl, so these have to be thumb2 */
916 /* The caller already transitioned to thumb */
917 /* The code below should be 12 bytes long */
918 fprintf (acfg->fp, "ldr ip, [pc, #8]\n");
919 /* thumb can't encode ld pc, [pc, ip] */
920 fprintf (acfg->fp, "add ip, pc, ip\n");
921 fprintf (acfg->fp, "ldr ip, [ip, #0]\n");
922 fprintf (acfg->fp, "bx ip\n");
923 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((acfg->plt_got_offset_base + index) * sizeof (gpointer)) + 4);
924 emit_int32 (acfg, acfg->plt_got_info_offsets [index]);
926 g_assert_not_reached ();
931 * arch_emit_specific_trampoline_pages:
933 * Emits a page full of trampolines: each trampoline uses its own address to
934 * lookup both the generic trampoline code and the data argument.
935 * This page can be remapped in process multiple times so we can get an
936 * unlimited number of trampolines.
937 * Specifically this implementation uses the following trick: two memory pages
938 * are allocated, with the first containing the data and the second containing the trampolines.
939 * To reduce trampoline size, each trampoline jumps at the start of the page where a common
940 * implementation does all the lifting.
941 * Note that the ARM single trampoline size is 8 bytes, exactly like the data that needs to be stored
942 * on the arm 32 bit system.
945 arch_emit_specific_trampoline_pages (MonoAotCompile *acfg)
947 #if defined(TARGET_ARM)
950 guint8 *loop_start, *loop_branch_back, *loop_end_check, *imt_found_check;
952 #define COMMON_TRAMP_SIZE 16
953 int count = (mono_pagesize () - COMMON_TRAMP_SIZE) / 8;
954 int imm8, rot_amount;
957 if (!acfg->aot_opts.use_trampolines_page)
960 sprintf (symbol, "%sspecific_trampolines_page", acfg->user_symbol_prefix);
961 emit_alignment (acfg, mono_pagesize ());
962 emit_global (acfg, symbol, TRUE);
963 emit_label (acfg, symbol);
965 /* emit the generic code first, the trampoline address + 8 is in the lr register */
967 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
968 ARM_SUB_REG_IMM (code, ARMREG_LR, ARMREG_LR, imm8, rot_amount);
969 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_LR, -8);
970 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_LR, -4);
972 g_assert (code - buf == COMMON_TRAMP_SIZE);
975 emit_bytes (acfg, buf, code - buf);
977 for (i = 0; i < count; ++i) {
979 ARM_PUSH (code, 0x5fff);
981 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
982 g_assert (code - buf == 8);
983 emit_bytes (acfg, buf, code - buf);
986 /* now the rgctx trampolines: each specific trampolines puts in the ip register
987 * the instruction pointer address, so the generic trampoline at the start of the page
988 * subtracts 4096 to get to the data page and loads the values
989 * We again fit the generic trampiline in 16 bytes.
991 sprintf (symbol, "%srgctx_trampolines_page", acfg->user_symbol_prefix);
992 emit_global (acfg, symbol, TRUE);
993 emit_label (acfg, symbol);
995 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
996 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
997 ARM_LDR_IMM (code, MONO_ARCH_RGCTX_REG, ARMREG_IP, -8);
998 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1000 g_assert (code - buf == COMMON_TRAMP_SIZE);
1003 emit_bytes (acfg, buf, code - buf);
1005 for (i = 0; i < count; ++i) {
1007 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1009 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1010 g_assert (code - buf == 8);
1011 emit_bytes (acfg, buf, code - buf);
1015 * gsharedvt arg trampolines: see arch_emit_gsharedvt_arg_trampoline ()
1017 sprintf (symbol, "%sgsharedvt_arg_trampolines_page", acfg->user_symbol_prefix);
1018 emit_global (acfg, symbol, TRUE);
1019 emit_label (acfg, symbol);
1021 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1022 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1023 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1024 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1025 ARM_LDR_IMM (code, ARMREG_PC, ARMREG_IP, -4);
1026 g_assert (code - buf == COMMON_TRAMP_SIZE);
1028 emit_bytes (acfg, buf, code - buf);
1030 for (i = 0; i < count; ++i) {
1032 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1034 arm_patch (code - 4, code - COMMON_TRAMP_SIZE - 8 * (i + 1));
1035 g_assert (code - buf == 8);
1036 emit_bytes (acfg, buf, code - buf);
1039 /* now the imt trampolines: each specific trampolines puts in the ip register
1040 * the instruction pointer address, so the generic trampoline at the start of the page
1041 * subtracts 4096 to get to the data page and loads the values
1042 * We again fit the generic trampiline in 16 bytes.
1044 #define IMT_TRAMP_SIZE 72
1045 sprintf (symbol, "%simt_trampolines_page", acfg->user_symbol_prefix);
1046 emit_global (acfg, symbol, TRUE);
1047 emit_label (acfg, symbol);
1049 /* Need at least two free registers, plus a slot for storing the pc */
1050 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1052 imm8 = mono_arm_is_rotated_imm8 (mono_pagesize (), &rot_amount);
1053 ARM_SUB_REG_IMM (code, ARMREG_IP, ARMREG_IP, imm8, rot_amount);
1054 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_IP, -8);
1056 /* The IMT method is in v5, r0 has the imt array address */
1059 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1060 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1061 imt_found_check = code;
1062 ARM_B_COND (code, ARMCOND_EQ, 0);
1064 /* End-of-loop check */
1065 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1066 loop_end_check = code;
1067 ARM_B_COND (code, ARMCOND_EQ, 0);
1070 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1071 loop_branch_back = code;
1073 arm_patch (loop_branch_back, loop_start);
1076 arm_patch (imt_found_check, code);
1077 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1078 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1079 /* Save it to the third stack slot */
1080 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1081 /* Restore the registers and branch */
1082 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1085 arm_patch (loop_end_check, code);
1086 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1087 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1088 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1092 g_assert (code - buf == IMT_TRAMP_SIZE);
1093 emit_bytes (acfg, buf, code - buf);
1095 for (i = 0; i < count; ++i) {
1097 ARM_MOV_REG_REG (code, ARMREG_IP, ARMREG_PC);
1099 arm_patch (code - 4, code - IMT_TRAMP_SIZE - 8 * (i + 1));
1100 g_assert (code - buf == 8);
1101 emit_bytes (acfg, buf, code - buf);
1107 * arch_emit_specific_trampoline:
1109 * Emit code for a specific trampoline. OFFSET is the offset of the first of
1110 * two GOT slots which contain the generic trampoline address and the trampoline
1111 * argument. TRAMP_SIZE is set to the size of the emitted trampoline.
1114 arch_emit_specific_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1117 * The trampolines created here are variations of the specific
1118 * trampolines created in mono_arch_create_specific_trampoline (). The
1120 * - the generic trampoline address is taken from a got slot.
1121 * - the offset of the got slot where the trampoline argument is stored
1122 * is embedded in the instruction stream, and the generic trampoline
1123 * can load the argument by loading the offset, adding it to the
1124 * address of the trampoline to get the address of the got slot, and
1125 * loading the argument from there.
1126 * - all the trampolines should be of the same length.
1128 #if defined(TARGET_AMD64)
1129 #if defined(__default_codegen__)
1130 /* This should be exactly 16 bytes long */
1132 /* call *<offset>(%rip) */
1133 emit_byte (acfg, '\x41');
1134 emit_byte (acfg, '\xff');
1135 emit_byte (acfg, '\x15');
1136 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1137 /* This should be relative to the start of the trampoline */
1138 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset+1) * sizeof (gpointer)) + 7);
1139 emit_zero_bytes (acfg, 5);
1140 #elif defined(__native_client_codegen__)
1142 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1143 guint8 *code = buf_aligned;
1148 /* Emit this call in 'code' so we can find out how long it is. */
1149 amd64_call_reg (code, AMD64_R11);
1150 call_start = mono_arch_nacl_skip_nops (buf_aligned);
1151 call_len = code - call_start;
1153 /* The tramp_size is twice the NaCl alignment because it starts with */
1154 /* a call which needs to be aligned to the end of the boundary. */
1155 *tramp_size = kNaClAlignment*2;
1157 /* Emit nops to align call site below which is 7 bytes plus */
1158 /* the length of the call sequence emitted above. */
1159 /* Note: this requires the specific trampoline starts on a */
1160 /* kNaclAlignedment aligned address, which it does because */
1161 /* it's its own function that is aligned. */
1162 guint8 nop_buf[256];
1163 guint8 *nopbuf_aligned = ALIGN_TO (nop_buf, kNaClAlignment);
1164 guint8 *nopbuf_end = mono_arch_nacl_pad (nopbuf_aligned, kNaClAlignment - 7 - (call_len));
1165 emit_bytes (acfg, nopbuf_aligned, nopbuf_end - nopbuf_aligned);
1167 /* The trampoline is stored at the offset'th pointer, the -4 is */
1168 /* present because RIP relative addressing starts at the end of */
1169 /* the current instruction, while the label "." is relative to */
1170 /* the beginning of the current asm location, which in this case */
1171 /* is not the mov instruction, but the offset itself, due to the */
1172 /* way the bytes and ints are emitted here. */
1173 got_offset = (offset * sizeof(gpointer)) - 4;
1175 /* mov <OFFSET>(%rip), %r11d */
1176 emit_byte (acfg, '\x45');
1177 emit_byte (acfg, '\x8b');
1178 emit_byte (acfg, '\x1d');
1179 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1182 emit_bytes (acfg, call_start, call_len);
1184 /* The arg is stored at the offset+1 pointer, relative to beginning */
1185 /* of trampoline: 7 for mov, plus the call length, and 1 for push. */
1186 got_offset = ((offset + 1) * sizeof(gpointer)) + 7 + call_len + 1;
1188 /* We can't emit this data directly, hide in a "push imm32" */
1189 emit_byte (acfg, '\x68'); /* push */
1190 emit_symbol_diff (acfg, acfg->got_symbol, ".", got_offset);
1191 emit_alignment (acfg, kNaClAlignment);
1192 #endif /*__native_client_codegen__*/
1193 #elif defined(TARGET_ARM)
1197 /* This should be exactly 20 bytes long */
1200 ARM_PUSH (code, 0x5fff);
1201 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 4);
1202 /* Load the value from the GOT */
1203 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1205 ARM_BLX_REG (code, ARMREG_R1);
1207 g_assert (code - buf == 16);
1210 emit_bytes (acfg, buf, code - buf);
1212 * Only one offset is needed, since the second one would be equal to the
1215 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 4);
1216 //emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 8);
1217 #elif defined(TARGET_POWERPC)
1224 g_assert (!acfg->use_bin_writer);
1227 * PPC has no ip relative addressing, so we need to compute the address
1228 * of the mscorlib got. That is slow and complex, so instead, we store it
1229 * in the second got slot of every aot image. The caller already computed
1230 * the address of its got and placed it into r30.
1232 img_writer_emit_unset_mode (acfg->w);
1233 /* Load mscorlib got address */
1234 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1235 /* Load generic trampoline address */
1236 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1237 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1238 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1239 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1240 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1242 fprintf (acfg->fp, "mtctr 11\n");
1243 /* Load trampoline argument */
1244 /* On ppc, we pass it normally to the generic trampoline */
1245 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1246 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1247 fprintf (acfg->fp, "%s 0, 11, 0\n", PPC_LDX_OP);
1248 /* Branch to generic trampoline */
1249 fprintf (acfg->fp, "bctr\n");
1251 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1252 *tramp_size = 10 * 4;
1254 *tramp_size = 9 * 4;
1256 #elif defined(TARGET_X86)
1260 /* Similar to the PPC code above */
1262 /* FIXME: Could this clobber the register needed by get_vcall_slot () ? */
1264 /* We clobber ECX, since EAX is used as MONO_ARCH_MONITOR_OBJECT_REG */
1265 #ifdef MONO_ARCH_MONITOR_OBJECT_REG
1266 g_assert (MONO_ARCH_MONITOR_OBJECT_REG != X86_ECX);
1270 /* Load mscorlib got address */
1271 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1272 /* Push trampoline argument */
1273 x86_push_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1274 /* Load generic trampoline address */
1275 x86_mov_reg_membase (code, X86_ECX, X86_ECX, offset * sizeof (gpointer), 4);
1276 /* Branch to generic trampoline */
1277 x86_jump_reg (code, X86_ECX);
1279 #ifdef __native_client_codegen__
1281 /* emit nops to next 32 byte alignment */
1282 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1283 while (code < (buf + a)) x86_nop(code);
1286 emit_bytes (acfg, buf, code - buf);
1288 *tramp_size = NACL_SIZE(17, kNaClAlignment);
1289 g_assert (code - buf == *tramp_size);
1291 g_assert_not_reached ();
1296 * arch_emit_unbox_trampoline:
1298 * Emit code for the unbox trampoline for METHOD used in the full-aot case.
1299 * CALL_TARGET is the symbol pointing to the native code of METHOD.
1302 arch_emit_unbox_trampoline (MonoAotCompile *acfg, MonoCompile *cfg, MonoMethod *method, const char *call_target)
1304 #if defined(TARGET_AMD64)
1309 this_reg = mono_arch_get_this_arg_reg (NULL);
1311 amd64_alu_reg_imm (code, X86_ADD, this_reg, sizeof (MonoObject));
1313 emit_bytes (acfg, buf, code - buf);
1315 emit_byte (acfg, '\xe9');
1316 emit_symbol_diff (acfg, call_target, ".", -4);
1317 #elif defined(TARGET_X86)
1324 x86_alu_membase_imm (code, X86_ADD, X86_ESP, this_pos, sizeof (MonoObject));
1326 emit_bytes (acfg, buf, code - buf);
1329 emit_byte (acfg, '\xe9');
1330 emit_symbol_diff (acfg, call_target, ".", -4);
1331 #elif defined(TARGET_ARM)
1335 if (acfg->thumb_mixed && cfg->compile_llvm) {
1336 fprintf (acfg->fp, "add r0, r0, #%d\n", (int)sizeof (MonoObject));
1337 fprintf (acfg->fp, "b %s\n", call_target);
1338 fprintf (acfg->fp, ".arm\n");
1339 fprintf (acfg->fp, ".align 2\n");
1345 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (MonoObject));
1347 emit_bytes (acfg, buf, code - buf);
1348 /* jump to method */
1349 if (acfg->use_bin_writer) {
1356 img_writer_emit_reloc (acfg->w, R_ARM_JUMP24, call_target, -8);
1357 emit_bytes (acfg, buf, 4);
1359 if (acfg->thumb_mixed && cfg->compile_llvm)
1360 fprintf (acfg->fp, "\n\tbx %s\n", call_target);
1362 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1364 #elif defined(TARGET_POWERPC)
1367 g_assert (!acfg->use_bin_writer);
1369 fprintf (acfg->fp, "\n\taddi %d, %d, %d\n", this_pos, this_pos, (int)sizeof (MonoObject));
1370 fprintf (acfg->fp, "\n\tb %s\n", call_target);
1372 g_assert_not_reached ();
1377 * arch_emit_static_rgctx_trampoline:
1379 * Emit code for a static rgctx trampoline. OFFSET is the offset of the first of
1380 * two GOT slots which contain the rgctx argument, and the method to jump to.
1381 * TRAMP_SIZE is set to the size of the emitted trampoline.
1382 * These kinds of trampolines cannot be enumerated statically, since there could
1383 * be one trampoline per method instantiation, so we emit the same code for all
1384 * trampolines, and parameterize them using two GOT slots.
1387 arch_emit_static_rgctx_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1389 #if defined(TARGET_AMD64)
1390 #if defined(__default_codegen__)
1391 /* This should be exactly 13 bytes long */
1394 /* mov <OFFSET>(%rip), %r10 */
1395 emit_byte (acfg, '\x4d');
1396 emit_byte (acfg, '\x8b');
1397 emit_byte (acfg, '\x15');
1398 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1400 /* jmp *<offset>(%rip) */
1401 emit_byte (acfg, '\xff');
1402 emit_byte (acfg, '\x25');
1403 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1404 #elif defined(__native_client_codegen__)
1406 guint8 *buf_aligned = ALIGN_TO(buf, kNaClAlignment);
1407 guint8 *code = buf_aligned;
1409 /* mov <OFFSET>(%rip), %r10d */
1410 emit_byte (acfg, '\x45');
1411 emit_byte (acfg, '\x8b');
1412 emit_byte (acfg, '\x15');
1413 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1415 /* mov <OFFSET>(%rip), %r11d */
1416 emit_byte (acfg, '\x45');
1417 emit_byte (acfg, '\x8b');
1418 emit_byte (acfg, '\x1d');
1419 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4);
1422 amd64_jump_reg (code, AMD64_R11);
1423 emit_bytes (acfg, buf_aligned, code - buf_aligned);
1425 emit_alignment (acfg, kNaClAlignment);
1426 *tramp_size = kNaClAlignment;
1427 #endif /*__native_client_codegen__*/
1429 #elif defined(TARGET_ARM)
1433 /* This should be exactly 24 bytes long */
1436 /* Load rgctx value */
1437 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 8);
1438 ARM_LDR_REG_REG (code, MONO_ARCH_RGCTX_REG, ARMREG_PC, ARMREG_IP);
1439 /* Load branch addr + branch */
1440 ARM_LDR_IMM (code, ARMREG_IP, ARMREG_PC, 4);
1441 ARM_LDR_REG_REG (code, ARMREG_PC, ARMREG_PC, ARMREG_IP);
1443 g_assert (code - buf == 16);
1446 emit_bytes (acfg, buf, code - buf);
1447 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4 + 8);
1448 emit_symbol_diff (acfg, acfg->got_symbol, ".", ((offset + 1) * sizeof (gpointer)) - 4 + 4);
1449 #elif defined(TARGET_POWERPC)
1456 g_assert (!acfg->use_bin_writer);
1459 * PPC has no ip relative addressing, so we need to compute the address
1460 * of the mscorlib got. That is slow and complex, so instead, we store it
1461 * in the second got slot of every aot image. The caller already computed
1462 * the address of its got and placed it into r30.
1464 img_writer_emit_unset_mode (acfg->w);
1465 /* Load mscorlib got address */
1466 fprintf (acfg->fp, "%s 0, %d(30)\n", PPC_LD_OP, (int)sizeof (gpointer));
1468 fprintf (acfg->fp, "lis 11, %d@h\n", (int)(offset * sizeof (gpointer)));
1469 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)(offset * sizeof (gpointer)));
1470 fprintf (acfg->fp, "%s %d, 11, 0\n", PPC_LDX_OP, MONO_ARCH_RGCTX_REG);
1471 /* Load target address */
1472 fprintf (acfg->fp, "lis 11, %d@h\n", (int)((offset + 1) * sizeof (gpointer)));
1473 fprintf (acfg->fp, "ori 11, 11, %d@l\n", (int)((offset + 1) * sizeof (gpointer)));
1474 fprintf (acfg->fp, "%s 11, 11, 0\n", PPC_LDX_OP);
1475 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1476 fprintf (acfg->fp, "%s 2, %d(11)\n", PPC_LD_OP, (int)sizeof (gpointer));
1477 fprintf (acfg->fp, "%s 11, 0(11)\n", PPC_LD_OP);
1479 fprintf (acfg->fp, "mtctr 11\n");
1480 /* Branch to the target address */
1481 fprintf (acfg->fp, "bctr\n");
1483 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
1484 *tramp_size = 11 * 4;
1486 *tramp_size = 9 * 4;
1489 #elif defined(TARGET_X86)
1493 /* Similar to the PPC code above */
1495 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1498 /* Load mscorlib got address */
1499 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1501 x86_mov_reg_membase (code, MONO_ARCH_RGCTX_REG, X86_ECX, offset * sizeof (gpointer), 4);
1502 /* Branch to the target address */
1503 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1505 #ifdef __native_client_codegen__
1507 /* emit nops to next 32 byte alignment */
1508 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1509 while (code < (buf + a)) x86_nop(code);
1513 emit_bytes (acfg, buf, code - buf);
1515 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1516 g_assert (code - buf == *tramp_size);
1518 g_assert_not_reached ();
1523 * arch_emit_imt_thunk:
1525 * Emit an IMT thunk usable in full-aot mode. The thunk uses 1 got slot which
1526 * points to an array of pointer pairs. The pairs of the form [key, ptr], where
1527 * key is the IMT key, and ptr holds the address of a memory location holding
1528 * the address to branch to if the IMT arg matches the key. The array is
1529 * terminated by a pair whose key is NULL, and whose ptr is the address of the
1531 * TRAMP_SIZE is set to the size of the emitted trampoline.
1534 arch_emit_imt_thunk (MonoAotCompile *acfg, int offset, int *tramp_size)
1536 #if defined(TARGET_AMD64)
1538 #if defined(__native_client_codegen__)
1541 guint8 *labels [16];
1543 guint8 *mov_buf_ptr = mov_buf;
1545 const int kSizeOfMove = 7;
1546 #if defined(__default_codegen__)
1547 code = buf = g_malloc (256);
1548 #elif defined(__native_client_codegen__)
1549 buf_alloc = g_malloc (256 + kNaClAlignment + kSizeOfMove);
1550 buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1551 /* The RIP relative move below is emitted first */
1556 /* FIXME: Optimize this, i.e. use binary search etc. */
1557 /* Maybe move the body into a separate function (slower, but much smaller) */
1559 /* MONO_ARCH_IMT_SCRATCH_REG is a free register */
1562 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1564 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1567 amd64_alu_membase_reg_size (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, MONO_ARCH_IMT_REG, sizeof (gpointer));
1569 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1572 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, 2 * sizeof (gpointer));
1573 amd64_jump_code (code, labels [0]);
1576 mono_amd64_patch (labels [2], code);
1577 amd64_mov_reg_membase (code, MONO_ARCH_IMT_SCRATCH_REG, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer), sizeof (gpointer));
1578 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1581 mono_amd64_patch (labels [1], code);
1582 /* Load fail tramp */
1583 amd64_alu_reg_imm (code, X86_ADD, MONO_ARCH_IMT_SCRATCH_REG, sizeof (gpointer));
1584 /* Check if there is a fail tramp */
1585 amd64_alu_membase_imm (code, X86_CMP, MONO_ARCH_IMT_SCRATCH_REG, 0, 0);
1587 amd64_branch8 (code, X86_CC_Z, 0, FALSE);
1588 /* Jump to fail tramp */
1589 amd64_jump_membase (code, MONO_ARCH_IMT_SCRATCH_REG, 0);
1592 mono_amd64_patch (labels [3], code);
1593 x86_breakpoint (code);
1595 /* mov <OFFSET>(%rip), MONO_ARCH_IMT_SCRATCH_REG */
1596 amd64_emit_rex (mov_buf_ptr, sizeof(gpointer), MONO_ARCH_IMT_SCRATCH_REG, 0, AMD64_RIP);
1597 *(mov_buf_ptr)++ = (unsigned char)0x8b; /* mov opcode */
1598 x86_address_byte (mov_buf_ptr, 0, MONO_ARCH_IMT_SCRATCH_REG & 0x7, 5);
1599 emit_bytes (acfg, mov_buf, mov_buf_ptr - mov_buf);
1600 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) - 4);
1602 emit_bytes (acfg, buf, code - buf);
1604 *tramp_size = code - buf + kSizeOfMove;
1605 #if defined(__native_client_codegen__)
1606 /* The tramp will be padded to the next kNaClAlignment bundle. */
1607 *tramp_size = ALIGN_TO ((*tramp_size), kNaClAlignment);
1610 #if defined(__default_codegen__)
1612 #elif defined(__native_client_codegen__)
1616 #elif defined(TARGET_X86)
1618 #ifdef __native_client_codegen__
1621 guint8 *labels [16];
1623 #if defined(__default_codegen__)
1624 code = buf = g_malloc (256);
1625 #elif defined(__native_client_codegen__)
1626 buf_alloc = g_malloc (256 + kNaClAlignment);
1627 code = buf = ((guint)buf_alloc + kNaClAlignment) & ~kNaClAlignmentMask;
1630 /* Allocate a temporary stack slot */
1631 x86_push_reg (code, X86_EAX);
1633 x86_push_reg (code, X86_EAX);
1635 /* Load mscorlib got address */
1636 x86_mov_reg_membase (code, X86_EAX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1638 x86_mov_reg_membase (code, X86_EAX, X86_EAX, offset * sizeof (gpointer), 4);
1641 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1643 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1646 x86_alu_membase_reg (code, X86_CMP, X86_EAX, 0, MONO_ARCH_IMT_REG);
1648 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1651 x86_alu_reg_imm (code, X86_ADD, X86_EAX, 2 * sizeof (gpointer));
1652 x86_jump_code (code, labels [0]);
1655 mono_x86_patch (labels [2], code);
1656 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1657 x86_mov_reg_membase (code, X86_EAX, X86_EAX, 0, 4);
1658 /* Save the target address to the temporary stack location */
1659 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1661 x86_pop_reg (code, X86_EAX);
1662 /* Jump to the target address */
1666 mono_x86_patch (labels [1], code);
1667 /* Load fail tramp */
1668 x86_mov_reg_membase (code, X86_EAX, X86_EAX, sizeof (gpointer), 4);
1669 x86_alu_membase_imm (code, X86_CMP, X86_EAX, 0, 0);
1671 x86_branch8 (code, X86_CC_Z, FALSE, 0);
1672 /* Jump to fail tramp */
1673 x86_mov_membase_reg (code, X86_ESP, 4, X86_EAX, 4);
1674 x86_pop_reg (code, X86_EAX);
1678 mono_x86_patch (labels [3], code);
1679 x86_breakpoint (code);
1681 #ifdef __native_client_codegen__
1683 /* emit nops to next 32 byte alignment */
1684 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1685 while (code < (buf + a)) x86_nop(code);
1688 emit_bytes (acfg, buf, code - buf);
1690 *tramp_size = code - buf;
1692 #if defined(__default_codegen__)
1694 #elif defined(__native_client_codegen__)
1698 #elif defined(TARGET_ARM)
1700 guint8 *code, *code2, *labels [16];
1704 /* The IMT method is in v5 */
1706 /* Need at least two free registers, plus a slot for storing the pc */
1707 ARM_PUSH (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_R2));
1709 /* Load the parameter from the GOT */
1710 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_PC, 0);
1711 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R0);
1714 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_R0, 0);
1715 ARM_CMP_REG_REG (code, ARMREG_R1, ARMREG_V5);
1717 ARM_B_COND (code, ARMCOND_EQ, 0);
1719 /* End-of-loop check */
1720 ARM_CMP_REG_IMM (code, ARMREG_R1, 0, 0);
1722 ARM_B_COND (code, ARMCOND_EQ, 0);
1725 ARM_ADD_REG_IMM8 (code, ARMREG_R0, ARMREG_R0, sizeof (gpointer) * 2);
1728 arm_patch (labels [4], labels [1]);
1731 arm_patch (labels [2], code);
1732 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1733 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 0);
1734 /* Save it to the third stack slot */
1735 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1736 /* Restore the registers and branch */
1737 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1740 arm_patch (labels [3], code);
1741 ARM_LDR_IMM (code, ARMREG_R0, ARMREG_R0, 4);
1742 ARM_STR_IMM (code, ARMREG_R0, ARMREG_SP, 8);
1743 ARM_POP (code, (1 << ARMREG_R0)|(1 << ARMREG_R1)|(1 << ARMREG_PC));
1747 ARM_LDR_IMM (code2, ARMREG_R0, ARMREG_PC, (code - (labels [0] + 8)));
1749 emit_bytes (acfg, buf, code - buf);
1750 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + (code - (labels [0] + 8)) - 4);
1752 *tramp_size = code - buf + 4;
1753 #elif defined(TARGET_POWERPC)
1755 guint8 *code, *labels [16];
1759 /* Load the mscorlib got address */
1760 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r30);
1761 /* Load the parameter from the GOT */
1762 ppc_load (code, ppc_r0, offset * sizeof (gpointer));
1763 ppc_ldptr_indexed (code, ppc_r11, ppc_r11, ppc_r0);
1765 /* Load and check key */
1767 ppc_ldptr (code, ppc_r0, 0, ppc_r11);
1768 ppc_cmp (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, MONO_ARCH_IMT_REG);
1770 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1772 /* End-of-loop check */
1773 ppc_cmpi (code, 0, sizeof (gpointer) == 8 ? 1 : 0, ppc_r0, 0);
1775 ppc_bc (code, PPC_BR_TRUE, PPC_BR_EQ, 0);
1778 ppc_addi (code, ppc_r11, ppc_r11, 2 * sizeof (gpointer));
1781 mono_ppc_patch (labels [4], labels [1]);
1784 mono_ppc_patch (labels [2], code);
1785 ppc_ldptr (code, ppc_r11, sizeof (gpointer), ppc_r11);
1786 /* r11 now contains the value of the vtable slot */
1787 /* this is not a function descriptor on ppc64 */
1788 ppc_ldptr (code, ppc_r11, 0, ppc_r11);
1789 ppc_mtctr (code, ppc_r11);
1790 ppc_bcctr (code, PPC_BR_ALWAYS, 0);
1793 mono_ppc_patch (labels [3], code);
1797 *tramp_size = code - buf;
1799 emit_bytes (acfg, buf, code - buf);
1801 g_assert_not_reached ();
1806 * arch_emit_gsharedvt_arg_trampoline:
1808 * Emit code for a gsharedvt arg trampoline. OFFSET is the offset of the first of
1809 * two GOT slots which contain the argument, and the code to jump to.
1810 * TRAMP_SIZE is set to the size of the emitted trampoline.
1811 * These kinds of trampolines cannot be enumerated statically, since there could
1812 * be one trampoline per method instantiation, so we emit the same code for all
1813 * trampolines, and parameterize them using two GOT slots.
1816 arch_emit_gsharedvt_arg_trampoline (MonoAotCompile *acfg, int offset, int *tramp_size)
1818 #if defined(TARGET_X86)
1822 /* Similar to the PPC code above */
1824 g_assert (MONO_ARCH_RGCTX_REG != X86_ECX);
1827 /* Load mscorlib got address */
1828 x86_mov_reg_membase (code, X86_ECX, MONO_ARCH_GOT_REG, sizeof (gpointer), 4);
1830 x86_mov_reg_membase (code, X86_EAX, X86_ECX, offset * sizeof (gpointer), 4);
1831 /* Branch to the target address */
1832 x86_jump_membase (code, X86_ECX, (offset + 1) * sizeof (gpointer));
1834 #ifdef __native_client_codegen__
1836 /* emit nops to next 32 byte alignment */
1837 int a = (~kNaClAlignmentMask) & ((code - buf) + kNaClAlignment - 1);
1838 while (code < (buf + a)) x86_nop(code);
1842 emit_bytes (acfg, buf, code - buf);
1844 *tramp_size = NACL_SIZE (15, kNaClAlignment);
1845 g_assert (code - buf == *tramp_size);
1846 #elif defined(TARGET_ARM)
1850 /* The same as mono_arch_get_gsharedvt_arg_trampoline (), but for AOT */
1851 /* Similar to arch_emit_specific_trampoline () */
1854 ARM_PUSH (code, (1 << ARMREG_R0) | (1 << ARMREG_R1) | (1 << ARMREG_R2) | (1 << ARMREG_R3));
1855 ARM_LDR_IMM (code, ARMREG_R1, ARMREG_PC, 8);
1856 /* Load the arg value from the GOT */
1857 ARM_LDR_REG_REG (code, ARMREG_R0, ARMREG_PC, ARMREG_R1);
1858 /* Load the addr from the GOT */
1859 ARM_LDR_REG_REG (code, ARMREG_R1, ARMREG_PC, ARMREG_R1);
1861 ARM_BX (code, ARMREG_R1);
1863 g_assert (code - buf == 20);
1866 emit_bytes (acfg, buf, code - buf);
1867 emit_symbol_diff (acfg, acfg->got_symbol, ".", (offset * sizeof (gpointer)) + 4);
1869 g_assert_not_reached ();
1874 arch_emit_autoreg (MonoAotCompile *acfg, char *symbol)
1876 #if defined(TARGET_POWERPC) && defined(__mono_ilp32__)
1877 /* Based on code generated by gcc */
1878 img_writer_emit_unset_mode (acfg->w);
1881 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1882 ".section .ctors,\"aw\",@progbits\n"
1886 ".section .opd,\"aw\"\n"
1889 ".long .%s,.TOC.@tocbase32\n"
1892 ".type .%s,@function\n"
1894 ".%s:\n", symbol, symbol, symbol, symbol, symbol, symbol, symbol, symbol);
1896 ".section .ctors,\"aw\",@progbits\n"
1900 ".section .opd,\"aw\"\n"
1903 ".long .%1$s,.TOC.@tocbase32\n"
1904 ".size %1$s,.-%1$s\n"
1906 ".type .%1$s,@function\n"
1908 ".%1$s:\n", symbol);
1919 "lis 3, .Lglobals@h\n"
1920 "ori 3, 3, .Lglobals@l\n"
1921 "bl .mono_aot_register_module\n"
1929 #if defined(_MSC_VER) || defined(MONO_CROSS_COMPILE)
1931 ".size .%s,.-.%s\n", symbol, symbol);
1934 ".size .%1$s,.-.%1$s\n", symbol);
1940 /* END OF ARCH SPECIFIC CODE */
1943 mono_get_field_token (MonoClassField *field)
1945 MonoClass *klass = field->parent;
1948 for (i = 0; i < klass->field.count; ++i) {
1949 if (field == &klass->fields [i])
1950 return MONO_TOKEN_FIELD_DEF | (klass->field.first + 1 + i);
1953 g_assert_not_reached ();
1958 encode_value (gint32 value, guint8 *buf, guint8 **endbuf)
1962 //printf ("ENCODE: %d 0x%x.\n", value, value);
1965 * Same encoding as the one used in the metadata, extended to handle values
1966 * greater than 0x1fffffff.
1968 if ((value >= 0) && (value <= 127))
1970 else if ((value >= 0) && (value <= 16383)) {
1971 p [0] = 0x80 | (value >> 8);
1972 p [1] = value & 0xff;
1974 } else if ((value >= 0) && (value <= 0x1fffffff)) {
1975 p [0] = (value >> 24) | 0xc0;
1976 p [1] = (value >> 16) & 0xff;
1977 p [2] = (value >> 8) & 0xff;
1978 p [3] = value & 0xff;
1983 p [1] = (value >> 24) & 0xff;
1984 p [2] = (value >> 16) & 0xff;
1985 p [3] = (value >> 8) & 0xff;
1986 p [4] = value & 0xff;
1994 stream_init (MonoDynamicStream *sh)
1997 sh->alloc_size = 4096;
1998 sh->data = g_malloc (4096);
2000 /* So offsets are > 0 */
2006 make_room_in_stream (MonoDynamicStream *stream, int size)
2008 if (size <= stream->alloc_size)
2011 while (stream->alloc_size <= size) {
2012 if (stream->alloc_size < 4096)
2013 stream->alloc_size = 4096;
2015 stream->alloc_size *= 2;
2018 stream->data = g_realloc (stream->data, stream->alloc_size);
2022 add_stream_data (MonoDynamicStream *stream, const char *data, guint32 len)
2026 make_room_in_stream (stream, stream->index + len);
2027 memcpy (stream->data + stream->index, data, len);
2028 idx = stream->index;
2029 stream->index += len;
2036 * Add data to the binary blob inside the aot image. Returns the offset inside the
2037 * blob where the data was stored.
2040 add_to_blob (MonoAotCompile *acfg, const guint8 *data, guint32 data_len)
2042 if (acfg->blob.alloc_size == 0)
2043 stream_init (&acfg->blob);
2045 return add_stream_data (&acfg->blob, (char*)data, data_len);
2049 add_to_blob_aligned (MonoAotCompile *acfg, const guint8 *data, guint32 data_len, guint32 align)
2054 if (acfg->blob.alloc_size == 0)
2055 stream_init (&acfg->blob);
2057 count = acfg->blob.index % align;
2059 /* we assume the stream data will be aligned */
2061 add_stream_data (&acfg->blob, buf, 4 - count);
2063 return add_stream_data (&acfg->blob, (char*)data, data_len);
2067 * emit_offset_table:
2069 * Emit a table of increasing offsets in a compact form using differential encoding.
2070 * There is an index entry for each GROUP_SIZE number of entries. The greater the
2071 * group size, the more compact the table becomes, but the slower it becomes to compute
2072 * a given entry. Returns the size of the table.
2075 emit_offset_table (MonoAotCompile *acfg, int noffsets, int group_size, gint32 *offsets)
2077 gint32 current_offset;
2078 int i, buf_size, ngroups, index_entry_size;
2080 guint32 *index_offsets;
2082 ngroups = (noffsets + (group_size - 1)) / group_size;
2084 index_offsets = g_new0 (guint32, ngroups);
2086 buf_size = noffsets * 4;
2087 p = buf = g_malloc0 (buf_size);
2090 for (i = 0; i < noffsets; ++i) {
2091 //printf ("D: %d -> %d\n", i, offsets [i]);
2092 if ((i % group_size) == 0) {
2093 index_offsets [i / group_size] = p - buf;
2094 /* Emit the full value for these entries */
2095 encode_value (offsets [i], p, &p);
2097 /* The offsets are allowed to be non-increasing */
2098 //g_assert (offsets [i] >= current_offset);
2099 encode_value (offsets [i] - current_offset, p, &p);
2101 current_offset = offsets [i];
2104 if (ngroups && index_offsets [ngroups - 1] < 65000)
2105 index_entry_size = 2;
2107 index_entry_size = 4;
2109 /* Emit the header */
2110 emit_int32 (acfg, noffsets);
2111 emit_int32 (acfg, group_size);
2112 emit_int32 (acfg, ngroups);
2113 emit_int32 (acfg, index_entry_size);
2115 /* Emit the index */
2116 for (i = 0; i < ngroups; ++i) {
2117 if (index_entry_size == 2)
2118 emit_int16 (acfg, index_offsets [i]);
2120 emit_int32 (acfg, index_offsets [i]);
2124 emit_bytes (acfg, buf, p - buf);
2126 return (int)(p - buf) + (ngroups * 4);
2130 get_image_index (MonoAotCompile *cfg, MonoImage *image)
2134 index = GPOINTER_TO_UINT (g_hash_table_lookup (cfg->image_hash, image));
2138 index = g_hash_table_size (cfg->image_hash);
2139 g_hash_table_insert (cfg->image_hash, image, GUINT_TO_POINTER (index + 1));
2140 g_ptr_array_add (cfg->image_table, image);
2146 find_typespec_for_class (MonoAotCompile *acfg, MonoClass *klass)
2149 int len = acfg->image->tables [MONO_TABLE_TYPESPEC].rows;
2151 /* FIXME: Search referenced images as well */
2152 if (!acfg->typespec_classes) {
2153 acfg->typespec_classes = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoClass*) * len);
2154 for (i = 0; i < len; ++i) {
2155 acfg->typespec_classes [i] = mono_class_get_full (acfg->image, MONO_TOKEN_TYPE_SPEC | (i + 1), NULL);
2158 for (i = 0; i < len; ++i) {
2159 if (acfg->typespec_classes [i] == klass)
2164 return MONO_TOKEN_TYPE_SPEC | (i + 1);
2170 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf);
2173 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf);
2176 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf);
2179 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf);
2182 encode_klass_ref_inner (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2187 * The encoding begins with one of the MONO_AOT_TYPEREF values, followed by additional
2191 if (klass->generic_class) {
2193 g_assert (klass->type_token);
2195 /* Find a typespec for a class if possible */
2196 token = find_typespec_for_class (acfg, klass);
2198 encode_value (MONO_AOT_TYPEREF_TYPESPEC_TOKEN, p, &p);
2199 encode_value (token, p, &p);
2201 MonoClass *gclass = klass->generic_class->container_class;
2202 MonoGenericInst *inst = klass->generic_class->context.class_inst;
2203 static int count = 0;
2206 encode_value (MONO_AOT_TYPEREF_GINST, p, &p);
2207 encode_klass_ref (acfg, gclass, p, &p);
2208 encode_ginst (acfg, inst, p, &p);
2212 } else if (klass->type_token) {
2213 int iindex = get_image_index (acfg, klass->image);
2215 g_assert (mono_metadata_token_code (klass->type_token) == MONO_TOKEN_TYPE_DEF);
2217 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX, p, &p);
2218 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2220 encode_value (MONO_AOT_TYPEREF_TYPEDEF_INDEX_IMAGE, p, &p);
2221 encode_value (klass->type_token - MONO_TOKEN_TYPE_DEF, p, &p);
2222 encode_value (get_image_index (acfg, klass->image), p, &p);
2224 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2225 MonoGenericContainer *container = mono_type_get_generic_param_owner (&klass->byval_arg);
2226 MonoGenericParam *par = klass->byval_arg.data.generic_param;
2228 encode_value (MONO_AOT_TYPEREF_VAR, p, &p);
2229 encode_value (klass->byval_arg.type, p, &p);
2230 encode_value (mono_type_get_generic_param_num (&klass->byval_arg), p, &p);
2232 encode_value (container ? 1 : 0, p, &p);
2234 encode_value (container->is_method, p, &p);
2235 g_assert (par->serial == 0);
2236 if (container->is_method)
2237 encode_method_ref (acfg, container->owner.method, p, &p);
2239 encode_klass_ref (acfg, container->owner.klass, p, &p);
2241 encode_value (par->serial, p, &p);
2243 } else if (klass->byval_arg.type == MONO_TYPE_PTR) {
2244 encode_value (MONO_AOT_TYPEREF_PTR, p, &p);
2245 encode_type (acfg, &klass->byval_arg, p, &p);
2248 g_assert (klass->rank > 0);
2249 encode_value (MONO_AOT_TYPEREF_ARRAY, p, &p);
2250 encode_value (klass->rank, p, &p);
2251 encode_klass_ref (acfg, klass->element_class, p, &p);
2259 * Encode a reference to KLASS. We use our home-grown encoding instead of the
2260 * standard metadata encoding.
2263 encode_klass_ref (MonoAotCompile *acfg, MonoClass *klass, guint8 *buf, guint8 **endbuf)
2265 gboolean shared = FALSE;
2268 * The encoding of generic instances is large so emit them only once.
2270 if (klass->generic_class) {
2272 g_assert (klass->type_token);
2274 /* Find a typespec for a class if possible */
2275 token = find_typespec_for_class (acfg, klass);
2278 } else if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR)) {
2283 guint offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->klass_blob_hash, klass));
2287 buf2 = g_malloc (1024);
2290 encode_klass_ref_inner (acfg, klass, p, &p);
2291 g_assert (p - buf2 < 1024);
2293 offset = add_to_blob (acfg, buf2, p - buf2);
2296 g_hash_table_insert (acfg->klass_blob_hash, klass, GUINT_TO_POINTER (offset + 1));
2302 encode_value (MONO_AOT_TYPEREF_BLOB_INDEX, p, &p);
2303 encode_value (offset, p, &p);
2308 encode_klass_ref_inner (acfg, klass, buf, endbuf);
2312 encode_field_info (MonoAotCompile *cfg, MonoClassField *field, guint8 *buf, guint8 **endbuf)
2314 guint32 token = mono_get_field_token (field);
2317 encode_klass_ref (cfg, field->parent, p, &p);
2318 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_FIELD_DEF);
2319 encode_value (token - MONO_TOKEN_FIELD_DEF, p, &p);
2324 encode_ginst (MonoAotCompile *acfg, MonoGenericInst *inst, guint8 *buf, guint8 **endbuf)
2329 encode_value (inst->type_argc, p, &p);
2330 for (i = 0; i < inst->type_argc; ++i)
2331 encode_klass_ref (acfg, mono_class_from_mono_type (inst->type_argv [i]), p, &p);
2336 encode_generic_context (MonoAotCompile *acfg, MonoGenericContext *context, guint8 *buf, guint8 **endbuf)
2339 MonoGenericInst *inst;
2341 inst = context->class_inst;
2343 g_assert (inst->type_argc);
2344 encode_ginst (acfg, inst, p, &p);
2346 encode_value (0, p, &p);
2348 inst = context->method_inst;
2350 g_assert (inst->type_argc);
2351 encode_ginst (acfg, inst, p, &p);
2353 encode_value (0, p, &p);
2359 encode_type (MonoAotCompile *acfg, MonoType *t, guint8 *buf, guint8 **endbuf)
2363 g_assert (t->num_mods == 0);
2364 /* t->attrs can be ignored */
2365 //g_assert (t->attrs == 0);
2368 *p = MONO_TYPE_PINNED;
2372 *p = MONO_TYPE_BYREF;
2380 case MONO_TYPE_VOID:
2381 case MONO_TYPE_BOOLEAN:
2382 case MONO_TYPE_CHAR:
2395 case MONO_TYPE_STRING:
2396 case MONO_TYPE_OBJECT:
2397 case MONO_TYPE_TYPEDBYREF:
2399 case MONO_TYPE_VALUETYPE:
2400 case MONO_TYPE_CLASS:
2401 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2403 case MONO_TYPE_SZARRAY:
2404 encode_klass_ref (acfg, t->data.klass, p, &p);
2407 encode_type (acfg, t->data.type, p, &p);
2409 case MONO_TYPE_GENERICINST: {
2410 MonoClass *gclass = t->data.generic_class->container_class;
2411 MonoGenericInst *inst = t->data.generic_class->context.class_inst;
2413 encode_klass_ref (acfg, gclass, p, &p);
2414 encode_ginst (acfg, inst, p, &p);
2417 case MONO_TYPE_ARRAY: {
2418 MonoArrayType *array = t->data.array;
2421 encode_klass_ref (acfg, array->eklass, p, &p);
2422 encode_value (array->rank, p, &p);
2423 encode_value (array->numsizes, p, &p);
2424 for (i = 0; i < array->numsizes; ++i)
2425 encode_value (array->sizes [i], p, &p);
2426 encode_value (array->numlobounds, p, &p);
2427 for (i = 0; i < array->numlobounds; ++i)
2428 encode_value (array->lobounds [i], p, &p);
2432 case MONO_TYPE_MVAR:
2433 encode_klass_ref (acfg, mono_class_from_mono_type (t), p, &p);
2436 g_assert_not_reached ();
2443 encode_signature (MonoAotCompile *acfg, MonoMethodSignature *sig, guint8 *buf, guint8 **endbuf)
2449 /* Similar to the metadata encoding */
2450 if (sig->generic_param_count)
2454 if (sig->explicit_this)
2456 flags |= (sig->call_convention & 0x0F);
2460 if (sig->generic_param_count)
2461 encode_value (sig->generic_param_count, p, &p);
2462 encode_value (sig->param_count, p, &p);
2464 encode_type (acfg, sig->ret, p, &p);
2465 for (i = 0; i < sig->param_count; ++i) {
2466 if (sig->sentinelpos == i) {
2467 *p = MONO_TYPE_SENTINEL;
2470 encode_type (acfg, sig->params [i], p, &p);
2476 #define MAX_IMAGE_INDEX 250
2479 encode_method_ref (MonoAotCompile *acfg, MonoMethod *method, guint8 *buf, guint8 **endbuf)
2481 guint32 image_index = get_image_index (acfg, method->klass->image);
2482 guint32 token = method->token;
2483 MonoJumpInfoToken *ji;
2487 * The encoding for most methods is as follows:
2488 * - image index encoded as a leb128
2489 * - token index encoded as a leb128
2490 * Values of image index >= MONO_AOT_METHODREF_MIN are used to mark additional
2491 * types of method encodings.
2494 /* Mark methods which can't use aot trampolines because they need the further
2495 * processing in mono_magic_trampoline () which requires a MonoMethod*.
2497 if ((method->is_generic && (method->flags & METHOD_ATTRIBUTE_VIRTUAL)) ||
2498 (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED))
2499 encode_value ((MONO_AOT_METHODREF_NO_AOT_TRAMPOLINE << 24), p, &p);
2501 if (method->wrapper_type) {
2502 encode_value ((MONO_AOT_METHODREF_WRAPPER << 24), p, &p);
2504 encode_value (method->wrapper_type, p, &p);
2506 switch (method->wrapper_type) {
2507 case MONO_WRAPPER_REMOTING_INVOKE:
2508 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
2509 case MONO_WRAPPER_XDOMAIN_INVOKE: {
2512 m = mono_marshal_method_from_wrapper (method);
2514 encode_method_ref (acfg, m, p, &p);
2517 case MONO_WRAPPER_PROXY_ISINST:
2518 case MONO_WRAPPER_LDFLD:
2519 case MONO_WRAPPER_LDFLDA:
2520 case MONO_WRAPPER_STFLD:
2521 case MONO_WRAPPER_ISINST: {
2522 MonoClass *proxy_class = mono_marshal_get_wrapper_info (method);
2523 encode_klass_ref (acfg, proxy_class, p, &p);
2526 case MONO_WRAPPER_LDFLD_REMOTE:
2527 case MONO_WRAPPER_STFLD_REMOTE:
2529 case MONO_WRAPPER_ALLOC: {
2530 AllocatorWrapperInfo *info = mono_marshal_get_wrapper_info (method);
2532 /* The GC name is saved once in MonoAotFileInfo */
2533 g_assert (info->alloc_type != -1);
2534 encode_value (info->alloc_type, p, &p);
2537 case MONO_WRAPPER_WRITE_BARRIER:
2539 case MONO_WRAPPER_STELEMREF: {
2540 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2543 encode_value (info->subtype, p, &p);
2544 if (info->subtype == WRAPPER_SUBTYPE_VIRTUAL_STELEMREF)
2545 encode_value (info->d.virtual_stelemref.kind, p, &p);
2548 case MONO_WRAPPER_UNKNOWN: {
2549 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2552 encode_value (info->subtype, p, &p);
2553 if (info->subtype == WRAPPER_SUBTYPE_PTR_TO_STRUCTURE ||
2554 info->subtype == WRAPPER_SUBTYPE_STRUCTURE_TO_PTR)
2555 encode_klass_ref (acfg, method->klass, p, &p);
2556 else if (info->subtype == WRAPPER_SUBTYPE_SYNCHRONIZED_INNER)
2557 encode_method_ref (acfg, info->d.synchronized_inner.method, p, &p);
2560 case MONO_WRAPPER_MANAGED_TO_NATIVE: {
2561 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2564 encode_value (info->subtype, p, &p);
2565 if (info->subtype == WRAPPER_SUBTYPE_ICALL_WRAPPER) {
2566 strcpy ((char*)p, method->name);
2567 p += strlen (method->name) + 1;
2568 } else if (info->subtype == WRAPPER_SUBTYPE_NATIVE_FUNC_AOT) {
2569 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2571 g_assert (info->subtype == WRAPPER_SUBTYPE_NONE);
2572 encode_method_ref (acfg, info->d.managed_to_native.method, p, &p);
2576 case MONO_WRAPPER_SYNCHRONIZED: {
2579 m = mono_marshal_method_from_wrapper (method);
2581 g_assert (m != method);
2582 encode_method_ref (acfg, m, p, &p);
2585 case MONO_WRAPPER_MANAGED_TO_MANAGED: {
2586 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2589 encode_value (info->subtype, p, &p);
2591 if (info->subtype == WRAPPER_SUBTYPE_ELEMENT_ADDR) {
2592 encode_value (info->d.element_addr.rank, p, &p);
2593 encode_value (info->d.element_addr.elem_size, p, &p);
2594 } else if (info->subtype == WRAPPER_SUBTYPE_STRING_CTOR) {
2595 encode_method_ref (acfg, info->d.string_ctor.method, p, &p);
2597 g_assert_not_reached ();
2601 case MONO_WRAPPER_CASTCLASS: {
2602 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2605 encode_value (info->subtype, p, &p);
2608 case MONO_WRAPPER_RUNTIME_INVOKE: {
2609 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2612 encode_value (info->subtype, p, &p);
2613 if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_DIRECT || info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_VIRTUAL)
2614 encode_method_ref (acfg, info->d.runtime_invoke.method, p, &p);
2615 else if (info->subtype == WRAPPER_SUBTYPE_RUNTIME_INVOKE_NORMAL)
2616 encode_signature (acfg, info->d.runtime_invoke.sig, p, &p);
2619 case MONO_WRAPPER_DELEGATE_INVOKE:
2620 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
2621 case MONO_WRAPPER_DELEGATE_END_INVOKE: {
2622 if (method->is_inflated) {
2623 /* These wrappers are identified by their class */
2624 encode_value (1, p, &p);
2625 encode_klass_ref (acfg, method->klass, p, &p);
2627 MonoMethodSignature *sig = mono_method_signature (method);
2629 encode_value (0, p, &p);
2630 encode_signature (acfg, sig, p, &p);
2634 case MONO_WRAPPER_NATIVE_TO_MANAGED: {
2635 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
2638 encode_method_ref (acfg, info->d.native_to_managed.method, p, &p);
2639 encode_klass_ref (acfg, info->d.native_to_managed.klass, p, &p);
2643 g_assert_not_reached ();
2645 } else if (mono_method_signature (method)->is_inflated) {
2647 * This is a generic method, find the original token which referenced it and
2649 * Obtain the token from information recorded by the JIT.
2651 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2653 image_index = get_image_index (acfg, ji->image);
2654 g_assert (image_index < MAX_IMAGE_INDEX);
2657 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2658 encode_value (image_index, p, &p);
2659 encode_value (token, p, &p);
2661 MonoMethod *declaring;
2662 MonoGenericContext *context = mono_method_get_context (method);
2664 g_assert (method->is_inflated);
2665 declaring = ((MonoMethodInflated*)method)->declaring;
2668 * This might be a non-generic method of a generic instance, which
2669 * doesn't have a token since the reference is generated by the JIT
2670 * like Nullable:Box/Unbox, or by generic sharing.
2672 encode_value ((MONO_AOT_METHODREF_GINST << 24), p, &p);
2673 /* Encode the klass */
2674 encode_klass_ref (acfg, method->klass, p, &p);
2675 /* Encode the method */
2676 image_index = get_image_index (acfg, method->klass->image);
2677 g_assert (image_index < MAX_IMAGE_INDEX);
2678 g_assert (declaring->token);
2679 token = declaring->token;
2680 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2681 encode_value (image_index, p, &p);
2682 encode_value (token, p, &p);
2683 encode_generic_context (acfg, context, p, &p);
2685 } else if (token == 0) {
2686 /* This might be a method of a constructed type like int[,].Set */
2687 /* Obtain the token from information recorded by the JIT */
2688 ji = g_hash_table_lookup (acfg->token_info_hash, method);
2690 image_index = get_image_index (acfg, ji->image);
2691 g_assert (image_index < MAX_IMAGE_INDEX);
2694 encode_value ((MONO_AOT_METHODREF_METHODSPEC << 24), p, &p);
2695 encode_value (image_index, p, &p);
2696 encode_value (token, p, &p);
2699 g_assert (method->klass->rank);
2701 /* Encode directly */
2702 encode_value ((MONO_AOT_METHODREF_ARRAY << 24), p, &p);
2703 encode_klass_ref (acfg, method->klass, p, &p);
2704 if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank)
2705 encode_value (0, p, &p);
2706 else if (!strcmp (method->name, ".ctor") && mono_method_signature (method)->param_count == method->klass->rank * 2)
2707 encode_value (1, p, &p);
2708 else if (!strcmp (method->name, "Get"))
2709 encode_value (2, p, &p);
2710 else if (!strcmp (method->name, "Address"))
2711 encode_value (3, p, &p);
2712 else if (!strcmp (method->name, "Set"))
2713 encode_value (4, p, &p);
2715 g_assert_not_reached ();
2718 g_assert (mono_metadata_token_table (token) == MONO_TABLE_METHOD);
2720 if (image_index >= MONO_AOT_METHODREF_MIN) {
2721 encode_value ((MONO_AOT_METHODREF_LARGE_IMAGE_INDEX << 24), p, &p);
2722 encode_value (image_index, p, &p);
2723 encode_value (mono_metadata_token_index (token), p, &p);
2725 encode_value ((image_index << 24) | mono_metadata_token_index (token), p, &p);
2732 compare_patches (gconstpointer a, gconstpointer b)
2736 i = (*(MonoJumpInfo**)a)->ip.i;
2737 j = (*(MonoJumpInfo**)b)->ip.i;
2748 static G_GNUC_UNUSED char*
2749 patch_to_string (MonoJumpInfo *patch_info)
2753 str = g_string_new ("");
2755 g_string_append_printf (str, "%s(", get_patch_name (patch_info->type));
2757 switch (patch_info->type) {
2758 case MONO_PATCH_INFO_VTABLE:
2759 mono_type_get_desc (str, &patch_info->data.klass->byval_arg, TRUE);
2764 g_string_append_printf (str, ")");
2765 return g_string_free (str, FALSE);
2771 * Return whenever PATCH_INFO refers to a direct call, and thus requires a
2774 static inline gboolean
2775 is_plt_patch (MonoJumpInfo *patch_info)
2777 switch (patch_info->type) {
2778 case MONO_PATCH_INFO_METHOD:
2779 case MONO_PATCH_INFO_INTERNAL_METHOD:
2780 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
2781 case MONO_PATCH_INFO_ICALL_ADDR:
2782 case MONO_PATCH_INFO_CLASS_INIT:
2783 case MONO_PATCH_INFO_RGCTX_FETCH:
2784 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
2785 case MONO_PATCH_INFO_MONITOR_ENTER:
2786 case MONO_PATCH_INFO_MONITOR_EXIT:
2787 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
2797 * Return the symbol identifying the plt entry PLT_OFFSET.
2800 get_plt_symbol (MonoAotCompile *acfg, int plt_offset, MonoJumpInfo *patch_info)
2804 * The Apple linker reorganizes object files, so it doesn't like branches to local
2805 * labels, since those have no relocations.
2807 return g_strdup_printf ("%sp_%d", acfg->llvm_label_prefix, plt_offset);
2809 return g_strdup_printf ("%sp_%d", acfg->temp_prefix, plt_offset);
2816 * Return a PLT entry which belongs to the method identified by PATCH_INFO.
2818 static MonoPltEntry*
2819 get_plt_entry (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
2823 if (!is_plt_patch (patch_info))
2826 res = g_hash_table_lookup (acfg->patch_to_plt_entry, patch_info);
2828 // FIXME: This breaks the calculation of final_got_size
2829 if (!acfg->llvm && patch_info->type == MONO_PATCH_INFO_METHOD && (patch_info->data.method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED)) {
2831 * Allocate a separate PLT slot for each such patch, since some plt
2832 * entries will refer to the method itself, and some will refer to the
2839 MonoJumpInfo *new_ji;
2841 g_assert (!acfg->final_got_size);
2843 new_ji = mono_patch_info_dup_mp (acfg->mempool, patch_info);
2845 res = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoPltEntry));
2846 res->plt_offset = acfg->plt_offset;
2848 res->symbol = get_plt_symbol (acfg, res->plt_offset, patch_info);
2849 if (acfg->aot_opts.write_symbols)
2850 res->debug_sym = get_plt_entry_debug_sym (acfg, res->ji, acfg->plt_entry_debug_sym_cache);
2852 res->llvm_symbol = g_strdup_printf ("%s_%s_llvm", res->symbol, res->debug_sym);
2854 res->llvm_symbol = g_strdup_printf ("%s_llvm", res->symbol);
2856 g_hash_table_insert (acfg->patch_to_plt_entry, new_ji, res);
2858 g_hash_table_insert (acfg->plt_offset_to_entry, GUINT_TO_POINTER (res->plt_offset), res);
2860 //g_assert (mono_patch_info_equal (patch_info, new_ji));
2861 //mono_print_ji (patch_info); printf ("\n");
2862 //g_hash_table_print_stats (acfg->patch_to_plt_entry);
2864 acfg->plt_offset ++;
2873 * Returns the offset of the GOT slot where the runtime object resulting from resolving
2874 * JI could be found if it exists, otherwise allocates a new one.
2877 get_got_offset (MonoAotCompile *acfg, MonoJumpInfo *ji)
2881 got_offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->patch_to_got_offset_by_type [ji->type], ji));
2883 return got_offset - 1;
2885 got_offset = acfg->got_offset;
2886 acfg->got_offset ++;
2888 if (acfg->final_got_size)
2889 g_assert (got_offset < acfg->final_got_size);
2891 acfg->stats.got_slots ++;
2892 acfg->stats.got_slot_types [ji->type] ++;
2894 g_hash_table_insert (acfg->patch_to_got_offset, ji, GUINT_TO_POINTER (got_offset + 1));
2895 g_hash_table_insert (acfg->patch_to_got_offset_by_type [ji->type], ji, GUINT_TO_POINTER (got_offset + 1));
2896 g_ptr_array_add (acfg->got_patches, ji);
2901 /* Add a method to the list of methods which need to be emitted */
2903 add_method_with_index (MonoAotCompile *acfg, MonoMethod *method, int index, gboolean extra)
2906 if (!g_hash_table_lookup (acfg->method_indexes, method)) {
2907 g_ptr_array_add (acfg->methods, method);
2908 g_hash_table_insert (acfg->method_indexes, method, GUINT_TO_POINTER (index + 1));
2909 acfg->nmethods = acfg->methods->len + 1;
2912 if (method->wrapper_type || extra)
2913 g_ptr_array_add (acfg->extra_methods, method);
2917 get_method_index (MonoAotCompile *acfg, MonoMethod *method)
2919 int index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2927 add_method_full (MonoAotCompile *acfg, MonoMethod *method, gboolean extra, int depth)
2931 index = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_indexes, method));
2935 index = acfg->method_index;
2936 add_method_with_index (acfg, method, index, extra);
2938 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (index));
2940 g_hash_table_insert (acfg->method_depth, method, GUINT_TO_POINTER (depth));
2942 acfg->method_index ++;
2948 add_method (MonoAotCompile *acfg, MonoMethod *method)
2950 return add_method_full (acfg, method, FALSE, 0);
2954 add_extra_method_with_depth (MonoAotCompile *acfg, MonoMethod *method, int depth)
2956 if (mono_method_is_generic_sharable_full (method, FALSE, TRUE, FALSE))
2957 method = mini_get_shared_method (method);
2959 if (acfg->aot_opts.log_generics)
2960 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
2962 add_method_full (acfg, method, TRUE, depth);
2966 add_extra_method (MonoAotCompile *acfg, MonoMethod *method)
2968 add_extra_method_with_depth (acfg, method, 0);
2972 add_jit_icall_wrapper (gpointer key, gpointer value, gpointer user_data)
2974 MonoAotCompile *acfg = user_data;
2975 MonoJitICallInfo *callinfo = value;
2976 MonoMethod *wrapper;
2982 name = g_strdup_printf ("__icall_wrapper_%s", callinfo->name);
2983 wrapper = mono_marshal_get_icall_wrapper (callinfo->sig, name, callinfo->func, check_for_pending_exc);
2986 add_method (acfg, wrapper);
2990 get_runtime_invoke_sig (MonoMethodSignature *sig)
2992 MonoMethodBuilder *mb;
2995 mb = mono_mb_new (mono_defaults.object_class, "FOO", MONO_WRAPPER_NONE);
2996 m = mono_mb_create_method (mb, sig, 16);
2997 return mono_marshal_get_runtime_invoke (m, FALSE);
3001 can_marshal_struct (MonoClass *klass)
3003 MonoClassField *field;
3004 gboolean can_marshal = TRUE;
3005 gpointer iter = NULL;
3006 MonoMarshalType *info;
3009 if ((klass->flags & TYPE_ATTRIBUTE_LAYOUT_MASK) == TYPE_ATTRIBUTE_AUTO_LAYOUT)
3012 info = mono_marshal_load_type_info (klass);
3014 /* Only allow a few field types to avoid asserts in the marshalling code */
3015 while ((field = mono_class_get_fields (klass, &iter))) {
3016 if ((field->type->attrs & FIELD_ATTRIBUTE_STATIC))
3019 switch (field->type->type) {
3024 case MONO_TYPE_BOOLEAN:
3027 case MONO_TYPE_CHAR:
3035 case MONO_TYPE_STRING:
3037 case MONO_TYPE_VALUETYPE:
3038 if (!mono_class_from_mono_type (field->type)->enumtype && !can_marshal_struct (mono_class_from_mono_type (field->type)))
3039 can_marshal = FALSE;
3041 case MONO_TYPE_SZARRAY: {
3042 gboolean has_mspec = FALSE;
3045 for (i = 0; i < info->num_fields; ++i) {
3046 if (info->fields [i].field == field && info->fields [i].mspec)
3051 can_marshal = FALSE;
3055 can_marshal = FALSE;
3061 /* Its hard to compute whenever these can be marshalled or not */
3062 if (!strcmp (klass->name_space, "System.Net.NetworkInformation.MacOsStructs") && strcmp (klass->name, "sockaddr_dl"))
3069 create_gsharedvt_inst (MonoAotCompile *acfg, MonoMethod *method, MonoGenericContext *ctx)
3071 /* Create a vtype instantiation */
3072 MonoGenericContext shared_context;
3074 MonoGenericInst *inst;
3075 MonoGenericContainer *container;
3076 MonoClass **constraints;
3079 memset (ctx, 0, sizeof (MonoGenericContext));
3081 if (method->klass->generic_container) {
3082 shared_context = method->klass->generic_container->context;
3083 inst = shared_context.class_inst;
3085 args = g_new0 (MonoType*, inst->type_argc);
3086 for (i = 0; i < inst->type_argc; ++i) {
3087 args [i] = &mono_defaults.int_class->byval_arg;
3089 ctx->class_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3091 if (method->is_generic) {
3092 container = mono_method_get_generic_container (method);
3093 shared_context = container->context;
3094 inst = shared_context.method_inst;
3096 args = g_new0 (MonoType*, inst->type_argc);
3097 for (i = 0; i < container->type_argc; ++i) {
3098 MonoGenericParamInfo *info = &container->type_params [i].info;
3099 gboolean ref_only = FALSE;
3101 if (info && info->constraints) {
3102 constraints = info->constraints;
3104 while (*constraints) {
3105 MonoClass *cklass = *constraints;
3106 if (!(cklass == mono_defaults.object_class || (cklass->image == mono_defaults.corlib && !strcmp (cklass->name, "ValueType"))))
3107 /* Inflaring the method with our vtype would not be valid */
3114 args [i] = &mono_defaults.object_class->byval_arg;
3116 args [i] = &mono_defaults.int_class->byval_arg;
3118 ctx->method_inst = mono_metadata_get_generic_inst (inst->type_argc, args);
3123 add_wrappers (MonoAotCompile *acfg)
3125 MonoMethod *method, *m;
3127 MonoMethodSignature *sig, *csig;
3131 * FIXME: Instead of AOTing all the wrappers, it might be better to redesign them
3132 * so there is only one wrapper of a given type, or inlining their contents into their
3137 * FIXME: This depends on the fact that different wrappers have different
3141 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3143 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3144 gboolean skip = FALSE;
3146 method = mono_get_method (acfg->image, token, NULL);
3148 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3149 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
3150 (method->flags & METHOD_ATTRIBUTE_ABSTRACT))
3153 if (method->is_generic || method->klass->generic_container)
3156 /* Skip methods which can not be handled by get_runtime_invoke () */
3157 sig = mono_method_signature (method);
3160 if ((sig->ret->type == MONO_TYPE_PTR) ||
3161 (sig->ret->type == MONO_TYPE_TYPEDBYREF))
3164 for (j = 0; j < sig->param_count; j++) {
3165 if (sig->params [j]->type == MONO_TYPE_TYPEDBYREF)
3169 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3170 if (!mono_class_is_contextbound (method->klass)) {
3171 MonoDynCallInfo *info = mono_arch_dyn_call_prepare (sig);
3172 gboolean has_nullable = FALSE;
3174 for (j = 0; j < sig->param_count; j++) {
3175 if (sig->params [j]->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (sig->params [j])))
3176 has_nullable = TRUE;
3179 if (info && !has_nullable) {
3180 /* Supported by the dynamic runtime-invoke wrapper */
3188 //printf ("%s\n", mono_method_full_name (method, TRUE));
3189 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3193 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
3194 #ifdef MONO_ARCH_HAVE_TLS_GET
3195 MonoMethodDesc *desc;
3196 MonoMethod *orig_method;
3200 /* Runtime invoke wrappers */
3202 /* void runtime-invoke () [.cctor] */
3203 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3204 csig->ret = &mono_defaults.void_class->byval_arg;
3205 add_method (acfg, get_runtime_invoke_sig (csig));
3207 /* void runtime-invoke () [Finalize] */
3208 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3210 csig->ret = &mono_defaults.void_class->byval_arg;
3211 add_method (acfg, get_runtime_invoke_sig (csig));
3213 /* void runtime-invoke (string) [exception ctor] */
3214 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 1);
3216 csig->ret = &mono_defaults.void_class->byval_arg;
3217 csig->params [0] = &mono_defaults.string_class->byval_arg;
3218 add_method (acfg, get_runtime_invoke_sig (csig));
3220 /* void runtime-invoke (string, string) [exception ctor] */
3221 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3223 csig->ret = &mono_defaults.void_class->byval_arg;
3224 csig->params [0] = &mono_defaults.string_class->byval_arg;
3225 csig->params [1] = &mono_defaults.string_class->byval_arg;
3226 add_method (acfg, get_runtime_invoke_sig (csig));
3228 /* string runtime-invoke () [Exception.ToString ()] */
3229 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 0);
3231 csig->ret = &mono_defaults.string_class->byval_arg;
3232 add_method (acfg, get_runtime_invoke_sig (csig));
3234 /* void runtime-invoke (string, Exception) [exception ctor] */
3235 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3237 csig->ret = &mono_defaults.void_class->byval_arg;
3238 csig->params [0] = &mono_defaults.string_class->byval_arg;
3239 csig->params [1] = &mono_defaults.exception_class->byval_arg;
3240 add_method (acfg, get_runtime_invoke_sig (csig));
3242 /* Assembly runtime-invoke (string, bool) [DoAssemblyResolve] */
3243 csig = mono_metadata_signature_alloc (mono_defaults.corlib, 2);
3245 csig->ret = &(mono_class_from_name (
3246 mono_defaults.corlib, "System.Reflection", "Assembly"))->byval_arg;
3247 csig->params [0] = &mono_defaults.string_class->byval_arg;
3248 csig->params [1] = &mono_defaults.boolean_class->byval_arg;
3249 add_method (acfg, get_runtime_invoke_sig (csig));
3251 /* runtime-invoke used by finalizers */
3252 add_method (acfg, mono_marshal_get_runtime_invoke (mono_class_get_method_from_name_flags (mono_defaults.object_class, "Finalize", 0, 0), TRUE));
3254 /* This is used by mono_runtime_capture_context () */
3255 method = mono_get_context_capture_method ();
3257 add_method (acfg, mono_marshal_get_runtime_invoke (method, FALSE));
3259 #ifdef MONO_ARCH_DYN_CALL_SUPPORTED
3260 add_method (acfg, mono_marshal_get_runtime_invoke_dynamic ());
3263 /* JIT icall wrappers */
3264 /* FIXME: locking */
3265 g_hash_table_foreach (mono_get_jit_icall_info (), add_jit_icall_wrapper, acfg);
3268 add_method (acfg, mono_marshal_get_stelemref ());
3270 #ifdef MONO_ARCH_HAVE_TLS_GET
3271 /* Managed Allocators */
3272 nallocators = mono_gc_get_managed_allocator_types ();
3273 for (i = 0; i < nallocators; ++i) {
3274 m = mono_gc_get_managed_allocator_by_type (i);
3276 add_method (acfg, m);
3279 /* Monitor Enter/Exit */
3280 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3281 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3282 /* This is a v4 method */
3284 method = mono_monitor_get_fast_path (orig_method);
3286 add_method (acfg, method);
3288 mono_method_desc_free (desc);
3290 desc = mono_method_desc_new ("Monitor:Exit(object)", FALSE);
3291 orig_method = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3292 g_assert (orig_method);
3293 mono_method_desc_free (desc);
3294 method = mono_monitor_get_fast_path (orig_method);
3296 add_method (acfg, method);
3299 /* Stelemref wrappers */
3301 MonoMethod **wrappers;
3304 wrappers = mono_marshal_get_virtual_stelemref_wrappers (&nwrappers);
3305 for (i = 0; i < nwrappers; ++i)
3306 add_method (acfg, wrappers [i]);
3310 /* castclass_with_check wrapper */
3311 add_method (acfg, mono_marshal_get_castclass_with_cache ());
3312 /* isinst_with_check wrapper */
3313 add_method (acfg, mono_marshal_get_isinst_with_cache ());
3315 #if defined(MONO_ARCH_ENABLE_MONITOR_IL_FASTPATH)
3317 MonoMethodDesc *desc;
3320 desc = mono_method_desc_new ("Monitor:Enter(object,bool&)", FALSE);
3321 m = mono_method_desc_search_in_class (desc, mono_defaults.monitor_class);
3322 mono_method_desc_free (desc);
3324 m = mono_monitor_get_fast_path (m);
3326 add_method (acfg, m);
3333 * remoting-invoke-with-check wrappers are very frequent, so avoid emitting them,
3334 * we use the original method instead at runtime.
3335 * Since full-aot doesn't support remoting, this is not a problem.
3338 /* remoting-invoke wrappers */
3339 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3340 MonoMethodSignature *sig;
3342 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3343 method = mono_get_method (acfg->image, token, NULL);
3345 sig = mono_method_signature (method);
3347 if (sig->hasthis && (method->klass->marshalbyref || method->klass == mono_defaults.object_class)) {
3348 m = mono_marshal_get_remoting_invoke_with_check (method);
3350 add_method (acfg, m);
3355 /* delegate-invoke wrappers */
3356 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3358 MonoCustomAttrInfo *cattr;
3360 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3361 klass = mono_class_get (acfg->image, token);
3364 mono_loader_clear_error ();
3368 if (!klass->delegate || klass == mono_defaults.delegate_class || klass == mono_defaults.multicastdelegate_class)
3371 if (!klass->generic_container) {
3372 method = mono_get_delegate_invoke (klass);
3374 m = mono_marshal_get_delegate_invoke (method, NULL);
3376 add_method (acfg, m);
3378 method = mono_class_get_method_from_name_flags (klass, "BeginInvoke", -1, 0);
3380 add_method (acfg, mono_marshal_get_delegate_begin_invoke (method));
3382 method = mono_class_get_method_from_name_flags (klass, "EndInvoke", -1, 0);
3384 add_method (acfg, mono_marshal_get_delegate_end_invoke (method));
3386 cattr = mono_custom_attrs_from_class (klass);
3391 for (j = 0; j < cattr->num_attrs; ++j)
3392 if (cattr->attrs [j].ctor && (!strcmp (cattr->attrs [j].ctor->klass->name, "MonoNativeFunctionWrapperAttribute") || !strcmp (cattr->attrs [j].ctor->klass->name, "UnmanagedFunctionPointerAttribute")))
3394 if (j < cattr->num_attrs)
3395 add_method (acfg, mono_marshal_get_native_func_wrapper_aot (klass));
3397 } else if ((acfg->opts & MONO_OPT_GSHAREDVT) && klass->generic_container) {
3398 MonoGenericContext ctx;
3399 MonoMethod *inst, *gshared;
3402 * Emit gsharedvt versions of the generic delegate-invoke wrappers
3405 method = mono_get_delegate_invoke (klass);
3406 create_gsharedvt_inst (acfg, method, &ctx);
3408 inst = mono_class_inflate_generic_method (method, &ctx);
3410 m = mono_marshal_get_delegate_invoke (inst, NULL);
3411 g_assert (m->is_inflated);
3413 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3414 add_extra_method (acfg, gshared);
3417 method = mono_get_delegate_begin_invoke (klass);
3418 create_gsharedvt_inst (acfg, method, &ctx);
3420 inst = mono_class_inflate_generic_method (method, &ctx);
3422 m = mono_marshal_get_delegate_begin_invoke (inst);
3423 g_assert (m->is_inflated);
3425 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3426 add_extra_method (acfg, gshared);
3429 method = mono_get_delegate_end_invoke (klass);
3430 create_gsharedvt_inst (acfg, method, &ctx);
3432 inst = mono_class_inflate_generic_method (method, &ctx);
3434 m = mono_marshal_get_delegate_end_invoke (inst);
3435 g_assert (m->is_inflated);
3437 gshared = mini_get_shared_method_full (m, FALSE, TRUE);
3438 add_extra_method (acfg, gshared);
3443 /* Synchronized wrappers */
3444 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3445 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3446 method = mono_get_method (acfg->image, token, NULL);
3448 if (method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED && !method->is_generic)
3449 add_method (acfg, mono_marshal_get_synchronized_wrapper (method));
3452 /* pinvoke wrappers */
3453 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3455 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3457 method = mono_get_method (acfg->image, token, NULL);
3459 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3460 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3461 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3465 /* native-to-managed wrappers */
3466 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHOD].rows; ++i) {
3468 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
3469 MonoCustomAttrInfo *cattr;
3472 method = mono_get_method (acfg->image, token, NULL);
3475 * Only generate native-to-managed wrappers for methods which have an
3476 * attribute named MonoPInvokeCallbackAttribute. We search for the attribute by
3477 * name to avoid defining a new assembly to contain it.
3479 cattr = mono_custom_attrs_from_method (method);
3482 for (j = 0; j < cattr->num_attrs; ++j)
3483 if (cattr->attrs [j].ctor && !strcmp (cattr->attrs [j].ctor->klass->name, "MonoPInvokeCallbackAttribute"))
3485 if (j < cattr->num_attrs) {
3486 MonoCustomAttrEntry *e = &cattr->attrs [j];
3487 MonoMethodSignature *sig = mono_method_signature (e->ctor);
3488 const char *p = (const char*)e->data;
3490 int slen, num_named, named_type, data_type;
3494 char *export_name = NULL;
3495 MonoMethod *wrapper;
3497 /* this cannot be enforced by the C# compiler so we must give the user some warning before aborting */
3498 if (!(method->flags & METHOD_ATTRIBUTE_STATIC)) {
3499 g_warning ("AOT restriction: Method '%s' must be static since it is decorated with [MonoPInvokeCallback]. See http://ios.xamarin.com/Documentation/Limitations#Reverse_Callbacks",
3500 mono_method_full_name (method, TRUE));
3504 g_assert (sig->param_count == 1);
3505 g_assert (sig->params [0]->type == MONO_TYPE_CLASS && !strcmp (mono_class_from_mono_type (sig->params [0])->name, "Type"));
3508 * Decode the cattr manually since we can't create objects
3509 * during aot compilation.
3515 /* From load_cattr_value () in reflection.c */
3516 slen = mono_metadata_decode_value (p, &p);
3517 n = g_memdup (p, slen + 1);
3519 t = mono_reflection_type_from_name (n, acfg->image);
3523 klass = mono_class_from_mono_type (t);
3524 g_assert (klass->parent == mono_defaults.multicastdelegate_class);
3528 num_named = read16 (p);
3531 g_assert (num_named < 2);
3532 if (num_named == 1) {
3535 MonoType *prop_type;
3537 /* parse ExportSymbol attribute */
3539 named_type = *named;
3544 name_len = mono_metadata_decode_blob_size (named, &named);
3545 name = g_malloc (name_len + 1);
3546 memcpy (name, named, name_len);
3547 name [name_len] = 0;
3550 g_assert (named_type == 0x54);
3551 g_assert (!strcmp (name, "ExportSymbol"));
3553 prop_type = &mono_defaults.string_class->byval_arg;
3555 /* load_cattr_value (), string case */
3556 g_assert (*named != (char)0xff);
3557 slen = mono_metadata_decode_value (named, &named);
3558 export_name = g_malloc (slen + 1);
3559 memcpy (export_name, named, slen);
3560 export_name [slen] = 0;
3564 wrapper = mono_marshal_get_managed_wrapper (method, klass, 0);
3565 add_method (acfg, wrapper);
3567 g_hash_table_insert (acfg->export_names, wrapper, export_name);
3571 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
3572 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)) {
3573 add_method (acfg, mono_marshal_get_native_wrapper (method, TRUE, TRUE));
3577 /* StructureToPtr/PtrToStructure wrappers */
3578 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
3581 token = MONO_TOKEN_TYPE_DEF | (i + 1);
3582 klass = mono_class_get (acfg->image, token);
3585 mono_loader_clear_error ();
3589 if (klass->valuetype && !klass->generic_container && can_marshal_struct (klass) &&
3590 !(klass->nested_in && strstr (klass->nested_in->name, "<PrivateImplementationDetails>") == klass->nested_in->name)) {
3591 add_method (acfg, mono_marshal_get_struct_to_ptr (klass));
3592 add_method (acfg, mono_marshal_get_ptr_to_struct (klass));
3598 has_type_vars (MonoClass *klass)
3600 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR))
3603 return has_type_vars (klass->element_class);
3604 if (klass->generic_class) {
3605 MonoGenericContext *context = &klass->generic_class->context;
3606 if (context->class_inst) {
3609 for (i = 0; i < context->class_inst->type_argc; ++i)
3610 if (has_type_vars (mono_class_from_mono_type (context->class_inst->type_argv [i])))
3618 method_has_type_vars (MonoMethod *method)
3620 if (has_type_vars (method->klass))
3623 if (method->is_inflated) {
3624 MonoGenericContext *context = mono_method_get_context (method);
3625 if (context->method_inst) {
3628 for (i = 0; i < context->method_inst->type_argc; ++i)
3629 if (has_type_vars (mono_class_from_mono_type (context->method_inst->type_argv [i])))
3636 static void add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref);
3639 add_generic_class (MonoAotCompile *acfg, MonoClass *klass, gboolean force, const char *ref)
3641 /* This might lead to a huge code blowup so only do it if neccesary */
3642 if (!acfg->aot_opts.full_aot && !force)
3645 add_generic_class_with_depth (acfg, klass, 0, ref);
3649 check_type_depth (MonoType *t, int depth)
3657 case MONO_TYPE_GENERICINST: {
3658 MonoGenericClass *gklass = t->data.generic_class;
3659 MonoGenericInst *ginst = gklass->context.class_inst;
3662 for (i = 0; i < ginst->type_argc; ++i) {
3663 if (check_type_depth (ginst->type_argv [i], depth + 1))
3677 * add_generic_class:
3679 * Add all methods of a generic class.
3682 add_generic_class_with_depth (MonoAotCompile *acfg, MonoClass *klass, int depth, const char *ref)
3685 MonoClassField *field;
3688 if (!acfg->ginst_hash)
3689 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3691 mono_class_init (klass);
3693 if (klass->generic_class && klass->generic_class->context.class_inst->is_open)
3696 if (has_type_vars (klass))
3699 if (!klass->generic_class && !klass->rank)
3702 if (klass->exception_type)
3705 if (!acfg->ginst_hash)
3706 acfg->ginst_hash = g_hash_table_new (NULL, NULL);
3708 if (g_hash_table_lookup (acfg->ginst_hash, klass))
3711 if (check_type_depth (&klass->byval_arg, 0))
3714 if (acfg->aot_opts.log_generics)
3715 printf ("%*sAdding generic instance %s [%s].\n", depth, "", mono_type_full_name (&klass->byval_arg), ref);
3717 g_hash_table_insert (acfg->ginst_hash, klass, klass);
3720 while ((method = mono_class_get_methods (klass, &iter))) {
3721 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
3725 if (method->is_generic)
3730 * FIXME: Instances which are referenced by these methods are not added,
3731 * for example Array.Resize<int> for List<int>.Add ().
3733 add_extra_method_with_depth (acfg, method, depth + 1);
3737 while ((field = mono_class_get_fields (klass, &iter))) {
3738 if (field->type->type == MONO_TYPE_GENERICINST)
3739 add_generic_class_with_depth (acfg, mono_class_from_mono_type (field->type), depth + 1, "field");
3742 if (klass->delegate) {
3743 method = mono_get_delegate_invoke (klass);
3745 method = mono_marshal_get_delegate_invoke (method, NULL);
3747 if (acfg->aot_opts.log_generics)
3748 printf ("%*sAdding method %s.\n", depth, "", mono_method_full_name (method, TRUE));
3750 add_method (acfg, method);
3753 /* Add superclasses */
3755 add_generic_class_with_depth (acfg, klass->parent, depth, "parent");
3758 * For ICollection<T>, add instances of the helper methods
3759 * in Array, since a T[] could be cast to ICollection<T>.
3761 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") &&
3762 (!strcmp(klass->name, "ICollection`1") || !strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IList`1") || !strcmp (klass->name, "IEnumerator`1") || !strcmp (klass->name, "IReadOnlyList`1"))) {
3763 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3764 MonoClass *array_class = mono_bounded_array_class_get (tclass, 1, FALSE);
3768 if (!strcmp (klass->name, "IEnumerator`1"))
3769 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, "IEnumerable`1");
3771 name_prefix = g_strdup_printf ("%s.%s", klass->name_space, klass->name);
3773 /* Add the T[]/InternalEnumerator class */
3774 if (!strcmp (klass->name, "IEnumerable`1") || !strcmp (klass->name, "IEnumerator`1")) {
3778 while ((nclass = mono_class_get_nested_types (array_class->parent, &iter))) {
3779 if (!strcmp (nclass->name, "InternalEnumerator`1"))
3783 nclass = mono_class_inflate_generic_class (nclass, mono_generic_class_get_context (klass->generic_class));
3784 add_generic_class (acfg, nclass, FALSE, "ICollection<T>");
3788 while ((method = mono_class_get_methods (array_class, &iter))) {
3789 if (strstr (method->name, name_prefix)) {
3790 MonoMethod *m = mono_aot_get_array_helper_from_wrapper (method);
3792 add_extra_method_with_depth (acfg, m, depth);
3796 g_free (name_prefix);
3799 /* Add an instance of GenericComparer<T> which is created dynamically by Comparer<T> */
3800 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "Comparer`1")) {
3801 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3802 MonoClass *icomparable, *gcomparer;
3803 MonoGenericContext ctx;
3804 MonoType *args [16];
3806 memset (&ctx, 0, sizeof (ctx));
3808 icomparable = mono_class_from_name (mono_defaults.corlib, "System", "IComparable`1");
3809 g_assert (icomparable);
3810 args [0] = &tclass->byval_arg;
3811 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3813 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (icomparable, &ctx), tclass)) {
3814 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericComparer`1");
3815 g_assert (gcomparer);
3816 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "Comparer<T>");
3820 /* Add an instance of GenericEqualityComparer<T> which is created dynamically by EqualityComparer<T> */
3821 if (klass->image == mono_defaults.corlib && !strcmp (klass->name_space, "System.Collections.Generic") && !strcmp (klass->name, "EqualityComparer`1")) {
3822 MonoClass *tclass = mono_class_from_mono_type (klass->generic_class->context.class_inst->type_argv [0]);
3823 MonoClass *iface, *gcomparer;
3824 MonoGenericContext ctx;
3825 MonoType *args [16];
3827 memset (&ctx, 0, sizeof (ctx));
3829 iface = mono_class_from_name (mono_defaults.corlib, "System", "IEquatable`1");
3831 args [0] = &tclass->byval_arg;
3832 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3834 if (mono_class_is_assignable_from (mono_class_inflate_generic_class (iface, &ctx), tclass)) {
3835 gcomparer = mono_class_from_name (mono_defaults.corlib, "System.Collections.Generic", "GenericEqualityComparer`1");
3836 g_assert (gcomparer);
3837 add_generic_class (acfg, mono_class_inflate_generic_class (gcomparer, &ctx), FALSE, "EqualityComparer<T>");
3843 add_instances_of (MonoAotCompile *acfg, MonoClass *klass, MonoType **insts, int ninsts, gboolean force)
3846 MonoGenericContext ctx;
3847 MonoType *args [16];
3849 if (acfg->aot_opts.no_instances)
3852 memset (&ctx, 0, sizeof (ctx));
3854 for (i = 0; i < ninsts; ++i) {
3855 args [0] = insts [i];
3856 ctx.class_inst = mono_metadata_get_generic_inst (1, args);
3857 add_generic_class (acfg, mono_class_inflate_generic_class (klass, &ctx), force, "");
3862 add_types_from_method_header (MonoAotCompile *acfg, MonoMethod *method)
3864 MonoMethodHeader *header;
3865 MonoMethodSignature *sig;
3868 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
3870 sig = mono_method_signature (method);
3873 for (j = 0; j < sig->param_count; ++j)
3874 if (sig->params [j]->type == MONO_TYPE_GENERICINST)
3875 add_generic_class_with_depth (acfg, mono_class_from_mono_type (sig->params [j]), depth + 1, "arg");
3878 header = mono_method_get_header (method);
3881 for (j = 0; j < header->num_locals; ++j)
3882 if (header->locals [j]->type == MONO_TYPE_GENERICINST)
3883 add_generic_class_with_depth (acfg, mono_class_from_mono_type (header->locals [j]), depth + 1, "local");
3888 * add_generic_instances:
3890 * Add instances referenced by the METHODSPEC/TYPESPEC table.
3893 add_generic_instances (MonoAotCompile *acfg)
3898 MonoGenericContext *context;
3900 if (acfg->aot_opts.no_instances)
3903 for (i = 0; i < acfg->image->tables [MONO_TABLE_METHODSPEC].rows; ++i) {
3904 token = MONO_TOKEN_METHOD_SPEC | (i + 1);
3905 method = mono_get_method (acfg->image, token, NULL);
3910 if (method->klass->image != acfg->image)
3913 context = mono_method_get_context (method);
3915 if (context && ((context->class_inst && context->class_inst->is_open)))
3919 * For open methods, create an instantiation which can be passed to the JIT.
3920 * FIXME: Handle class_inst as well.
3922 if (context && context->method_inst && context->method_inst->is_open) {
3923 MonoGenericContext shared_context;
3924 MonoGenericInst *inst;
3925 MonoType **type_argv;
3927 MonoMethod *declaring_method;
3928 gboolean supported = TRUE;
3930 /* Check that the context doesn't contain open constructed types */
3931 if (context->class_inst) {
3932 inst = context->class_inst;
3933 for (i = 0; i < inst->type_argc; ++i) {
3934 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)
3936 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3940 if (context->method_inst) {
3941 inst = context->method_inst;
3942 for (i = 0; i < inst->type_argc; ++i) {
3943 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)
3945 if (mono_class_is_open_constructed_type (inst->type_argv [i]))
3953 memset (&shared_context, 0, sizeof (MonoGenericContext));
3955 inst = context->class_inst;
3957 type_argv = g_new0 (MonoType*, inst->type_argc);
3958 for (i = 0; i < inst->type_argc; ++i) {
3959 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)
3960 type_argv [i] = &mono_defaults.object_class->byval_arg;
3962 type_argv [i] = inst->type_argv [i];
3965 shared_context.class_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3969 inst = context->method_inst;
3971 type_argv = g_new0 (MonoType*, inst->type_argc);
3972 for (i = 0; i < inst->type_argc; ++i) {
3973 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)
3974 type_argv [i] = &mono_defaults.object_class->byval_arg;
3976 type_argv [i] = inst->type_argv [i];
3979 shared_context.method_inst = mono_metadata_get_generic_inst (inst->type_argc, type_argv);
3983 if (method->is_generic || method->klass->generic_container)
3984 declaring_method = method;
3986 declaring_method = mono_method_get_declaring_generic_method (method);
3988 method = mono_class_inflate_generic_method (declaring_method, &shared_context);
3992 * If the method is fully sharable, it was already added in place of its
3993 * generic definition.
3995 if (mono_method_is_generic_sharable_full (method, FALSE, FALSE, FALSE))
3999 * FIXME: Partially shared methods are not shared here, so we end up with
4000 * many identical methods.
4002 add_extra_method (acfg, method);
4005 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPESPEC].rows; ++i) {
4008 token = MONO_TOKEN_TYPE_SPEC | (i + 1);
4010 klass = mono_class_get (acfg->image, token);
4011 if (!klass || klass->rank) {
4012 mono_loader_clear_error ();
4016 add_generic_class (acfg, klass, FALSE, "typespec");
4019 /* Add types of args/locals */
4020 for (i = 0; i < acfg->methods->len; ++i) {
4021 method = g_ptr_array_index (acfg->methods, i);
4022 add_types_from_method_header (acfg, method);
4025 if (acfg->image == mono_defaults.corlib) {
4027 MonoType *insts [256];
4030 insts [ninsts ++] = &mono_defaults.byte_class->byval_arg;
4031 insts [ninsts ++] = &mono_defaults.sbyte_class->byval_arg;
4032 insts [ninsts ++] = &mono_defaults.int16_class->byval_arg;
4033 insts [ninsts ++] = &mono_defaults.uint16_class->byval_arg;
4034 insts [ninsts ++] = &mono_defaults.int32_class->byval_arg;
4035 insts [ninsts ++] = &mono_defaults.uint32_class->byval_arg;
4036 insts [ninsts ++] = &mono_defaults.int64_class->byval_arg;
4037 insts [ninsts ++] = &mono_defaults.uint64_class->byval_arg;
4038 insts [ninsts ++] = &mono_defaults.single_class->byval_arg;
4039 insts [ninsts ++] = &mono_defaults.double_class->byval_arg;
4040 insts [ninsts ++] = &mono_defaults.char_class->byval_arg;
4041 insts [ninsts ++] = &mono_defaults.boolean_class->byval_arg;
4043 /* Add GenericComparer<T> instances for primitive types for Enum.ToString () */
4044 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericComparer`1");
4046 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4047 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "GenericEqualityComparer`1");
4049 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4051 /* Add instances of the array generic interfaces for primitive types */
4052 /* This will add instances of the InternalArray_ helper methods in Array too */
4053 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "ICollection`1");
4055 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4056 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IList`1");
4058 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4059 klass = mono_class_from_name (acfg->image, "System.Collections.Generic", "IEnumerable`1");
4061 add_instances_of (acfg, klass, insts, ninsts, TRUE);
4064 * Add a managed-to-native wrapper of Array.GetGenericValueImpl<object>, which is
4065 * used for all instances of GetGenericValueImpl by the AOT runtime.
4068 MonoGenericContext ctx;
4069 MonoType *args [16];
4070 MonoMethod *get_method;
4071 MonoClass *array_klass = mono_array_class_get (mono_defaults.object_class, 1)->parent;
4073 get_method = mono_class_get_method_from_name (array_klass, "GetGenericValueImpl", 2);
4076 memset (&ctx, 0, sizeof (ctx));
4077 args [0] = &mono_defaults.object_class->byval_arg;
4078 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4079 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (get_method, &ctx), TRUE, TRUE));
4083 /* Same for CompareExchange<T>/Exchange<T> */
4085 MonoGenericContext ctx;
4086 MonoType *args [16];
4088 MonoClass *interlocked_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Interlocked");
4089 gpointer iter = NULL;
4091 while ((m = mono_class_get_methods (interlocked_klass, &iter))) {
4092 if ((!strcmp (m->name, "CompareExchange") || !strcmp (m->name, "Exchange")) && m->is_generic) {
4093 memset (&ctx, 0, sizeof (ctx));
4094 args [0] = &mono_defaults.object_class->byval_arg;
4095 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4096 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4101 /* Same for Volatile.Read/Write<T> */
4103 MonoGenericContext ctx;
4104 MonoType *args [16];
4106 MonoClass *volatile_klass = mono_class_from_name (mono_defaults.corlib, "System.Threading", "Volatile");
4107 gpointer iter = NULL;
4109 if (volatile_klass) {
4110 while ((m = mono_class_get_methods (volatile_klass, &iter))) {
4111 if ((!strcmp (m->name, "Read") || !strcmp (m->name, "Write")) && m->is_generic) {
4112 memset (&ctx, 0, sizeof (ctx));
4113 args [0] = &mono_defaults.object_class->byval_arg;
4114 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
4115 add_extra_method (acfg, mono_marshal_get_native_wrapper (mono_class_inflate_generic_method (m, &ctx), TRUE, TRUE));
4124 * is_direct_callable:
4126 * Return whenever the method identified by JI is directly callable without
4127 * going through the PLT.
4130 is_direct_callable (MonoAotCompile *acfg, MonoMethod *method, MonoJumpInfo *patch_info)
4132 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4133 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4135 gboolean direct_callable = TRUE;
4137 if (direct_callable && !(!callee_cfg->has_got_slots && (callee_cfg->method->klass->flags & TYPE_ATTRIBUTE_BEFORE_FIELD_INIT)))
4138 direct_callable = FALSE;
4139 if ((callee_cfg->method->iflags & METHOD_IMPL_ATTRIBUTE_SYNCHRONIZED) && (!method || method->wrapper_type != MONO_WRAPPER_SYNCHRONIZED))
4140 // FIXME: Maybe call the wrapper directly ?
4141 direct_callable = FALSE;
4143 if (acfg->aot_opts.soft_debug || acfg->aot_opts.no_direct_calls) {
4144 /* Disable this so all calls go through load_method (), see the
4145 * mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE; line in
4146 * mono_debugger_agent_init ().
4148 direct_callable = FALSE;
4151 if (direct_callable)
4154 } else if ((patch_info->type == MONO_PATCH_INFO_ICALL_ADDR && patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL)) {
4155 if (acfg->aot_opts.direct_pinvoke)
4157 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4158 if (acfg->aot_opts.direct_icalls)
4167 get_pinvoke_import (MonoAotCompile *acfg, MonoMethod *method)
4169 MonoImage *image = method->klass->image;
4170 MonoMethodPInvoke *piinfo = (MonoMethodPInvoke *) method;
4171 MonoTableInfo *tables = image->tables;
4172 MonoTableInfo *im = &tables [MONO_TABLE_IMPLMAP];
4173 MonoTableInfo *mr = &tables [MONO_TABLE_MODULEREF];
4174 guint32 im_cols [MONO_IMPLMAP_SIZE];
4177 import = g_hash_table_lookup (acfg->method_to_pinvoke_import, method);
4181 if (!piinfo->implmap_idx || piinfo->implmap_idx > im->rows)
4184 mono_metadata_decode_row (im, piinfo->implmap_idx - 1, im_cols, MONO_IMPLMAP_SIZE);
4186 if (!im_cols [MONO_IMPLMAP_SCOPE] || im_cols [MONO_IMPLMAP_SCOPE] > mr->rows)
4189 import = g_strdup_printf ("%s", mono_metadata_string_heap (image, im_cols [MONO_IMPLMAP_NAME]));
4191 g_hash_table_insert (acfg->method_to_pinvoke_import, method, import);
4197 * emit_and_reloc_code:
4199 * Emit the native code in CODE, handling relocations along the way. If GOT_ONLY
4200 * is true, calls are made through the GOT too. This is used for emitting trampolines
4201 * in full-aot mode, since calls made from trampolines couldn't go through the PLT,
4202 * since trampolines are needed to make PTL work.
4205 emit_and_reloc_code (MonoAotCompile *acfg, MonoMethod *method, guint8 *code, guint32 code_len, MonoJumpInfo *relocs, gboolean got_only)
4207 int i, pindex, start_index, method_index;
4209 MonoJumpInfo *patch_info;
4210 MonoMethodHeader *header;
4211 gboolean skip, direct_call, external_call;
4213 const char *direct_call_target;
4214 const char *direct_pinvoke;
4217 header = mono_method_get_header (method);
4219 method_index = get_method_index (acfg, method);
4222 /* Collect and sort relocations */
4223 patches = g_ptr_array_new ();
4224 for (patch_info = relocs; patch_info; patch_info = patch_info->next)
4225 g_ptr_array_add (patches, patch_info);
4226 g_ptr_array_sort (patches, compare_patches);
4229 for (i = 0; i < code_len; i++) {
4231 for (pindex = start_index; pindex < patches->len; ++pindex) {
4232 patch_info = g_ptr_array_index (patches, pindex);
4233 if (patch_info->ip.i >= i)
4237 #ifdef MONO_ARCH_AOT_SUPPORTED
4239 if (patch_info && (patch_info->ip.i == i) && (pindex < patches->len)) {
4240 start_index = pindex;
4242 switch (patch_info->type) {
4243 case MONO_PATCH_INFO_NONE:
4245 case MONO_PATCH_INFO_GOT_OFFSET: {
4248 arch_emit_got_offset (acfg, code + i, &code_size);
4251 patch_info->type = MONO_PATCH_INFO_NONE;
4256 * If this patch is a call, try emitting a direct call instead of
4257 * through a PLT entry. This is possible if the called method is in
4258 * the same assembly and requires no initialization.
4260 direct_call = FALSE;
4261 external_call = FALSE;
4262 if ((patch_info->type == MONO_PATCH_INFO_METHOD) && (patch_info->data.method->klass->image == acfg->image)) {
4263 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4264 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, patch_info->data.method);
4265 //printf ("DIRECT: %s %s\n", method ? mono_method_full_name (method, TRUE) : "", mono_method_full_name (callee_cfg->method, TRUE));
4267 direct_call_target = callee_cfg->asm_symbol;
4268 patch_info->type = MONO_PATCH_INFO_NONE;
4269 acfg->stats.direct_calls ++;
4272 acfg->stats.all_calls ++;
4273 } else if (patch_info->type == MONO_PATCH_INFO_ICALL_ADDR) {
4274 if (!got_only && is_direct_callable (acfg, method, patch_info)) {
4275 if (!(patch_info->data.method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL))
4276 direct_pinvoke = mono_lookup_icall_symbol (patch_info->data.method);
4278 direct_pinvoke = get_pinvoke_import (acfg, patch_info->data.method);
4279 if (direct_pinvoke) {
4281 g_assert (strlen (direct_pinvoke) < 1000);
4282 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, direct_pinvoke);
4285 } else if (patch_info->type == MONO_PATCH_INFO_JIT_ICALL_ADDR) {
4286 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4287 if (!got_only && sym && acfg->aot_opts.direct_icalls) {
4288 /* Call to a C function implementing a jit icall */
4290 external_call = TRUE;
4291 g_assert (strlen (sym) < 1000);
4292 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4294 } else if (patch_info->type == MONO_PATCH_INFO_INTERNAL_METHOD) {
4295 MonoJitICallInfo *info = mono_find_jit_icall_by_name (patch_info->data.name);
4296 const char *sym = mono_lookup_jit_icall_symbol (patch_info->data.name);
4297 if (!got_only && sym && acfg->aot_opts.direct_icalls && info->func == info->wrapper) {
4298 /* Call to a jit icall without a wrapper */
4300 external_call = TRUE;
4301 g_assert (strlen (sym) < 1000);
4302 direct_call_target = g_strdup_printf ("%s%s", acfg->user_symbol_prefix, sym);
4307 patch_info->type = MONO_PATCH_INFO_NONE;
4308 acfg->stats.direct_calls ++;
4311 if (!got_only && !direct_call) {
4312 MonoPltEntry *plt_entry = get_plt_entry (acfg, patch_info);
4314 /* This patch has a PLT entry, so we must emit a call to the PLT entry */
4316 direct_call_target = plt_entry->symbol;
4318 /* Nullify the patch */
4319 patch_info->type = MONO_PATCH_INFO_NONE;
4320 plt_entry->jit_used = TRUE;
4327 arch_emit_direct_call (acfg, direct_call_target, external_call, &call_size);
4332 got_slot = get_got_offset (acfg, patch_info);
4334 arch_emit_got_access (acfg, code + i, got_slot, &code_size);
4341 #endif /* MONO_ARCH_AOT_SUPPORTED */
4344 /* Find next patch */
4346 for (pindex = start_index; pindex < patches->len; ++pindex) {
4347 patch_info = g_ptr_array_index (patches, pindex);
4348 if (patch_info->ip.i >= i)
4352 /* Try to emit multiple bytes at once */
4353 if (pindex < patches->len && patch_info->ip.i > i) {
4354 emit_bytes (acfg, code + i, patch_info->ip.i - i);
4355 i = patch_info->ip.i - 1;
4357 emit_bytes (acfg, code + i, 1);
4366 * Modify SYMBOL so it only includes characters permissible in symbols.
4369 sanitize_symbol (char *symbol)
4371 int i, len = strlen (symbol);
4373 for (i = 0; i < len; ++i)
4374 if (!isalnum (symbol [i]) && (symbol [i] != '_'))
4379 get_debug_sym (MonoMethod *method, const char *prefix, GHashTable *cache)
4381 char *name1, *name2, *cached;
4382 int i, j, len, count;
4385 // This is so that we don't accidentally create a local symbol (which starts with 'L')
4386 if (!prefix || !*prefix)
4390 name1 = mono_method_full_name (method, TRUE);
4391 len = strlen (name1);
4392 name2 = malloc (strlen (prefix) + len + 16);
4393 memcpy (name2, prefix, strlen (prefix));
4394 j = strlen (prefix);
4395 for (i = 0; i < len; ++i) {
4396 if (isalnum (name1 [i])) {
4397 name2 [j ++] = name1 [i];
4398 } else if (name1 [i] == ' ' && name1 [i + 1] == '(' && name1 [i + 2] == ')') {
4400 } else if (name1 [i] == ',' && name1 [i + 1] == ' ') {
4403 } else if (name1 [i] == '(' || name1 [i] == ')' || name1 [i] == '>') {
4412 while (g_hash_table_lookup (cache, name2)) {
4413 sprintf (name2 + j, "_%d", count);
4417 cached = g_strdup (name2);
4418 g_hash_table_insert (cache, cached, cached);
4424 emit_method_code (MonoAotCompile *acfg, MonoCompile *cfg)
4429 char *debug_sym = NULL;
4430 char *symbol = NULL;
4431 int func_alignment = AOT_FUNC_ALIGNMENT;
4432 MonoMethodHeader *header;
4435 method = cfg->orig_method;
4436 code = cfg->native_code;
4437 header = cfg->header;
4439 method_index = get_method_index (acfg, method);
4440 symbol = g_strdup_printf ("%sme_%x", acfg->temp_prefix, method_index);
4443 /* Make the labels local */
4444 emit_section_change (acfg, ".text", 0);
4445 emit_alignment (acfg, func_alignment);
4447 if (acfg->global_symbols && acfg->need_no_dead_strip)
4448 fprintf (acfg->fp, " .no_dead_strip %s\n", cfg->asm_symbol);
4450 emit_label (acfg, cfg->asm_symbol);
4452 if (acfg->aot_opts.write_symbols && !acfg->global_symbols) {
4454 * Write a C style symbol for every method, this has two uses:
4455 * - it works on platforms where the dwarf debugging info is not
4457 * - it allows the setting of breakpoints of aot-ed methods.
4459 debug_sym = get_debug_sym (method, "", acfg->method_label_hash);
4461 if (acfg->need_no_dead_strip)
4462 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
4463 emit_local_symbol (acfg, debug_sym, symbol, TRUE);
4464 emit_label (acfg, debug_sym);
4467 export_name = g_hash_table_lookup (acfg->export_names, method);
4469 /* Emit a global symbol for the method */
4470 emit_global_inner (acfg, export_name, TRUE);
4471 emit_label (acfg, export_name);
4474 if (cfg->verbose_level > 0)
4475 g_print ("Method %s emitted as %s\n", mono_method_full_name (method, TRUE), cfg->asm_symbol);
4477 acfg->stats.code_size += cfg->code_len;
4479 acfg->cfgs [method_index]->got_offset = acfg->got_offset;
4481 emit_and_reloc_code (acfg, method, code, cfg->code_len, cfg->patch_info, FALSE);
4485 if (acfg->aot_opts.write_symbols) {
4486 emit_symbol_size (acfg, debug_sym, ".");
4490 emit_label (acfg, symbol);
4497 * Encode PATCH_INFO into its disk representation.
4500 encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info, guint8 *buf, guint8 **endbuf)
4504 switch (patch_info->type) {
4505 case MONO_PATCH_INFO_NONE:
4507 case MONO_PATCH_INFO_IMAGE:
4508 encode_value (get_image_index (acfg, patch_info->data.image), p, &p);
4510 case MONO_PATCH_INFO_MSCORLIB_GOT_ADDR:
4511 case MONO_PATCH_INFO_JIT_TLS_ID:
4512 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
4513 case MONO_PATCH_INFO_CASTCLASS_CACHE:
4515 case MONO_PATCH_INFO_METHOD_REL:
4516 encode_value ((gint)patch_info->data.offset, p, &p);
4518 case MONO_PATCH_INFO_SWITCH: {
4519 gpointer *table = (gpointer *)patch_info->data.table->table;
4522 encode_value (patch_info->data.table->table_size, p, &p);
4523 for (k = 0; k < patch_info->data.table->table_size; k++)
4524 encode_value ((int)(gssize)table [k], p, &p);
4527 case MONO_PATCH_INFO_METHODCONST:
4528 case MONO_PATCH_INFO_METHOD:
4529 case MONO_PATCH_INFO_METHOD_JUMP:
4530 case MONO_PATCH_INFO_ICALL_ADDR:
4531 case MONO_PATCH_INFO_METHOD_RGCTX:
4532 encode_method_ref (acfg, patch_info->data.method, p, &p);
4534 case MONO_PATCH_INFO_INTERNAL_METHOD:
4535 case MONO_PATCH_INFO_JIT_ICALL_ADDR: {
4536 guint32 len = strlen (patch_info->data.name);
4538 encode_value (len, p, &p);
4540 memcpy (p, patch_info->data.name, len);
4545 case MONO_PATCH_INFO_LDSTR: {
4546 guint32 image_index = get_image_index (acfg, patch_info->data.token->image);
4547 guint32 token = patch_info->data.token->token;
4548 g_assert (mono_metadata_token_code (token) == MONO_TOKEN_STRING);
4549 encode_value (image_index, p, &p);
4550 encode_value (patch_info->data.token->token - MONO_TOKEN_STRING, p, &p);
4553 case MONO_PATCH_INFO_RVA:
4554 case MONO_PATCH_INFO_DECLSEC:
4555 case MONO_PATCH_INFO_LDTOKEN:
4556 case MONO_PATCH_INFO_TYPE_FROM_HANDLE:
4557 encode_value (get_image_index (acfg, patch_info->data.token->image), p, &p);
4558 encode_value (patch_info->data.token->token, p, &p);
4559 encode_value (patch_info->data.token->has_context, p, &p);
4560 if (patch_info->data.token->has_context)
4561 encode_generic_context (acfg, &patch_info->data.token->context, p, &p);
4563 case MONO_PATCH_INFO_EXC_NAME: {
4564 MonoClass *ex_class;
4567 mono_class_from_name (mono_defaults.exception_class->image,
4568 "System", patch_info->data.target);
4569 g_assert (ex_class);
4570 encode_klass_ref (acfg, ex_class, p, &p);
4573 case MONO_PATCH_INFO_R4:
4574 encode_value (*((guint32 *)patch_info->data.target), p, &p);
4576 case MONO_PATCH_INFO_R8:
4577 encode_value (((guint32 *)patch_info->data.target) [MINI_LS_WORD_IDX], p, &p);
4578 encode_value (((guint32 *)patch_info->data.target) [MINI_MS_WORD_IDX], p, &p);
4580 case MONO_PATCH_INFO_VTABLE:
4581 case MONO_PATCH_INFO_CLASS:
4582 case MONO_PATCH_INFO_IID:
4583 case MONO_PATCH_INFO_ADJUSTED_IID:
4584 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4586 case MONO_PATCH_INFO_CLASS_INIT:
4587 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
4588 encode_klass_ref (acfg, patch_info->data.klass, p, &p);
4590 case MONO_PATCH_INFO_FIELD:
4591 case MONO_PATCH_INFO_SFLDA:
4592 encode_field_info (acfg, patch_info->data.field, p, &p);
4594 case MONO_PATCH_INFO_INTERRUPTION_REQUEST_FLAG:
4596 case MONO_PATCH_INFO_RGCTX_FETCH: {
4597 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
4602 * entry->method has a lenghtly encoding and multiple rgctx_fetch entries
4603 * reference the same method, so encode the method only once.
4605 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_blob_hash, entry->method));
4607 buf2 = g_malloc (1024);
4610 encode_method_ref (acfg, entry->method, p2, &p2);
4611 g_assert (p2 - buf2 < 1024);
4613 offset = add_to_blob (acfg, buf2, p2 - buf2);
4616 g_hash_table_insert (acfg->method_blob_hash, entry->method, GUINT_TO_POINTER (offset + 1));
4621 encode_value (offset, p, &p);
4622 g_assert (entry->info_type < 256);
4623 g_assert (entry->data->type < 256);
4624 encode_value ((entry->in_mrgctx ? 1 : 0) | (entry->info_type << 1) | (entry->data->type << 9), p, &p);
4625 encode_patch (acfg, entry->data, p, &p);
4628 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
4629 case MONO_PATCH_INFO_MONITOR_ENTER:
4630 case MONO_PATCH_INFO_MONITOR_EXIT:
4631 case MONO_PATCH_INFO_SEQ_POINT_INFO:
4633 case MONO_PATCH_INFO_LLVM_IMT_TRAMPOLINE:
4634 encode_method_ref (acfg, patch_info->data.imt_tramp->method, p, &p);
4635 encode_value (patch_info->data.imt_tramp->vt_offset, p, &p);
4637 case MONO_PATCH_INFO_SIGNATURE:
4638 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.target, p, &p);
4640 case MONO_PATCH_INFO_GSHAREDVT_CALL:
4641 encode_signature (acfg, (MonoMethodSignature*)patch_info->data.gsharedvt->sig, p, &p);
4642 encode_method_ref (acfg, patch_info->data.gsharedvt->method, p, &p);
4645 g_warning ("unable to handle jump info %d", patch_info->type);
4646 g_assert_not_reached ();
4653 encode_patch_list (MonoAotCompile *acfg, GPtrArray *patches, int n_patches, int first_got_offset, guint8 *buf, guint8 **endbuf)
4656 guint32 pindex, offset;
4657 MonoJumpInfo *patch_info;
4659 encode_value (n_patches, p, &p);
4661 for (pindex = 0; pindex < patches->len; ++pindex) {
4662 patch_info = g_ptr_array_index (patches, pindex);
4664 if (patch_info->type == MONO_PATCH_INFO_NONE || patch_info->type == MONO_PATCH_INFO_BB)
4668 offset = get_got_offset (acfg, patch_info);
4669 encode_value (offset, p, &p);
4676 emit_method_info (MonoAotCompile *acfg, MonoCompile *cfg)
4680 int pindex, buf_size, n_patches;
4682 MonoJumpInfo *patch_info;
4683 MonoMethodHeader *header;
4684 guint32 method_index;
4686 guint32 first_got_offset;
4688 method = cfg->orig_method;
4689 header = mono_method_get_header (method);
4691 method_index = get_method_index (acfg, method);
4693 /* Sort relocations */
4694 patches = g_ptr_array_new ();
4695 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next)
4696 g_ptr_array_add (patches, patch_info);
4697 g_ptr_array_sort (patches, compare_patches);
4699 first_got_offset = acfg->cfgs [method_index]->got_offset;
4701 /**********************/
4702 /* Encode method info */
4703 /**********************/
4705 buf_size = (patches->len < 1000) ? 40960 : 40960 + (patches->len * 64);
4706 p = buf = g_malloc (buf_size);
4708 if (mono_class_get_cctor (method->klass))
4709 encode_klass_ref (acfg, method->klass, p, &p);
4711 /* Not needed when loading the method */
4712 encode_value (0, p, &p);
4715 if (cfg->opt & MONO_OPT_SHARED) {
4716 encode_value (g_list_length (cfg->ldstr_list), p, &p);
4717 for (l = cfg->ldstr_list; l; l = l->next) {
4718 encode_value ((long)l->data, p, &p);
4722 /* Used only in shared mode */
4723 g_assert (!cfg->ldstr_list);
4726 for (pindex = 0; pindex < patches->len; ++pindex) {
4727 patch_info = g_ptr_array_index (patches, pindex);
4729 if ((patch_info->type == MONO_PATCH_INFO_GOT_OFFSET) ||
4730 (patch_info->type == MONO_PATCH_INFO_NONE)) {
4731 patch_info->type = MONO_PATCH_INFO_NONE;
4736 if ((patch_info->type == MONO_PATCH_INFO_IMAGE) && (patch_info->data.image == acfg->image)) {
4737 /* Stored in a GOT slot initialized at module load time */
4738 patch_info->type = MONO_PATCH_INFO_NONE;
4742 if (patch_info->type == MONO_PATCH_INFO_GC_CARD_TABLE_ADDR) {
4743 /* Stored in a GOT slot initialized at module load time */
4744 patch_info->type = MONO_PATCH_INFO_NONE;
4748 if (is_plt_patch (patch_info)) {
4749 /* Calls are made through the PLT */
4750 patch_info->type = MONO_PATCH_INFO_NONE;
4758 g_assert (cfg->has_got_slots);
4760 encode_patch_list (acfg, patches, n_patches, first_got_offset, p, &p);
4762 acfg->stats.info_size += p - buf;
4764 g_assert (p - buf < buf_size);
4766 cfg->method_info_offset = add_to_blob (acfg, buf, p - buf);
4771 get_unwind_info_offset (MonoAotCompile *acfg, guint8 *encoded, guint32 encoded_len)
4773 guint32 cache_index;
4776 /* Reuse the unwind module to canonize and store unwind info entries */
4777 cache_index = mono_cache_unwind_info (encoded, encoded_len);
4779 /* Use +/- 1 to distinguish 0s from missing entries */
4780 offset = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1)));
4788 * It would be easier to use assembler symbols, but the caller needs an
4791 offset = acfg->unwind_info_offset;
4792 g_hash_table_insert (acfg->unwind_info_offsets, GUINT_TO_POINTER (cache_index + 1), GUINT_TO_POINTER (offset + 1));
4793 g_ptr_array_add (acfg->unwind_ops, GUINT_TO_POINTER (cache_index));
4796 encode_value (encoded_len, p, &p);
4798 acfg->unwind_info_offset += encoded_len + (p - buf);
4804 emit_exception_debug_info (MonoAotCompile *acfg, MonoCompile *cfg)
4807 int i, k, buf_size, method_index;
4808 guint32 debug_info_size;
4810 MonoMethodHeader *header;
4811 guint8 *p, *buf, *debug_info;
4812 MonoJitInfo *jinfo = cfg->jit_info;
4814 gboolean use_unwind_ops = FALSE;
4815 MonoSeqPointInfo *seq_points;
4817 method = cfg->orig_method;
4818 code = cfg->native_code;
4819 header = cfg->header;
4821 method_index = get_method_index (acfg, method);
4823 if (!acfg->aot_opts.nodebug) {
4824 mono_debug_serialize_debug_info (cfg, &debug_info, &debug_info_size);
4827 debug_info_size = 0;
4830 seq_points = cfg->seq_point_info;
4832 buf_size = header->num_clauses * 256 + debug_info_size + 2048 + (seq_points ? (seq_points->len * 64) : 0) + cfg->gc_map_size;
4833 p = buf = g_malloc (buf_size);
4835 #ifdef MONO_ARCH_HAVE_XP_UNWIND
4836 use_unwind_ops = cfg->unwind_ops != NULL;
4839 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);
4841 encode_value (flags, p, &p);
4843 if (use_unwind_ops) {
4844 guint32 encoded_len;
4848 * This is a duplicate of the data in the .debug_frame section, but that
4849 * section cannot be accessed using the dl interface.
4851 encoded = mono_unwind_ops_encode (cfg->unwind_ops, &encoded_len);
4852 encode_value (get_unwind_info_offset (acfg, encoded, encoded_len), p, &p);
4855 encode_value (jinfo->used_regs, p, &p);
4858 /*Encode the number of holes before the number of clauses to make decoding easier*/
4859 if (jinfo->has_try_block_holes) {
4860 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4861 encode_value (table->num_holes, p, &p);
4864 /* Exception table */
4865 if (cfg->compile_llvm) {
4867 * When using LLVM, we can't emit some data, like pc offsets, this reg/offset etc.,
4868 * since the information is only available to llc. Instead, we let llc save the data
4869 * into the LSDA, and read it from there at runtime.
4871 /* The assembly might be CIL stripped so emit the data ourselves */
4872 if (header->num_clauses)
4873 encode_value (header->num_clauses, p, &p);
4875 for (k = 0; k < header->num_clauses; ++k) {
4876 MonoExceptionClause *clause;
4878 clause = &header->clauses [k];
4880 encode_value (clause->flags, p, &p);
4881 if (clause->data.catch_class) {
4882 encode_value (1, p, &p);
4883 encode_klass_ref (acfg, clause->data.catch_class, p, &p);
4885 encode_value (0, p, &p);
4888 /* Emit a list of nesting clauses */
4889 for (i = 0; i < header->num_clauses; ++i) {
4891 MonoExceptionClause *clause1 = &header->clauses [cindex1];
4893 MonoExceptionClause *clause2 = &header->clauses [cindex2];
4895 if (cindex1 != cindex2 && clause1->try_offset >= clause2->try_offset && clause1->handler_offset <= clause2->handler_offset)
4896 encode_value (i, p, &p);
4898 encode_value (-1, p, &p);
4901 if (jinfo->num_clauses)
4902 encode_value (jinfo->num_clauses, p, &p);
4904 for (k = 0; k < jinfo->num_clauses; ++k) {
4905 MonoJitExceptionInfo *ei = &jinfo->clauses [k];
4907 encode_value (ei->flags, p, &p);
4908 encode_value (ei->exvar_offset, p, &p);
4910 if (ei->flags == MONO_EXCEPTION_CLAUSE_FILTER || ei->flags == MONO_EXCEPTION_CLAUSE_FINALLY)
4911 encode_value ((gint)((guint8*)ei->data.filter - code), p, &p);
4913 if (ei->data.catch_class) {
4914 encode_value (1, p, &p);
4915 encode_klass_ref (acfg, ei->data.catch_class, p, &p);
4917 encode_value (0, p, &p);
4921 encode_value ((gint)((guint8*)ei->try_start - code), p, &p);
4922 encode_value ((gint)((guint8*)ei->try_end - code), p, &p);
4923 encode_value ((gint)((guint8*)ei->handler_start - code), p, &p);
4927 if (jinfo->has_generic_jit_info) {
4928 MonoGenericJitInfo *gi = mono_jit_info_get_generic_jit_info (jinfo);
4929 MonoGenericSharingContext* gsctx = gi->generic_sharing_context;
4933 encode_value (gi->nlocs, p, &p);
4935 for (i = 0; i < gi->nlocs; ++i) {
4936 MonoDwarfLocListEntry *entry = &gi->locations [i];
4938 encode_value (entry->is_reg ? 1 : 0, p, &p);
4939 encode_value (entry->reg, p, &p);
4941 encode_value (entry->offset, p, &p);
4943 g_assert (entry->from == 0);
4945 encode_value (entry->from, p, &p);
4946 encode_value (entry->to, p, &p);
4949 if (!cfg->compile_llvm) {
4950 encode_value (gi->has_this ? 1 : 0, p, &p);
4951 encode_value (gi->this_reg, p, &p);
4952 encode_value (gi->this_offset, p, &p);
4957 * Need to encode jinfo->method too, since it is not equal to 'method'
4958 * when using generic sharing.
4960 encode_method_ref (acfg, jinfo->method, p, &p);
4962 if (gsctx && (gsctx->var_is_vt || gsctx->mvar_is_vt)) {
4963 MonoMethodInflated *inflated;
4964 MonoGenericContext *context;
4965 MonoGenericInst *inst;
4967 g_assert (jinfo->method->is_inflated);
4968 inflated = (MonoMethodInflated*)jinfo->method;
4969 context = &inflated->context;
4971 encode_value (1, p, &p);
4972 if (context->class_inst) {
4973 inst = context->class_inst;
4975 encode_value (inst->type_argc, p, &p);
4976 for (i = 0; i < inst->type_argc; ++i)
4977 encode_value (gsctx->var_is_vt [i], p, &p);
4979 encode_value (0, p, &p);
4981 if (context->method_inst) {
4982 inst = context->method_inst;
4984 encode_value (inst->type_argc, p, &p);
4985 for (i = 0; i < inst->type_argc; ++i)
4986 encode_value (gsctx->mvar_is_vt [i], p, &p);
4988 encode_value (0, p, &p);
4991 encode_value (0, p, &p);
4995 if (jinfo->has_try_block_holes) {
4996 MonoTryBlockHoleTableJitInfo *table = mono_jit_info_get_try_block_hole_table_info (jinfo);
4997 for (i = 0; i < table->num_holes; ++i) {
4998 MonoTryBlockHoleJitInfo *hole = &table->holes [i];
4999 encode_value (hole->clause, p, &p);
5000 encode_value (hole->length, p, &p);
5001 encode_value (hole->offset, p, &p);
5005 if (jinfo->has_arch_eh_info) {
5006 MonoArchEHJitInfo *eh_info;
5008 eh_info = mono_jit_info_get_arch_eh_info (jinfo);
5009 encode_value (eh_info->stack_size, p, &p);
5013 int il_offset, native_offset, last_il_offset, last_native_offset, j;
5015 encode_value (seq_points->len, p, &p);
5016 last_il_offset = last_native_offset = 0;
5017 for (i = 0; i < seq_points->len; ++i) {
5018 SeqPoint *sp = &seq_points->seq_points [i];
5019 il_offset = sp->il_offset;
5020 native_offset = sp->native_offset;
5021 encode_value (il_offset - last_il_offset, p, &p);
5022 encode_value (native_offset - last_native_offset, p, &p);
5023 last_il_offset = il_offset;
5024 last_native_offset = native_offset;
5026 encode_value (sp->next_len, p, &p);
5027 for (j = 0; j < sp->next_len; ++j)
5028 encode_value (sp->next [j], p, &p);
5032 g_assert (debug_info_size < buf_size);
5034 encode_value (debug_info_size, p, &p);
5035 if (debug_info_size) {
5036 memcpy (p, debug_info, debug_info_size);
5037 p += debug_info_size;
5038 g_free (debug_info);
5043 encode_value (cfg->gc_map_size, p, &p);
5044 /* The GC map requires 4 bytes of alignment */
5045 while ((gsize)p % 4)
5047 memcpy (p, cfg->gc_map, cfg->gc_map_size);
5048 p += cfg->gc_map_size;
5051 acfg->stats.ex_info_size += p - buf;
5053 g_assert (p - buf < buf_size);
5056 /* The GC Map requires 4 byte alignment */
5057 cfg->ex_info_offset = add_to_blob_aligned (acfg, buf, p - buf, cfg->gc_map ? 4 : 1);
5062 emit_klass_info (MonoAotCompile *acfg, guint32 token)
5064 MonoClass *klass = mono_class_get (acfg->image, token);
5066 int i, buf_size, res;
5067 gboolean no_special_static, cant_encode;
5068 gpointer iter = NULL;
5071 mono_loader_clear_error ();
5075 p = buf = g_malloc (buf_size);
5077 /* Mark as unusable */
5078 encode_value (-1, p, &p);
5080 res = add_to_blob (acfg, buf, p - buf);
5086 buf_size = 10240 + (klass->vtable_size * 16);
5087 p = buf = g_malloc (buf_size);
5091 mono_class_init (klass);
5093 mono_class_get_nested_types (klass, &iter);
5094 g_assert (klass->nested_classes_inited);
5096 mono_class_setup_vtable (klass);
5099 * Emit all the information which is required for creating vtables so
5100 * the runtime does not need to create the MonoMethod structures which
5101 * take up a lot of space.
5104 no_special_static = !mono_class_has_special_static_fields (klass);
5106 /* Check whenever we have enough info to encode the vtable */
5107 cant_encode = FALSE;
5108 for (i = 0; i < klass->vtable_size; ++i) {
5109 MonoMethod *cm = klass->vtable [i];
5111 if (cm && mono_method_signature (cm)->is_inflated && !g_hash_table_lookup (acfg->token_info_hash, cm))
5115 mono_class_has_finalizer (klass);
5117 if (klass->generic_container || cant_encode) {
5118 encode_value (-1, p, &p);
5120 encode_value (klass->vtable_size, p, &p);
5121 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);
5122 if (klass->has_cctor)
5123 encode_method_ref (acfg, mono_class_get_cctor (klass), p, &p);
5124 if (klass->has_finalize)
5125 encode_method_ref (acfg, mono_class_get_finalizer (klass), p, &p);
5127 encode_value (klass->instance_size, p, &p);
5128 encode_value (mono_class_data_size (klass), p, &p);
5129 encode_value (klass->packing_size, p, &p);
5130 encode_value (klass->min_align, p, &p);
5132 for (i = 0; i < klass->vtable_size; ++i) {
5133 MonoMethod *cm = klass->vtable [i];
5136 encode_method_ref (acfg, cm, p, &p);
5138 encode_value (0, p, &p);
5142 acfg->stats.class_info_size += p - buf;
5144 g_assert (p - buf < buf_size);
5145 res = add_to_blob (acfg, buf, p - buf);
5152 get_plt_entry_debug_sym (MonoAotCompile *acfg, MonoJumpInfo *ji, GHashTable *cache)
5154 char *debug_sym = NULL;
5157 case MONO_PATCH_INFO_METHOD:
5158 debug_sym = get_debug_sym (ji->data.method, "plt_", cache);
5160 case MONO_PATCH_INFO_INTERNAL_METHOD:
5161 debug_sym = g_strdup_printf ("plt__jit_icall_%s", ji->data.name);
5163 case MONO_PATCH_INFO_CLASS_INIT:
5164 debug_sym = g_strdup_printf ("plt__class_init_%s", mono_type_get_name (&ji->data.klass->byval_arg));
5165 sanitize_symbol (debug_sym);
5167 case MONO_PATCH_INFO_RGCTX_FETCH:
5168 debug_sym = g_strdup_printf ("plt__rgctx_fetch_%d", acfg->label_generator ++);
5170 case MONO_PATCH_INFO_ICALL_ADDR: {
5171 char *s = get_debug_sym (ji->data.method, "", cache);
5173 debug_sym = g_strdup_printf ("plt__icall_native_%s", s);
5177 case MONO_PATCH_INFO_JIT_ICALL_ADDR:
5178 debug_sym = g_strdup_printf ("plt__jit_icall_native_%s", ji->data.name);
5180 case MONO_PATCH_INFO_GENERIC_CLASS_INIT:
5181 debug_sym = g_strdup_printf ("plt__generic_class_init");
5191 * Calls made from AOTed code are routed through a table of jumps similar to the
5192 * ELF PLT (Program Linkage Table). Initially the PLT entries jump to code which transfers
5193 * control to the AOT runtime through a trampoline.
5196 emit_plt (MonoAotCompile *acfg)
5202 sprintf (symbol, "plt");
5204 emit_section_change (acfg, ".text", 0);
5205 emit_alignment (acfg, NACL_SIZE(16, kNaClAlignment));
5206 emit_label (acfg, symbol);
5207 emit_label (acfg, acfg->plt_symbol);
5209 for (i = 0; i < acfg->plt_offset; ++i) {
5210 char *debug_sym = NULL;
5211 MonoPltEntry *plt_entry = NULL;
5216 * The first plt entry is unused.
5220 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5225 * If the target is directly callable, alias the plt symbol to point to
5227 * FIXME: Use this to simplify emit_and_reloc_code ().
5228 * FIXME: Avoid the got slot.
5229 * FIXME: Add support to the binary writer.
5231 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer) {
5232 MonoCompile *callee_cfg = g_hash_table_lookup (acfg->method_to_cfg, ji->data.method);
5235 if (acfg->thumb_mixed && !callee_cfg->compile_llvm) {
5236 /* LLVM calls the PLT entries using bl, so emit a stub */
5237 fprintf (acfg->fp, "\n.thumb_func\n");
5238 emit_label (acfg, plt_entry->llvm_symbol);
5239 fprintf (acfg->fp, "bx pc\n");
5240 fprintf (acfg->fp, "nop\n");
5241 fprintf (acfg->fp, ".arm\n");
5242 fprintf (acfg->fp, "b %s\n", callee_cfg->asm_symbol);
5244 fprintf (acfg->fp, "\n.set %s, %s\n", plt_entry->llvm_symbol, callee_cfg->asm_symbol);
5251 debug_sym = plt_entry->debug_sym;
5253 if (acfg->thumb_mixed && !plt_entry->jit_used)
5254 /* Emit only a thumb version */
5257 if (acfg->llvm && !acfg->thumb_mixed)
5258 emit_label (acfg, plt_entry->llvm_symbol);
5261 if (acfg->need_no_dead_strip) {
5262 img_writer_emit_unset_mode (acfg->w);
5263 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5265 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5266 emit_label (acfg, debug_sym);
5269 emit_label (acfg, plt_entry->symbol);
5271 arch_emit_plt_entry (acfg, i);
5274 emit_symbol_size (acfg, debug_sym, ".");
5277 if (acfg->thumb_mixed) {
5278 /* Make sure the ARM symbols don't alias the thumb ones */
5279 emit_zero_bytes (acfg, 16);
5282 * Emit a separate set of PLT entries using thumb2 which is called by LLVM generated
5285 for (i = 0; i < acfg->plt_offset; ++i) {
5286 char *debug_sym = NULL;
5287 MonoPltEntry *plt_entry = NULL;
5293 plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
5296 if (ji && is_direct_callable (acfg, NULL, ji) && !acfg->use_bin_writer)
5299 /* Skip plt entries not actually called by LLVM code */
5300 if (!plt_entry->llvm_used)
5303 if (acfg->aot_opts.write_symbols) {
5304 if (plt_entry->debug_sym)
5305 debug_sym = g_strdup_printf ("%s_thumb", plt_entry->debug_sym);
5309 #if defined(TARGET_MACH)
5310 fprintf (acfg->fp, " .thumb_func %s\n", debug_sym);
5311 fprintf (acfg->fp, " .no_dead_strip %s\n", debug_sym);
5313 emit_local_symbol (acfg, debug_sym, NULL, TRUE);
5314 emit_label (acfg, debug_sym);
5316 fprintf (acfg->fp, "\n.thumb_func\n");
5318 emit_label (acfg, plt_entry->llvm_symbol);
5320 arch_emit_llvm_plt_entry (acfg, i);
5323 emit_symbol_size (acfg, debug_sym, ".");
5329 emit_symbol_size (acfg, acfg->plt_symbol, ".");
5331 sprintf (symbol, "plt_end");
5332 emit_label (acfg, symbol);
5336 * emit_trampoline_full:
5338 * If EMIT_TINFO is TRUE, emit additional information which can be used to create a MonoJitInfo for this trampoline by
5339 * create_jit_info_for_trampoline ().
5341 static G_GNUC_UNUSED void
5342 emit_trampoline_full (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info, gboolean emit_tinfo)
5344 char start_symbol [256];
5345 char end_symbol [256];
5347 guint32 buf_size, info_offset;
5348 MonoJumpInfo *patch_info;
5359 code_size = info->code_size;
5361 unwind_ops = info->unwind_ops;
5363 #ifdef __native_client_codegen__
5364 mono_nacl_fix_patches (code, ji);
5369 sprintf (start_symbol, "%s%s", acfg->user_symbol_prefix, name);
5371 emit_section_change (acfg, ".text", 0);
5372 emit_global (acfg, start_symbol, TRUE);
5373 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5374 emit_label (acfg, start_symbol);
5376 sprintf (symbol, "%snamed_%s", acfg->temp_prefix, name);
5377 emit_label (acfg, symbol);
5380 * The code should access everything through the GOT, so we pass
5383 emit_and_reloc_code (acfg, NULL, code, code_size, ji, TRUE);
5385 emit_symbol_size (acfg, start_symbol, ".");
5388 sprintf (end_symbol, "%snamede_%s", acfg->temp_prefix, name);
5389 emit_label (acfg, end_symbol);
5394 /* Sort relocations */
5395 patches = g_ptr_array_new ();
5396 for (patch_info = ji; patch_info; patch_info = patch_info->next)
5397 if (patch_info->type != MONO_PATCH_INFO_NONE)
5398 g_ptr_array_add (patches, patch_info);
5399 g_ptr_array_sort (patches, compare_patches);
5401 buf_size = patches->len * 128 + 128;
5402 buf = g_malloc (buf_size);
5405 encode_patch_list (acfg, patches, patches->len, got_offset, p, &p);
5406 g_assert (p - buf < buf_size);
5408 sprintf (symbol, "%s%s_p", acfg->user_symbol_prefix, name);
5410 info_offset = add_to_blob (acfg, buf, p - buf);
5412 emit_section_change (acfg, RODATA_SECT, 0);
5413 emit_global (acfg, symbol, FALSE);
5414 emit_label (acfg, symbol);
5416 emit_int32 (acfg, info_offset);
5420 guint32 encoded_len;
5424 * Emit additional information which can be used to reconstruct a partial MonoTrampInfo.
5426 encoded = mono_unwind_ops_encode (info->unwind_ops, &encoded_len);
5427 uw_offset = get_unwind_info_offset (acfg, encoded, encoded_len);
5430 emit_symbol_diff (acfg, end_symbol, start_symbol, 0);
5431 emit_int32 (acfg, uw_offset);
5434 /* Emit debug info */
5438 sprintf (symbol, "%s", name);
5439 sprintf (symbol2, "%snamed_%s", acfg->temp_prefix, name);
5442 mono_dwarf_writer_emit_trampoline (acfg->dwarf, symbol, symbol2, NULL, NULL, code_size, unwind_ops);
5446 static G_GNUC_UNUSED void
5447 emit_trampoline (MonoAotCompile *acfg, int got_offset, MonoTrampInfo *info)
5449 emit_trampoline_full (acfg, got_offset, info, FALSE);
5453 emit_trampolines (MonoAotCompile *acfg)
5456 char end_symbol [256];
5457 int i, tramp_got_offset;
5458 MonoAotTrampoline ntype;
5459 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5463 if (!acfg->aot_opts.full_aot)
5466 g_assert (acfg->image->assembly);
5468 /* Currently, we emit most trampolines into the mscorlib AOT image. */
5469 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
5470 #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
5471 MonoTrampInfo *info;
5474 * Emit the generic trampolines.
5476 * We could save some code by treating the generic trampolines as a wrapper
5477 * method, but that approach has its own complexities, so we choose the simpler
5480 for (tramp_type = 0; tramp_type < MONO_TRAMPOLINE_NUM; ++tramp_type) {
5481 /* we overload the boolean here to indicate the slightly different trampoline needed, see mono_arch_create_generic_trampoline() */
5482 mono_arch_create_generic_trampoline (tramp_type, &info, acfg->aot_opts.use_trampolines_page? 2: TRUE);
5483 emit_trampoline (acfg, acfg->got_offset, info);
5486 mono_arch_get_nullified_class_init_trampoline (&info);
5487 emit_trampoline (acfg, acfg->got_offset, info);
5488 #if defined(MONO_ARCH_MONITOR_OBJECT_REG)
5489 mono_arch_create_monitor_enter_trampoline (&info, TRUE);
5490 emit_trampoline (acfg, acfg->got_offset, info);
5491 mono_arch_create_monitor_exit_trampoline (&info, TRUE);
5492 emit_trampoline (acfg, acfg->got_offset, info);
5495 mono_arch_create_generic_class_init_trampoline (&info, TRUE);
5496 emit_trampoline (acfg, acfg->got_offset, info);
5498 /* Emit the exception related code pieces */
5499 mono_arch_get_restore_context (&info, TRUE);
5500 emit_trampoline (acfg, acfg->got_offset, info);
5501 mono_arch_get_call_filter (&info, TRUE);
5502 emit_trampoline (acfg, acfg->got_offset, info);
5503 mono_arch_get_throw_exception (&info, TRUE);
5504 emit_trampoline (acfg, acfg->got_offset, info);
5505 mono_arch_get_rethrow_exception (&info, TRUE);
5506 emit_trampoline (acfg, acfg->got_offset, info);
5507 mono_arch_get_throw_corlib_exception (&info, TRUE);
5508 emit_trampoline (acfg, acfg->got_offset, info);
5510 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
5511 mono_arch_get_gsharedvt_trampoline (&info, TRUE);
5513 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5515 /* Create a separate out trampoline for more information in stack traces */
5516 info->name = g_strdup ("gsharedvt_out_trampoline");
5517 emit_trampoline_full (acfg, acfg->got_offset, info, TRUE);
5521 #if defined(MONO_ARCH_HAVE_GET_TRAMPOLINES)
5523 GSList *l = mono_arch_get_trampolines (TRUE);
5526 MonoTrampInfo *info = l->data;
5528 emit_trampoline (acfg, acfg->got_offset, info);
5534 for (i = 0; i < acfg->aot_opts.nrgctx_fetch_trampolines; ++i) {
5537 offset = MONO_RGCTX_SLOT_MAKE_RGCTX (i);
5538 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5539 emit_trampoline (acfg, acfg->got_offset, info);
5541 offset = MONO_RGCTX_SLOT_MAKE_MRGCTX (i);
5542 mono_arch_create_rgctx_lazy_fetch_trampoline (offset, &info, TRUE);
5543 emit_trampoline (acfg, acfg->got_offset, info);
5546 #ifdef MONO_ARCH_HAVE_GENERAL_RGCTX_LAZY_FETCH_TRAMPOLINE
5547 mono_arch_create_general_rgctx_lazy_fetch_trampoline (&info, TRUE);
5548 emit_trampoline (acfg, acfg->got_offset, info);
5554 /* delegate_invoke_impl trampolines */
5555 l = mono_arch_get_delegate_invoke_impls ();
5557 MonoTrampInfo *info = l->data;
5559 emit_trampoline (acfg, acfg->got_offset, info);
5564 #endif /* #ifdef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES */
5566 /* Emit trampolines which are numerous */
5569 * These include the following:
5570 * - specific trampolines
5571 * - static rgctx invoke trampolines
5573 * These trampolines have the same code, they are parameterized by GOT
5575 * They are defined in this file, in the arch_... routines instead of
5576 * in tramp-<ARCH>.c, since it is easier to do it this way.
5580 * When running in aot-only mode, we can't create specific trampolines at
5581 * runtime, so we create a few, and save them in the AOT file.
5582 * Normal trampolines embed their argument as a literal inside the
5583 * trampoline code, we can't do that here, so instead we embed an offset
5584 * which needs to be added to the trampoline address to get the address of
5585 * the GOT slot which contains the argument value.
5586 * The generated trampolines jump to the generic trampolines using another
5587 * GOT slot, which will be setup by the AOT loader to point to the
5588 * generic trampoline code of the given type.
5592 * FIXME: Maybe we should use more specific trampolines (i.e. one class init for
5596 emit_section_change (acfg, ".text", 0);
5598 tramp_got_offset = acfg->got_offset;
5600 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype) {
5602 case MONO_AOT_TRAMP_SPECIFIC:
5603 sprintf (symbol, "specific_trampolines");
5605 case MONO_AOT_TRAMP_STATIC_RGCTX:
5606 sprintf (symbol, "static_rgctx_trampolines");
5608 case MONO_AOT_TRAMP_IMT_THUNK:
5609 sprintf (symbol, "imt_thunks");
5611 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
5612 sprintf (symbol, "gsharedvt_arg_trampolines");
5615 g_assert_not_reached ();
5618 sprintf (end_symbol, "%s_e", symbol);
5620 if (acfg->aot_opts.write_symbols)
5621 emit_local_symbol (acfg, symbol, end_symbol, TRUE);
5623 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5624 emit_label (acfg, symbol);
5626 acfg->trampoline_got_offset_base [ntype] = tramp_got_offset;
5628 for (i = 0; i < acfg->num_trampolines [ntype]; ++i) {
5632 case MONO_AOT_TRAMP_SPECIFIC:
5633 arch_emit_specific_trampoline (acfg, tramp_got_offset, &tramp_size);
5634 tramp_got_offset += 2;
5636 case MONO_AOT_TRAMP_STATIC_RGCTX:
5637 arch_emit_static_rgctx_trampoline (acfg, tramp_got_offset, &tramp_size);
5638 tramp_got_offset += 2;
5640 case MONO_AOT_TRAMP_IMT_THUNK:
5641 arch_emit_imt_thunk (acfg, tramp_got_offset, &tramp_size);
5642 tramp_got_offset += 1;
5644 case MONO_AOT_TRAMP_GSHAREDVT_ARG:
5645 arch_emit_gsharedvt_arg_trampoline (acfg, tramp_got_offset, &tramp_size);
5646 tramp_got_offset += 2;
5649 g_assert_not_reached ();
5651 #ifdef __native_client_codegen__
5652 /* align to avoid 32-byte boundary crossings */
5653 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
5656 if (!acfg->trampoline_size [ntype]) {
5657 g_assert (tramp_size);
5658 acfg->trampoline_size [ntype] = tramp_size;
5662 emit_label (acfg, end_symbol);
5665 arch_emit_specific_trampoline_pages (acfg);
5667 /* Reserve some entries at the end of the GOT for our use */
5668 acfg->num_trampoline_got_entries = tramp_got_offset - acfg->got_offset;
5671 acfg->got_offset += acfg->num_trampoline_got_entries;
5675 str_begins_with (const char *str1, const char *str2)
5677 int len = strlen (str2);
5678 return strncmp (str1, str2, len) == 0;
5682 mono_aot_readonly_field_override (MonoClassField *field)
5685 for (rdv = readonly_values; rdv; rdv = rdv->next) {
5686 char *p = rdv->name;
5688 len = strlen (field->parent->name_space);
5689 if (strncmp (p, field->parent->name_space, len))
5694 len = strlen (field->parent->name);
5695 if (strncmp (p, field->parent->name, len))
5700 if (strcmp (p, field->name))
5702 switch (rdv->type) {
5704 return &rdv->value.i1;
5706 return &rdv->value.i2;
5708 return &rdv->value.i4;
5717 add_readonly_value (MonoAotOptions *opts, const char *val)
5722 /* the format of val is:
5723 * namespace.typename.fieldname=type/value
5724 * type can be i1 for uint8/int8/boolean, i2 for uint16/int16/char, i4 for uint32/int32
5726 fval = strrchr (val, '/');
5728 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing /.\n", val);
5731 tval = strrchr (val, '=');
5733 fprintf (stderr, "AOT : invalid format for readonly field '%s', missing =.\n", val);
5736 rdv = g_new0 (ReadOnlyValue, 1);
5737 rdv->name = g_malloc0 (tval - val + 1);
5738 memcpy (rdv->name, val, tval - val);
5741 if (strncmp (tval, "i1", 2) == 0) {
5742 rdv->value.i1 = atoi (fval);
5743 rdv->type = MONO_TYPE_I1;
5744 } else if (strncmp (tval, "i2", 2) == 0) {
5745 rdv->value.i2 = atoi (fval);
5746 rdv->type = MONO_TYPE_I2;
5747 } else if (strncmp (tval, "i4", 2) == 0) {
5748 rdv->value.i4 = atoi (fval);
5749 rdv->type = MONO_TYPE_I4;
5751 fprintf (stderr, "AOT : unsupported type for readonly field '%s'.\n", tval);
5754 rdv->next = readonly_values;
5755 readonly_values = rdv;
5759 mono_aot_parse_options (const char *aot_options, MonoAotOptions *opts)
5761 gchar **args, **ptr;
5763 args = g_strsplit (aot_options ? aot_options : "", ",", -1);
5764 for (ptr = args; ptr && *ptr; ptr ++) {
5765 const char *arg = *ptr;
5767 if (str_begins_with (arg, "outfile=")) {
5768 opts->outfile = g_strdup (arg + strlen ("outfile="));
5769 } else if (str_begins_with (arg, "save-temps")) {
5770 opts->save_temps = TRUE;
5771 } else if (str_begins_with (arg, "keep-temps")) {
5772 opts->save_temps = TRUE;
5773 } else if (str_begins_with (arg, "write-symbols")) {
5774 opts->write_symbols = TRUE;
5775 } else if (str_begins_with (arg, "no-write-symbols")) {
5776 opts->write_symbols = FALSE;
5777 } else if (str_begins_with (arg, "metadata-only")) {
5778 opts->metadata_only = TRUE;
5779 } else if (str_begins_with (arg, "bind-to-runtime-version")) {
5780 opts->bind_to_runtime_version = TRUE;
5781 } else if (str_begins_with (arg, "full")) {
5782 opts->full_aot = TRUE;
5783 } else if (str_begins_with (arg, "threads=")) {
5784 opts->nthreads = atoi (arg + strlen ("threads="));
5785 } else if (str_begins_with (arg, "static")) {
5786 opts->static_link = TRUE;
5787 opts->no_dlsym = TRUE;
5788 } else if (str_begins_with (arg, "asmonly")) {
5789 opts->asm_only = TRUE;
5790 } else if (str_begins_with (arg, "asmwriter")) {
5791 opts->asm_writer = TRUE;
5792 } else if (str_begins_with (arg, "nodebug")) {
5793 opts->nodebug = TRUE;
5794 } else if (str_begins_with (arg, "dwarfdebug")) {
5795 opts->dwarf_debug = TRUE;
5796 } else if (str_begins_with (arg, "nopagetrampolines")) {
5797 opts->use_trampolines_page = FALSE;
5798 } else if (str_begins_with (arg, "ntrampolines=")) {
5799 opts->ntrampolines = atoi (arg + strlen ("ntrampolines="));
5800 } else if (str_begins_with (arg, "nrgctx-trampolines=")) {
5801 opts->nrgctx_trampolines = atoi (arg + strlen ("nrgctx-trampolines="));
5802 } else if (str_begins_with (arg, "nimt-trampolines=")) {
5803 opts->nimt_trampolines = atoi (arg + strlen ("nimt-trampolines="));
5804 } else if (str_begins_with (arg, "ngsharedvt-trampolines=")) {
5805 opts->ngsharedvt_arg_trampolines = atoi (arg + strlen ("ngsharedvt-trampolines="));
5806 } else if (str_begins_with (arg, "autoreg")) {
5807 opts->autoreg = TRUE;
5808 } else if (str_begins_with (arg, "tool-prefix=")) {
5809 opts->tool_prefix = g_strdup (arg + strlen ("tool-prefix="));
5810 } else if (str_begins_with (arg, "soft-debug")) {
5811 opts->soft_debug = TRUE;
5812 } else if (str_begins_with (arg, "direct-pinvoke")) {
5813 opts->direct_pinvoke = TRUE;
5814 } else if (str_begins_with (arg, "direct-icalls")) {
5815 opts->direct_icalls = TRUE;
5816 #if defined(TARGET_ARM)
5817 } else if (str_begins_with (arg, "iphone-abi")) {
5818 // older full-aot users did depend on this.
5820 } else if (str_begins_with (arg, "no-direct-calls")) {
5821 opts->no_direct_calls = TRUE;
5822 } else if (str_begins_with (arg, "print-skipped")) {
5823 opts->print_skipped_methods = TRUE;
5824 } else if (str_begins_with (arg, "stats")) {
5826 } else if (str_begins_with (arg, "no-instances")) {
5827 opts->no_instances = TRUE;
5828 } else if (str_begins_with (arg, "log-generics")) {
5829 opts->log_generics = TRUE;
5830 } else if (str_begins_with (arg, "mtriple=")) {
5831 opts->mtriple = g_strdup (arg + strlen ("mtriple="));
5832 } else if (str_begins_with (arg, "llvm-path=")) {
5833 opts->llvm_path = g_strdup (arg + strlen ("llvm-path="));
5834 } else if (str_begins_with (arg, "readonly-value=")) {
5835 add_readonly_value (opts, arg + strlen ("readonly-value="));
5836 } else if (str_begins_with (arg, "info")) {
5837 printf ("AOT target setup: %s.\n", AOT_TARGET_STR);
5839 } else if (str_begins_with (arg, "gc-maps")) {
5840 mini_gc_enable_gc_maps_for_aot ();
5841 } else if (str_begins_with (arg, "help") || str_begins_with (arg, "?")) {
5842 printf ("Supported options for --aot:\n");
5843 printf (" outfile=\n");
5844 printf (" save-temps\n");
5845 printf (" keep-temps\n");
5846 printf (" write-symbols\n");
5847 printf (" metadata-only\n");
5848 printf (" bind-to-runtime-version\n");
5850 printf (" threads=\n");
5851 printf (" static\n");
5852 printf (" asmonly\n");
5853 printf (" asmwriter\n");
5854 printf (" nodebug\n");
5855 printf (" dwarfdebug\n");
5856 printf (" ntrampolines=\n");
5857 printf (" nrgctx-trampolines=\n");
5858 printf (" nimt-trampolines=\n");
5859 printf (" ngsharedvt-trampolines=\n");
5860 printf (" autoreg\n");
5861 printf (" tool-prefix=\n");
5862 printf (" readonly-value=\n");
5863 printf (" soft-debug\n");
5864 printf (" gc-maps\n");
5865 printf (" print-skipped\n");
5866 printf (" no-instances\n");
5867 printf (" stats\n");
5869 printf (" help/?\n");
5872 fprintf (stderr, "AOT : Unknown argument '%s'.\n", arg);
5877 if (opts->use_trampolines_page) {
5878 opts->ntrampolines = 0;
5879 opts->nrgctx_trampolines = 0;
5880 opts->nimt_trampolines = 0;
5881 opts->ngsharedvt_arg_trampolines = 0;
5887 add_token_info_hash (gpointer key, gpointer value, gpointer user_data)
5889 MonoMethod *method = (MonoMethod*)key;
5890 MonoJumpInfoToken *ji = (MonoJumpInfoToken*)value;
5891 MonoJumpInfoToken *new_ji = g_new0 (MonoJumpInfoToken, 1);
5892 MonoAotCompile *acfg = user_data;
5894 new_ji->image = ji->image;
5895 new_ji->token = ji->token;
5896 g_hash_table_insert (acfg->token_info_hash, method, new_ji);
5900 can_encode_class (MonoAotCompile *acfg, MonoClass *klass)
5902 if (klass->type_token)
5904 if ((klass->byval_arg.type == MONO_TYPE_VAR) || (klass->byval_arg.type == MONO_TYPE_MVAR) || (klass->byval_arg.type == MONO_TYPE_PTR))
5907 return can_encode_class (acfg, klass->element_class);
5912 can_encode_method (MonoAotCompile *acfg, MonoMethod *method)
5914 if (method->wrapper_type) {
5915 switch (method->wrapper_type) {
5916 case MONO_WRAPPER_NONE:
5917 case MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK:
5918 case MONO_WRAPPER_XDOMAIN_INVOKE:
5919 case MONO_WRAPPER_STFLD:
5920 case MONO_WRAPPER_LDFLD:
5921 case MONO_WRAPPER_LDFLDA:
5922 case MONO_WRAPPER_LDFLD_REMOTE:
5923 case MONO_WRAPPER_STFLD_REMOTE:
5924 case MONO_WRAPPER_STELEMREF:
5925 case MONO_WRAPPER_ISINST:
5926 case MONO_WRAPPER_PROXY_ISINST:
5927 case MONO_WRAPPER_ALLOC:
5928 case MONO_WRAPPER_REMOTING_INVOKE:
5929 case MONO_WRAPPER_UNKNOWN:
5930 case MONO_WRAPPER_WRITE_BARRIER:
5931 case MONO_WRAPPER_DELEGATE_INVOKE:
5932 case MONO_WRAPPER_DELEGATE_BEGIN_INVOKE:
5933 case MONO_WRAPPER_DELEGATE_END_INVOKE:
5935 case MONO_WRAPPER_MANAGED_TO_MANAGED:
5936 case MONO_WRAPPER_CASTCLASS: {
5937 WrapperInfo *info = mono_marshal_get_wrapper_info (method);
5946 //printf ("Skip (wrapper call): %d -> %s\n", patch_info->type, mono_method_full_name (patch_info->data.method, TRUE));
5950 if (!method->token) {
5951 /* The method is part of a constructed type like Int[,].Set (). */
5952 if (!g_hash_table_lookup (acfg->token_info_hash, method)) {
5953 if (method->klass->rank)
5963 can_encode_patch (MonoAotCompile *acfg, MonoJumpInfo *patch_info)
5965 switch (patch_info->type) {
5966 case MONO_PATCH_INFO_METHOD:
5967 case MONO_PATCH_INFO_METHODCONST: {
5968 MonoMethod *method = patch_info->data.method;
5970 return can_encode_method (acfg, method);
5972 case MONO_PATCH_INFO_VTABLE:
5973 case MONO_PATCH_INFO_CLASS_INIT:
5974 case MONO_PATCH_INFO_DELEGATE_TRAMPOLINE:
5975 case MONO_PATCH_INFO_CLASS:
5976 case MONO_PATCH_INFO_IID:
5977 case MONO_PATCH_INFO_ADJUSTED_IID:
5978 if (!can_encode_class (acfg, patch_info->data.klass)) {
5979 //printf ("Skip: %s\n", mono_type_full_name (&patch_info->data.klass->byval_arg));
5983 case MONO_PATCH_INFO_RGCTX_FETCH: {
5984 MonoJumpInfoRgctxEntry *entry = patch_info->data.rgctx_entry;
5986 if (!can_encode_method (acfg, entry->method))
5988 if (!can_encode_patch (acfg, entry->data))
6002 * AOT compile a given method.
6003 * This function might be called by multiple threads, so it must be thread-safe.
6006 compile_method (MonoAotCompile *acfg, MonoMethod *method)
6009 MonoJumpInfo *patch_info;
6012 MonoMethod *wrapped;
6014 if (acfg->aot_opts.metadata_only)
6017 mono_acfg_lock (acfg);
6018 index = get_method_index (acfg, method);
6019 mono_acfg_unlock (acfg);
6021 /* fixme: maybe we can also precompile wrapper methods */
6022 if ((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
6023 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
6024 (method->flags & METHOD_ATTRIBUTE_ABSTRACT)) {
6025 //printf ("Skip (impossible): %s\n", mono_method_full_name (method, TRUE));
6029 if (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL)
6032 wrapped = mono_marshal_method_from_wrapper (method);
6033 if (wrapped && (wrapped->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) && wrapped->is_generic)
6034 // FIXME: The wrapper should be generic too, but it is not
6037 if (method->wrapper_type == MONO_WRAPPER_COMINTEROP)
6040 InterlockedIncrement (&acfg->stats.mcount);
6043 if (method->is_generic || method->klass->generic_container) {
6044 InterlockedIncrement (&acfg->stats.genericcount);
6049 //acfg->aot_opts.print_skipped_methods = TRUE;
6052 * Since these methods are the only ones which are compiled with
6053 * AOT support, and they are not used by runtime startup/shutdown code,
6054 * the runtime will not see AOT methods during AOT compilation,so it
6055 * does not need to support them by creating a fake GOT etc.
6057 cfg = mini_method_compile (method, acfg->opts, mono_get_root_domain (), FALSE, TRUE, 0);
6058 if (cfg->exception_type == MONO_EXCEPTION_GENERIC_SHARING_FAILED) {
6059 if (acfg->aot_opts.print_skipped_methods)
6060 printf ("Skip (gshared failure): %s (%s)\n", mono_method_full_name (method, TRUE), cfg->exception_message);
6061 InterlockedIncrement (&acfg->stats.genericcount);
6064 if (cfg->exception_type != MONO_EXCEPTION_NONE) {
6065 if (acfg->aot_opts.print_skipped_methods)
6066 printf ("Skip (JIT failure): %s\n", mono_method_full_name (method, TRUE));
6067 /* Let the exception happen at runtime */
6071 if (cfg->disable_aot) {
6072 if (acfg->aot_opts.print_skipped_methods)
6073 printf ("Skip (disabled): %s\n", mono_method_full_name (method, TRUE));
6074 InterlockedIncrement (&acfg->stats.ocount);
6075 mono_destroy_compile (cfg);
6079 /* Nullify patches which need no aot processing */
6080 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6081 switch (patch_info->type) {
6082 case MONO_PATCH_INFO_LABEL:
6083 case MONO_PATCH_INFO_BB:
6084 patch_info->type = MONO_PATCH_INFO_NONE;
6091 /* Collect method->token associations from the cfg */
6092 mono_acfg_lock (acfg);
6093 g_hash_table_foreach (cfg->token_info_hash, add_token_info_hash, acfg);
6094 mono_acfg_unlock (acfg);
6097 * Check for absolute addresses.
6100 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6101 switch (patch_info->type) {
6102 case MONO_PATCH_INFO_ABS:
6103 /* unable to handle this */
6112 if (acfg->aot_opts.print_skipped_methods)
6113 printf ("Skip (abs call): %s\n", mono_method_full_name (method, TRUE));
6114 InterlockedIncrement (&acfg->stats.abscount);
6115 mono_destroy_compile (cfg);
6119 /* Lock for the rest of the code */
6120 mono_acfg_lock (acfg);
6123 * Check for methods/klasses we can't encode.
6126 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6127 if (!can_encode_patch (acfg, patch_info))
6132 if (acfg->aot_opts.print_skipped_methods)
6133 printf ("Skip (patches): %s\n", mono_method_full_name (method, TRUE));
6134 acfg->stats.ocount++;
6135 mono_destroy_compile (cfg);
6136 mono_acfg_unlock (acfg);
6140 /* Adds generic instances referenced by this method */
6142 * The depth is used to avoid infinite loops when generic virtual recursion is
6145 depth = GPOINTER_TO_UINT (g_hash_table_lookup (acfg->method_depth, method));
6146 if (!acfg->aot_opts.no_instances && depth < 32) {
6147 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6148 switch (patch_info->type) {
6149 case MONO_PATCH_INFO_METHOD: {
6150 MonoMethod *m = patch_info->data.method;
6151 if (m->is_inflated) {
6152 if (!(mono_class_generic_sharing_enabled (m->klass) &&
6153 mono_method_is_generic_sharable_full (m, FALSE, FALSE, FALSE)) &&
6154 !method_has_type_vars (m)) {
6155 if (m->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
6156 if (acfg->aot_opts.full_aot)
6157 add_extra_method_with_depth (acfg, mono_marshal_get_native_wrapper (m, TRUE, TRUE), depth + 1);
6159 add_extra_method_with_depth (acfg, m, depth + 1);
6160 add_types_from_method_header (acfg, m);
6163 add_generic_class_with_depth (acfg, m->klass, depth + 5, "method");
6165 if (m->wrapper_type == MONO_WRAPPER_MANAGED_TO_MANAGED && !strcmp (m->name, "ElementAddr"))
6166 add_extra_method_with_depth (acfg, m, depth + 1);
6169 case MONO_PATCH_INFO_VTABLE: {
6170 MonoClass *klass = patch_info->data.klass;
6172 if (klass->generic_class && !mini_class_is_generic_sharable (klass))
6173 add_generic_class_with_depth (acfg, klass, depth + 5, "vtable");
6176 case MONO_PATCH_INFO_SFLDA: {
6177 MonoClass *klass = patch_info->data.field->parent;
6179 /* The .cctor needs to run at runtime. */
6180 if (klass->generic_class && !mono_generic_context_is_sharable (&klass->generic_class->context, FALSE) && mono_class_get_cctor (klass))
6181 add_extra_method_with_depth (acfg, mono_class_get_cctor (klass), depth + 1);
6190 /* Determine whenever the method has GOT slots */
6191 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6192 switch (patch_info->type) {
6193 case MONO_PATCH_INFO_GOT_OFFSET:
6194 case MONO_PATCH_INFO_NONE:
6195 case MONO_PATCH_INFO_GC_CARD_TABLE_ADDR:
6197 case MONO_PATCH_INFO_IMAGE:
6198 /* The assembly is stored in GOT slot 0 */
6199 if (patch_info->data.image != acfg->image)
6200 cfg->has_got_slots = TRUE;
6203 if (!is_plt_patch (patch_info))
6204 cfg->has_got_slots = TRUE;
6209 if (!cfg->has_got_slots)
6210 InterlockedIncrement (&acfg->stats.methods_without_got_slots);
6213 * FIXME: Instead of this mess, allocate the patches from the aot mempool.
6215 /* Make a copy of the patch info which is in the mempool */
6217 MonoJumpInfo *patches = NULL, *patches_end = NULL;
6219 for (patch_info = cfg->patch_info; patch_info; patch_info = patch_info->next) {
6220 MonoJumpInfo *new_patch_info = mono_patch_info_dup_mp (acfg->mempool, patch_info);
6223 patches = new_patch_info;
6225 patches_end->next = new_patch_info;
6226 patches_end = new_patch_info;
6228 cfg->patch_info = patches;
6230 /* Make a copy of the unwind info */
6232 GSList *l, *unwind_ops;
6236 for (l = cfg->unwind_ops; l; l = l->next) {
6237 op = mono_mempool_alloc (acfg->mempool, sizeof (MonoUnwindOp));
6238 memcpy (op, l->data, sizeof (MonoUnwindOp));
6239 unwind_ops = g_slist_prepend_mempool (acfg->mempool, unwind_ops, op);
6241 cfg->unwind_ops = g_slist_reverse (unwind_ops);
6243 /* Make a copy of the argument/local info */
6245 MonoInst **args, **locals;
6246 MonoMethodSignature *sig;
6247 MonoMethodHeader *header;
6250 sig = mono_method_signature (method);
6251 args = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * (sig->param_count + sig->hasthis));
6252 for (i = 0; i < sig->param_count + sig->hasthis; ++i) {
6253 args [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6254 memcpy (args [i], cfg->args [i], sizeof (MonoInst));
6258 header = mono_method_get_header (method);
6259 locals = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst*) * header->num_locals);
6260 for (i = 0; i < header->num_locals; ++i) {
6261 locals [i] = mono_mempool_alloc (acfg->mempool, sizeof (MonoInst));
6262 memcpy (locals [i], cfg->locals [i], sizeof (MonoInst));
6264 cfg->locals = locals;
6267 /* Free some fields used by cfg to conserve memory */
6268 mono_mempool_destroy (cfg->mempool);
6269 cfg->mempool = NULL;
6270 g_free (cfg->varinfo);
6271 cfg->varinfo = NULL;
6275 mono_regstate_free (cfg->rs);
6279 //printf ("Compile: %s\n", mono_method_full_name (method, TRUE));
6281 while (index >= acfg->cfgs_size) {
6282 MonoCompile **new_cfgs;
6285 new_size = acfg->cfgs_size * 2;
6286 new_cfgs = g_new0 (MonoCompile*, new_size);
6287 memcpy (new_cfgs, acfg->cfgs, sizeof (MonoCompile*) * acfg->cfgs_size);
6288 g_free (acfg->cfgs);
6289 acfg->cfgs = new_cfgs;
6290 acfg->cfgs_size = new_size;
6292 acfg->cfgs [index] = cfg;
6294 g_hash_table_insert (acfg->method_to_cfg, cfg->orig_method, cfg);
6297 if (cfg->orig_method->wrapper_type)
6298 g_ptr_array_add (acfg->extra_methods, cfg->orig_method);
6301 mono_acfg_unlock (acfg);
6303 InterlockedIncrement (&acfg->stats.ccount);
6307 compile_thread_main (gpointer *user_data)
6309 MonoDomain *domain = user_data [0];
6310 MonoAotCompile *acfg = user_data [1];
6311 GPtrArray *methods = user_data [2];
6314 mono_thread_attach (domain);
6316 for (i = 0; i < methods->len; ++i)
6317 compile_method (acfg, g_ptr_array_index (methods, i));
6321 load_profile_files (MonoAotCompile *acfg)
6325 int file_index, res, method_index, i;
6328 GList *unordered, *l;
6333 tmp = g_strdup_printf ("%s/.mono/aot-profile-data/%s-%d", g_get_home_dir (), acfg->image->assembly_name, file_index);
6335 if (!g_file_test (tmp, G_FILE_TEST_IS_REGULAR)) {
6340 infile = fopen (tmp, "r");
6343 printf ("Using profile data file '%s'\n", tmp);
6348 res = fscanf (infile, "%32s\n", ver);
6349 if ((res != 1) || strcmp (ver, "#VER:2") != 0) {
6350 printf ("Profile file has wrong version or invalid.\n");
6357 MonoMethodDesc *desc;
6360 if (fgets (name, 1023, infile) == NULL)
6363 /* Kill the newline */
6364 if (strlen (name) > 0)
6365 name [strlen (name) - 1] = '\0';
6367 desc = mono_method_desc_new (name, TRUE);
6369 method = mono_method_desc_search_in_image (desc, acfg->image);
6371 if (method && mono_method_get_token (method)) {
6372 token = mono_method_get_token (method);
6373 method_index = mono_metadata_token_index (token) - 1;
6376 for (i = 0; i < acfg->method_order->len; ++i) {
6377 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6383 g_ptr_array_add (acfg->method_order, GUINT_TO_POINTER (method_index));
6385 //printf ("No method found matching '%s'.\n", name);
6391 /* Add missing methods */
6393 for (method_index = 0; method_index < acfg->image->tables [MONO_TABLE_METHOD].rows; ++method_index) {
6395 for (i = 0; i < acfg->method_order->len; ++i) {
6396 if (g_ptr_array_index (acfg->method_order, i) == GUINT_TO_POINTER (method_index)) {
6402 unordered = g_list_prepend (unordered, GUINT_TO_POINTER (method_index));
6404 unordered = g_list_reverse (unordered);
6405 for (l = unordered; l; l = l->next)
6406 g_ptr_array_add (acfg->method_order, l->data);
6409 /* Used by the LLVM backend */
6411 mono_aot_get_got_offset (MonoJumpInfo *ji)
6413 return get_got_offset (llvm_acfg, ji);
6417 mono_aot_get_method_name (MonoCompile *cfg)
6419 if (llvm_acfg->aot_opts.static_link)
6420 /* Include the assembly name too to avoid duplicate symbol errors */
6421 return g_strdup_printf ("%s_%s", llvm_acfg->assembly_name_sym, get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash));
6423 return get_debug_sym (cfg->orig_method, "", llvm_acfg->method_label_hash);
6427 mono_aot_get_plt_symbol (MonoJumpInfoType type, gconstpointer data)
6429 MonoJumpInfo *ji = mono_mempool_alloc (llvm_acfg->mempool, sizeof (MonoJumpInfo));
6430 MonoPltEntry *plt_entry;
6433 ji->data.target = data;
6435 if (!can_encode_patch (llvm_acfg, ji))
6438 plt_entry = get_plt_entry (llvm_acfg, ji);
6439 plt_entry->llvm_used = TRUE;
6441 #if defined(TARGET_MACH)
6442 return g_strdup_printf (plt_entry->llvm_symbol + strlen (llvm_acfg->llvm_label_prefix));
6444 return g_strdup_printf (plt_entry->llvm_symbol);
6449 mono_aot_patch_info_dup (MonoJumpInfo* ji)
6453 mono_acfg_lock (llvm_acfg);
6454 res = mono_patch_info_dup_mp (llvm_acfg->mempool, ji);
6455 mono_acfg_unlock (llvm_acfg);
6465 * Emit the LLVM code into an LLVM bytecode file, and compile it using the LLVM
6469 emit_llvm_file (MonoAotCompile *acfg)
6471 char *command, *opts, *tempbc;
6473 MonoJumpInfo *patch_info;
6476 * When using LLVM, we let llvm emit the got since the LLVM IL needs to refer
6480 /* Compute the final size of the got */
6481 for (i = 0; i < acfg->nmethods; ++i) {
6482 if (acfg->cfgs [i]) {
6483 for (patch_info = acfg->cfgs [i]->patch_info; patch_info; patch_info = patch_info->next) {
6484 if (patch_info->type != MONO_PATCH_INFO_NONE) {
6485 if (!is_plt_patch (patch_info))
6486 get_got_offset (acfg, patch_info);
6488 get_plt_entry (acfg, patch_info);
6494 acfg->final_got_size = acfg->got_offset + acfg->plt_offset;
6496 if (acfg->aot_opts.full_aot) {
6500 * Need to add the got entries used by the trampolines.
6501 * This is only a conservative approximation.
6503 if (strcmp (acfg->image->assembly->aname.name, "mscorlib") == 0) {
6504 /* For the generic + rgctx trampolines */
6505 acfg->final_got_size += 400;
6506 /* For the specific trampolines */
6507 for (ntype = 0; ntype < MONO_AOT_TRAMP_NUM; ++ntype)
6508 acfg->final_got_size += acfg->num_trampolines [ntype] * 2;
6513 tempbc = g_strdup_printf ("%s.bc", acfg->tmpfname);
6514 mono_llvm_emit_aot_module (tempbc, acfg->final_got_size);
6518 * FIXME: Experiment with adding optimizations, the -std-compile-opts set takes
6519 * a lot of time, and doesn't seem to save much space.
6520 * The following optimizations cannot be enabled:
6522 * - 'jump-threading' changes our blockaddress references to int constants.
6523 * - 'basiccg' fails because it contains:
6524 * if (CS && !isa<IntrinsicInst>(II)) {
6525 * and isa<IntrinsicInst> is false for invokes to intrinsics (iltests.exe).
6526 * - 'prune-eh' and 'functionattrs' depend on 'basiccg'.
6527 * The opt list below was produced by taking the output of:
6528 * llvm-as < /dev/null | opt -O2 -disable-output -debug-pass=Arguments
6529 * then removing tailcallelim + the global opts, and adding a second gvn.
6531 opts = g_strdup ("-instcombine -simplifycfg");
6532 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");
6534 command = g_strdup_printf ("%sopt -f %s -o %s.opt.bc %s.bc", acfg->aot_opts.llvm_path, opts, acfg->tmpfname, acfg->tmpfname);
6535 printf ("Executing opt: %s\n", command);
6536 if (system (command) != 0) {
6542 if (!acfg->llc_args)
6543 acfg->llc_args = g_string_new ("");
6545 /* Verbose asm slows down llc greatly */
6546 g_string_append (acfg->llc_args, " -asm-verbose=false");
6548 if (acfg->aot_opts.mtriple)
6549 g_string_append_printf (acfg->llc_args, " -mtriple=%s", acfg->aot_opts.mtriple);
6551 if (llvm_acfg->aot_opts.static_link)
6552 g_string_append_printf (acfg->llc_args, " -relocation-model=static");
6554 g_string_append_printf (acfg->llc_args, " -relocation-model=pic");
6555 unlink (acfg->tmpfname);
6557 command = g_strdup_printf ("%sllc %s -disable-gnu-eh-frame -enable-mono-eh-frame -o %s %s.opt.bc", acfg->aot_opts.llvm_path, acfg->llc_args->str, acfg->tmpfname, acfg->tmpfname);
6559 printf ("Executing llc: %s\n", command);
6561 if (system (command) != 0) {
6568 emit_code (MonoAotCompile *acfg)
6570 int oindex, i, prev_index;
6572 char end_symbol [256];
6574 #if defined(TARGET_POWERPC64)
6575 sprintf (symbol, ".Lgot_addr");
6576 emit_section_change (acfg, ".text", 0);
6577 emit_alignment (acfg, 8);
6578 emit_label (acfg, symbol);
6579 emit_pointer (acfg, acfg->got_symbol);
6583 * This global symbol is used to compute the address of each method using the
6584 * code_offsets array. It is also used to compute the memory ranges occupied by
6585 * AOT code, so it must be equal to the address of the first emitted method.
6587 sprintf (symbol, "methods");
6588 emit_section_change (acfg, ".text", 0);
6589 emit_alignment (acfg, 8);
6591 for (i = 0; i < acfg->nmethods; ++i) {
6592 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm) {
6593 fprintf (acfg->fp, "\n.set methods, %s\n", acfg->cfgs [i]->asm_symbol);
6597 if (i == acfg->nmethods)
6598 /* No LLVM compiled methods */
6599 emit_label (acfg, symbol);
6601 emit_label (acfg, symbol);
6605 * Emit some padding so the local symbol for the first method doesn't have the
6606 * same address as 'methods'.
6608 #if defined(__default_codegen__)
6609 emit_zero_bytes (acfg, 16);
6610 #elif defined(__native_client_codegen__)
6612 const int kPaddingSize = 16;
6613 guint8 pad_buffer[kPaddingSize];
6614 mono_arch_nacl_pad (pad_buffer, kPaddingSize);
6615 emit_bytes (acfg, pad_buffer, kPaddingSize);
6619 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6623 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6625 cfg = acfg->cfgs [i];
6630 method = cfg->orig_method;
6632 /* Emit unbox trampoline */
6633 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
6634 sprintf (symbol, "ut_%d", get_method_index (acfg, method));
6636 emit_section_change (acfg, ".text", 0);
6637 #ifdef __native_client_codegen__
6638 emit_alignment (acfg, AOT_FUNC_ALIGNMENT);
6641 if (acfg->thumb_mixed && cfg->compile_llvm)
6642 fprintf (acfg->fp, "\n.thumb_func\n");
6644 emit_label (acfg, symbol);
6646 arch_emit_unbox_trampoline (acfg, cfg, cfg->orig_method, cfg->asm_symbol);
6649 if (cfg->compile_llvm)
6650 acfg->stats.llvm_count ++;
6652 emit_method_code (acfg, cfg);
6655 sprintf (symbol, "methods_end");
6656 emit_section_change (acfg, ".text", 0);
6657 emit_alignment (acfg, 8);
6658 emit_label (acfg, symbol);
6659 /* To distinguish it from the next symbol */
6660 emit_int32 (acfg, 0);
6663 * Add .no_dead_strip directives for all LLVM methods to prevent the OSX linker
6664 * from optimizing them away, since it doesn't see that code_offsets references them.
6665 * JITted methods don't need this since they are referenced using assembler local
6667 * FIXME: This is why write-symbols doesn't work on OSX ?
6669 if (acfg->llvm && acfg->need_no_dead_strip) {
6670 fprintf (acfg->fp, "\n");
6671 for (i = 0; i < acfg->nmethods; ++i) {
6672 if (acfg->cfgs [i] && acfg->cfgs [i]->compile_llvm)
6673 fprintf (acfg->fp, ".no_dead_strip %s\n", acfg->cfgs [i]->asm_symbol);
6678 if (acfg->direct_method_addresses) {
6679 acfg->flags |= MONO_AOT_FILE_FLAG_DIRECT_METHOD_ADDRESSES;
6682 * To work around linker issues, we emit a table of branches, and disassemble them at runtime.
6683 * This is PIE code, and the linker can update it if needed.
6685 sprintf (symbol, "method_addresses");
6686 emit_section_change (acfg, RODATA_SECT, 1);
6687 emit_alignment (acfg, 8);
6688 emit_label (acfg, symbol);
6689 emit_local_symbol (acfg, symbol, "method_addresses_end", TRUE);
6690 img_writer_emit_unset_mode (acfg->w);
6691 if (acfg->need_no_dead_strip)
6692 fprintf (acfg->fp, " .no_dead_strip %s\n", symbol);
6694 for (i = 0; i < acfg->nmethods; ++i) {
6695 if (acfg->cfgs [i]) {
6696 if (acfg->thumb_mixed && acfg->cfgs [i]->compile_llvm)
6697 fprintf (acfg->fp, "\tblx %s\n", acfg->cfgs [i]->asm_symbol);
6699 fprintf (acfg->fp, "\tbl %s\n", acfg->cfgs [i]->asm_symbol);
6701 fprintf (acfg->fp, "\tbl method_addresses\n");
6705 sprintf (symbol, "method_addresses_end");
6706 emit_label (acfg, symbol);
6709 sprintf (symbol, "code_offsets");
6710 emit_section_change (acfg, RODATA_SECT, 1);
6711 emit_alignment (acfg, 8);
6712 emit_label (acfg, symbol);
6713 emit_int32 (acfg, 0);
6715 sprintf (symbol, "code_offsets");
6716 emit_section_change (acfg, RODATA_SECT, 1);
6717 emit_alignment (acfg, 8);
6718 emit_label (acfg, symbol);
6720 acfg->stats.offsets_size += acfg->nmethods * 4;
6722 sprintf (end_symbol, "methods");
6723 for (i = 0; i < acfg->nmethods; ++i) {
6724 if (acfg->cfgs [i]) {
6725 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
6727 emit_int32 (acfg, 0xffffffff);
6732 sprintf (symbol, "code_offsets");
6733 emit_section_change (acfg, RODATA_SECT, 1);
6734 emit_alignment (acfg, 8);
6735 emit_label (acfg, symbol);
6737 acfg->stats.offsets_size += acfg->nmethods * 4;
6739 sprintf (end_symbol, "methods");
6740 for (i = 0; i < acfg->nmethods; ++i) {
6741 if (acfg->cfgs [i]) {
6742 emit_symbol_diff (acfg, acfg->cfgs [i]->asm_symbol, end_symbol, 0);
6744 emit_int32 (acfg, 0xffffffff);
6750 /* Emit a sorted table mapping methods to their unbox trampolines */
6751 sprintf (symbol, "unbox_trampolines");
6752 emit_section_change (acfg, RODATA_SECT, 1);
6753 emit_alignment (acfg, 8);
6754 emit_label (acfg, symbol);
6756 sprintf (end_symbol, "methods");
6758 for (i = 0; i < acfg->nmethods; ++i) {
6763 cfg = acfg->cfgs [i];
6767 method = cfg->orig_method;
6769 if (acfg->aot_opts.full_aot && cfg->orig_method->klass->valuetype) {
6770 index = get_method_index (acfg, method);
6771 sprintf (symbol, "ut_%d", index);
6773 emit_int32 (acfg, index);
6774 if (acfg->direct_method_addresses) {
6775 img_writer_emit_unset_mode (acfg->w);
6776 if (acfg->thumb_mixed && cfg->compile_llvm)
6777 fprintf (acfg->fp, "\n\tblx %s\n", symbol);
6779 fprintf (acfg->fp, "\n\tbl %s\n", symbol);
6781 emit_symbol_diff (acfg, symbol, end_symbol, 0);
6783 /* Make sure the table is sorted by index */
6784 g_assert (index > prev_index);
6788 sprintf (symbol, "unbox_trampolines_end");
6789 emit_label (acfg, symbol);
6793 emit_info (MonoAotCompile *acfg)
6799 offsets = g_new0 (gint32, acfg->nmethods);
6801 for (oindex = 0; oindex < acfg->method_order->len; ++oindex) {
6802 i = GPOINTER_TO_UINT (g_ptr_array_index (acfg->method_order, oindex));
6804 if (acfg->cfgs [i]) {
6805 emit_method_info (acfg, acfg->cfgs [i]);
6806 offsets [i] = acfg->cfgs [i]->method_info_offset;
6812 sprintf (symbol, "method_info_offsets");
6813 emit_section_change (acfg, RODATA_SECT, 1);
6814 emit_alignment (acfg, 8);
6815 emit_label (acfg, symbol);
6817 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
6822 #endif /* #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT) */
6824 #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k))))
6825 #define mix(a,b,c) { \
6826 a -= c; a ^= rot(c, 4); c += b; \
6827 b -= a; b ^= rot(a, 6); a += c; \
6828 c -= b; c ^= rot(b, 8); b += a; \
6829 a -= c; a ^= rot(c,16); c += b; \
6830 b -= a; b ^= rot(a,19); a += c; \
6831 c -= b; c ^= rot(b, 4); b += a; \
6833 #define final(a,b,c) { \
6834 c ^= b; c -= rot(b,14); \
6835 a ^= c; a -= rot(c,11); \
6836 b ^= a; b -= rot(a,25); \
6837 c ^= b; c -= rot(b,16); \
6838 a ^= c; a -= rot(c,4); \
6839 b ^= a; b -= rot(a,14); \
6840 c ^= b; c -= rot(b,24); \
6844 mono_aot_type_hash (MonoType *t1)
6846 guint hash = t1->type;
6848 hash |= t1->byref << 6; /* do not collide with t1->type values */
6850 case MONO_TYPE_VALUETYPE:
6851 case MONO_TYPE_CLASS:
6852 case MONO_TYPE_SZARRAY:
6853 /* check if the distribution is good enough */
6854 return ((hash << 5) - hash) ^ mono_metadata_str_hash (t1->data.klass->name);
6856 return ((hash << 5) - hash) ^ mono_metadata_type_hash (t1->data.type);
6857 case MONO_TYPE_ARRAY:
6858 return ((hash << 5) - hash) ^ mono_metadata_type_hash (&t1->data.array->eklass->byval_arg);
6859 case MONO_TYPE_GENERICINST:
6860 return ((hash << 5) - hash) ^ 0;
6867 * mono_aot_method_hash:
6869 * Return a hash code for methods which only depends on metadata.
6872 mono_aot_method_hash (MonoMethod *method)
6874 MonoMethodSignature *sig;
6878 guint32 *hashes_start, *hashes;
6880 MonoGenericInst *ginst = NULL;
6882 /* Similar to the hash in mono_method_get_imt_slot () */
6884 sig = mono_method_signature (method);
6886 if (method->is_inflated)
6887 ginst = ((MonoMethodInflated*)method)->context.method_inst;
6889 hashes_count = sig->param_count + 5 + (ginst ? ginst->type_argc : 0);
6890 hashes_start = g_malloc0 (hashes_count * sizeof (guint32));
6891 hashes = hashes_start;
6893 /* Some wrappers are assigned to random classes */
6894 if (!method->wrapper_type || method->wrapper_type == MONO_WRAPPER_REMOTING_INVOKE_WITH_CHECK)
6895 klass = method->klass;
6897 klass = mono_defaults.object_class;
6899 if (!method->wrapper_type) {
6900 char *full_name = mono_type_full_name (&klass->byval_arg);
6902 hashes [0] = mono_metadata_str_hash (full_name);
6906 hashes [0] = mono_metadata_str_hash (klass->name);
6907 hashes [1] = mono_metadata_str_hash (klass->name_space);
6909 if (method->wrapper_type == MONO_WRAPPER_STFLD || method->wrapper_type == MONO_WRAPPER_LDFLD || method->wrapper_type == MONO_WRAPPER_LDFLDA)
6910 /* The method name includes a stringified pointer */
6913 hashes [2] = mono_metadata_str_hash (method->name);
6914 hashes [3] = method->wrapper_type;
6915 hashes [4] = mono_aot_type_hash (sig->ret);
6917 for (i = 0; i < sig->param_count; i++) {
6918 hashes [hindex ++] = mono_aot_type_hash (sig->params [i]);
6921 for (i = 0; i < ginst->type_argc; ++i)
6922 hashes [hindex ++] = mono_aot_type_hash (ginst->type_argv [i]);
6924 g_assert (hindex == hashes_count);
6926 /* Setup internal state */
6927 a = b = c = 0xdeadbeef + (((guint32)hashes_count)<<2);
6929 /* Handle most of the hashes */
6930 while (hashes_count > 3) {
6939 /* Handle the last 3 hashes (all the case statements fall through) */
6940 switch (hashes_count) {
6941 case 3 : c += hashes [2];
6942 case 2 : b += hashes [1];
6943 case 1 : a += hashes [0];
6945 case 0: /* nothing left to add */
6949 free (hashes_start);
6958 * mono_aot_get_array_helper_from_wrapper;
6960 * Get the helper method in Array called by an array wrapper method.
6963 mono_aot_get_array_helper_from_wrapper (MonoMethod *method)
6967 MonoGenericContext ctx;
6968 MonoType *args [16];
6969 char *mname, *iname, *s, *s2, *helper_name = NULL;
6971 prefix = "System.Collections.Generic";
6972 s = g_strdup_printf ("%s", method->name + strlen (prefix) + 1);
6973 s2 = strstr (s, "`1.");
6979 //printf ("X: %s %s\n", iname, mname);
6981 if (!strcmp (iname, "IList"))
6982 helper_name = g_strdup_printf ("InternalArray__%s", mname);
6984 helper_name = g_strdup_printf ("InternalArray__%s_%s", iname, mname);
6985 m = mono_class_get_method_from_name (mono_defaults.array_class, helper_name, mono_method_signature (method)->param_count);
6987 g_free (helper_name);
6990 if (m->is_generic) {
6991 memset (&ctx, 0, sizeof (ctx));
6992 args [0] = &method->klass->element_class->byval_arg;
6993 ctx.method_inst = mono_metadata_get_generic_inst (1, args);
6994 m = mono_class_inflate_generic_method (m, &ctx);
7000 #if !defined(DISABLE_AOT) && !defined(DISABLE_JIT)
7002 typedef struct HashEntry {
7003 guint32 key, value, index;
7004 struct HashEntry *next;
7008 * emit_extra_methods:
7010 * Emit methods which are not in the METHOD table, like wrappers.
7013 emit_extra_methods (MonoAotCompile *acfg)
7015 int i, table_size, buf_size;
7018 guint32 *info_offsets;
7021 HashEntry *entry, *new_entry;
7022 int nmethods, max_chain_length;
7025 info_offsets = g_new0 (guint32, acfg->extra_methods->len);
7027 /* Emit method info */
7029 for (i = 0; i < acfg->extra_methods->len; ++i) {
7030 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7031 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7037 p = buf = g_malloc (buf_size);
7041 method = cfg->method_to_register;
7043 encode_method_ref (acfg, method, p, &p);
7045 g_assert ((p - buf) < buf_size);
7047 info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7052 * Construct a chained hash table for mapping indexes in extra_method_info to
7055 table_size = g_spaced_primes_closest ((int)(nmethods * 1.5));
7056 table = g_ptr_array_sized_new (table_size);
7057 for (i = 0; i < table_size; ++i)
7058 g_ptr_array_add (table, NULL);
7059 chain_lengths = g_new0 (int, table_size);
7060 max_chain_length = 0;
7061 for (i = 0; i < acfg->extra_methods->len; ++i) {
7062 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7063 MonoCompile *cfg = g_hash_table_lookup (acfg->method_to_cfg, method);
7069 key = info_offsets [i];
7070 value = get_method_index (acfg, method);
7072 hash = mono_aot_method_hash (method) % table_size;
7074 chain_lengths [hash] ++;
7075 max_chain_length = MAX (max_chain_length, chain_lengths [hash]);
7077 new_entry = mono_mempool_alloc0 (acfg->mempool, sizeof (HashEntry));
7078 new_entry->key = key;
7079 new_entry->value = value;
7081 entry = g_ptr_array_index (table, hash);
7082 if (entry == NULL) {
7083 new_entry->index = hash;
7084 g_ptr_array_index (table, hash) = new_entry;
7087 entry = entry->next;
7089 entry->next = new_entry;
7090 new_entry->index = table->len;
7091 g_ptr_array_add (table, new_entry);
7095 //printf ("MAX: %d\n", max_chain_length);
7097 /* Emit the table */
7098 sprintf (symbol, "extra_method_table");
7099 emit_section_change (acfg, RODATA_SECT, 0);
7100 emit_alignment (acfg, 8);
7101 emit_label (acfg, symbol);
7103 emit_int32 (acfg, table_size);
7104 for (i = 0; i < table->len; ++i) {
7105 HashEntry *entry = g_ptr_array_index (table, i);
7107 if (entry == NULL) {
7108 emit_int32 (acfg, 0);
7109 emit_int32 (acfg, 0);
7110 emit_int32 (acfg, 0);
7112 //g_assert (entry->key > 0);
7113 emit_int32 (acfg, entry->key);
7114 emit_int32 (acfg, entry->value);
7116 emit_int32 (acfg, entry->next->index);
7118 emit_int32 (acfg, 0);
7123 * Emit a table reverse mapping method indexes to their index in extra_method_info.
7124 * This is used by mono_aot_find_jit_info ().
7126 sprintf (symbol, "extra_method_info_offsets");
7127 emit_section_change (acfg, RODATA_SECT, 0);
7128 emit_alignment (acfg, 8);
7129 emit_label (acfg, symbol);
7131 emit_int32 (acfg, acfg->extra_methods->len);
7132 for (i = 0; i < acfg->extra_methods->len; ++i) {
7133 MonoMethod *method = g_ptr_array_index (acfg->extra_methods, i);
7135 emit_int32 (acfg, get_method_index (acfg, method));
7136 emit_int32 (acfg, info_offsets [i]);
7141 emit_exception_info (MonoAotCompile *acfg)
7147 offsets = g_new0 (gint32, acfg->nmethods);
7148 for (i = 0; i < acfg->nmethods; ++i) {
7149 if (acfg->cfgs [i]) {
7150 emit_exception_debug_info (acfg, acfg->cfgs [i]);
7151 offsets [i] = acfg->cfgs [i]->ex_info_offset;
7157 sprintf (symbol, "ex_info_offsets");
7158 emit_section_change (acfg, RODATA_SECT, 1);
7159 emit_alignment (acfg, 8);
7160 emit_label (acfg, symbol);
7162 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->nmethods, 10, offsets);
7167 emit_unwind_info (MonoAotCompile *acfg)
7173 * The unwind info contains a lot of duplicates so we emit each unique
7174 * entry once, and only store the offset from the start of the table in the
7178 sprintf (symbol, "unwind_info");
7179 emit_section_change (acfg, RODATA_SECT, 1);
7180 emit_alignment (acfg, 8);
7181 emit_label (acfg, symbol);
7183 for (i = 0; i < acfg->unwind_ops->len; ++i) {
7184 guint32 index = GPOINTER_TO_UINT (g_ptr_array_index (acfg->unwind_ops, i));
7185 guint8 *unwind_info;
7186 guint32 unwind_info_len;
7190 unwind_info = mono_get_cached_unwind_info (index, &unwind_info_len);
7193 encode_value (unwind_info_len, p, &p);
7194 emit_bytes (acfg, buf, p - buf);
7195 emit_bytes (acfg, unwind_info, unwind_info_len);
7197 acfg->stats.unwind_info_size += (p - buf) + unwind_info_len;
7202 emit_class_info (MonoAotCompile *acfg)
7208 offsets = g_new0 (gint32, acfg->image->tables [MONO_TABLE_TYPEDEF].rows);
7209 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i)
7210 offsets [i] = emit_klass_info (acfg, MONO_TOKEN_TYPE_DEF | (i + 1));
7212 sprintf (symbol, "class_info_offsets");
7213 emit_section_change (acfg, RODATA_SECT, 1);
7214 emit_alignment (acfg, 8);
7215 emit_label (acfg, symbol);
7217 acfg->stats.offsets_size += emit_offset_table (acfg, acfg->image->tables [MONO_TABLE_TYPEDEF].rows, 10, offsets);
7221 typedef struct ClassNameTableEntry {
7222 guint32 token, index;
7223 struct ClassNameTableEntry *next;
7224 } ClassNameTableEntry;
7227 emit_class_name_table (MonoAotCompile *acfg)
7230 guint32 token, hash;
7235 ClassNameTableEntry *entry, *new_entry;
7238 * Construct a chained hash table for mapping class names to typedef tokens.
7240 table_size = g_spaced_primes_closest ((int)(acfg->image->tables [MONO_TABLE_TYPEDEF].rows * 1.5));
7241 table = g_ptr_array_sized_new (table_size);
7242 for (i = 0; i < table_size; ++i)
7243 g_ptr_array_add (table, NULL);
7244 for (i = 0; i < acfg->image->tables [MONO_TABLE_TYPEDEF].rows; ++i) {
7245 token = MONO_TOKEN_TYPE_DEF | (i + 1);
7246 klass = mono_class_get (acfg->image, token);
7248 mono_loader_clear_error ();
7251 full_name = mono_type_get_name_full (mono_class_get_type (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
7252 hash = mono_metadata_str_hash (full_name) % table_size;
7255 /* FIXME: Allocate from the mempool */
7256 new_entry = g_new0 (ClassNameTableEntry, 1);
7257 new_entry->token = token;
7259 entry = g_ptr_array_index (table, hash);
7260 if (entry == NULL) {
7261 new_entry->index = hash;
7262 g_ptr_array_index (table, hash) = new_entry;
7265 entry = entry->next;
7267 entry->next = new_entry;
7268 new_entry->index = table->len;
7269 g_ptr_array_add (table, new_entry);
7273 /* Emit the table */
7274 sprintf (symbol, "class_name_table");
7275 emit_section_change (acfg, RODATA_SECT, 0);
7276 emit_alignment (acfg, 8);
7277 emit_label (acfg, symbol);
7279 /* FIXME: Optimize memory usage */
7280 g_assert (table_size < 65000);
7281 emit_int16 (acfg, table_size);
7282 g_assert (table->len < 65000);
7283 for (i = 0; i < table->len; ++i) {
7284 ClassNameTableEntry *entry = g_ptr_array_index (table, i);
7286 if (entry == NULL) {
7287 emit_int16 (acfg, 0);
7288 emit_int16 (acfg, 0);
7290 emit_int16 (acfg, mono_metadata_token_index (entry->token));
7292 emit_int16 (acfg, entry->next->index);
7294 emit_int16 (acfg, 0);
7300 emit_image_table (MonoAotCompile *acfg)
7306 * The image table is small but referenced in a lot of places.
7307 * So we emit it at once, and reference its elements by an index.
7310 sprintf (symbol, "image_table");
7311 emit_section_change (acfg, RODATA_SECT, 1);
7312 emit_alignment (acfg, 8);
7313 emit_label (acfg, symbol);
7315 emit_int32 (acfg, acfg->image_table->len);
7316 for (i = 0; i < acfg->image_table->len; i++) {
7317 MonoImage *image = (MonoImage*)g_ptr_array_index (acfg->image_table, i);
7318 MonoAssemblyName *aname = &image->assembly->aname;
7320 /* FIXME: Support multi-module assemblies */
7321 g_assert (image->assembly->image == image);
7323 emit_string (acfg, image->assembly_name);
7324 emit_string (acfg, image->guid);
7325 emit_string (acfg, aname->culture ? aname->culture : "");
7326 emit_string (acfg, (const char*)aname->public_key_token);
7328 emit_alignment (acfg, 8);
7329 emit_int32 (acfg, aname->flags);
7330 emit_int32 (acfg, aname->major);
7331 emit_int32 (acfg, aname->minor);
7332 emit_int32 (acfg, aname->build);
7333 emit_int32 (acfg, aname->revision);
7338 emit_got_info (MonoAotCompile *acfg)
7341 int i, first_plt_got_patch, buf_size;
7343 guint32 *got_info_offsets;
7345 /* Add the patches needed by the PLT to the GOT */
7346 acfg->plt_got_offset_base = acfg->got_offset;
7347 first_plt_got_patch = acfg->got_patches->len;
7348 for (i = 1; i < acfg->plt_offset; ++i) {
7349 MonoPltEntry *plt_entry = g_hash_table_lookup (acfg->plt_offset_to_entry, GUINT_TO_POINTER (i));
7351 g_ptr_array_add (acfg->got_patches, plt_entry->ji);
7353 acfg->stats.got_slot_types [plt_entry->ji->type] ++;
7356 acfg->got_offset += acfg->plt_offset;
7360 * - optimize offsets table.
7361 * - reduce number of exported symbols.
7362 * - emit info for a klass only once.
7363 * - determine when a method uses a GOT slot which is guaranteed to be already
7365 * - clean up and document the code.
7366 * - use String.Empty in class libs.
7369 /* Encode info required to decode shared GOT entries */
7370 buf_size = acfg->got_patches->len * 128;
7371 p = buf = mono_mempool_alloc (acfg->mempool, buf_size);
7372 got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->got_patches->len * sizeof (guint32));
7373 acfg->plt_got_info_offsets = mono_mempool_alloc (acfg->mempool, acfg->plt_offset * sizeof (guint32));
7375 if (acfg->plt_offset)
7376 acfg->plt_got_info_offsets [0] = 0;
7377 for (i = 0; i < acfg->got_patches->len; ++i) {
7378 MonoJumpInfo *ji = g_ptr_array_index (acfg->got_patches, i);
7383 encode_value (ji->type, p, &p);
7385 encode_patch (acfg, ji, p, &p);
7386 acfg->stats.got_slot_info_sizes [ji->type] += p - p2;
7387 g_assert (p - buf <= buf_size);
7388 got_info_offsets [i] = add_to_blob (acfg, buf, p - buf);
7390 if (i >= first_plt_got_patch)
7391 acfg->plt_got_info_offsets [i - first_plt_got_patch + 1] = got_info_offsets [i];
7392 acfg->stats.got_info_size += p - buf;
7395 /* Emit got_info_offsets table */
7396 sprintf (symbol, "got_info_offsets");
7397 emit_section_change (acfg, RODATA_SECT, 1);
7398 emit_alignment (acfg, 8);
7399 emit_label (acfg, symbol);
7401 /* No need to emit offsets for the got plt entries, the plt embeds them directly */
7402 acfg->stats.offsets_size += emit_offset_table (acfg, first_plt_got_patch, 10, (gint32*)got_info_offsets);
7406 emit_got (MonoAotCompile *acfg)
7411 /* Don't make GOT global so accesses to it don't need relocations */
7412 sprintf (symbol, "%s", acfg->got_symbol);
7413 emit_section_change (acfg, ".bss", 0);
7414 emit_alignment (acfg, 8);
7415 emit_local_symbol (acfg, symbol, "got_end", FALSE);
7416 emit_label (acfg, symbol);
7417 if (acfg->got_offset > 0)
7418 emit_zero_bytes (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7420 sprintf (symbol, "got_end");
7421 emit_label (acfg, symbol);
7425 typedef struct GlobalsTableEntry {
7426 guint32 value, index;
7427 struct GlobalsTableEntry *next;
7428 } GlobalsTableEntry;
7431 emit_globals (MonoAotCompile *acfg)
7437 GlobalsTableEntry *entry, *new_entry;
7439 if (!acfg->aot_opts.static_link)
7443 * When static linking, we emit a table containing our globals.
7447 * Construct a chained hash table for mapping global names to their index in
7448 * the globals table.
7450 table_size = g_spaced_primes_closest ((int)(acfg->globals->len * 1.5));
7451 table = g_ptr_array_sized_new (table_size);
7452 for (i = 0; i < table_size; ++i)
7453 g_ptr_array_add (table, NULL);
7454 for (i = 0; i < acfg->globals->len; ++i) {
7455 char *name = g_ptr_array_index (acfg->globals, i);
7457 hash = mono_metadata_str_hash (name) % table_size;
7459 /* FIXME: Allocate from the mempool */
7460 new_entry = g_new0 (GlobalsTableEntry, 1);
7461 new_entry->value = i;
7463 entry = g_ptr_array_index (table, hash);
7464 if (entry == NULL) {
7465 new_entry->index = hash;
7466 g_ptr_array_index (table, hash) = new_entry;
7469 entry = entry->next;
7471 entry->next = new_entry;
7472 new_entry->index = table->len;
7473 g_ptr_array_add (table, new_entry);
7477 /* Emit the table */
7478 sprintf (symbol, ".Lglobals_hash");
7479 emit_section_change (acfg, RODATA_SECT, 0);
7480 emit_alignment (acfg, 8);
7481 emit_label (acfg, symbol);
7483 /* FIXME: Optimize memory usage */
7484 g_assert (table_size < 65000);
7485 emit_int16 (acfg, table_size);
7486 for (i = 0; i < table->len; ++i) {
7487 GlobalsTableEntry *entry = g_ptr_array_index (table, i);
7489 if (entry == NULL) {
7490 emit_int16 (acfg, 0);
7491 emit_int16 (acfg, 0);
7493 emit_int16 (acfg, entry->value + 1);
7495 emit_int16 (acfg, entry->next->index);
7497 emit_int16 (acfg, 0);
7501 /* Emit the names */
7502 for (i = 0; i < acfg->globals->len; ++i) {
7503 char *name = g_ptr_array_index (acfg->globals, i);
7505 sprintf (symbol, "name_%d", i);
7506 emit_section_change (acfg, RODATA_SECT, 1);
7508 emit_alignment (acfg, 4);
7510 emit_label (acfg, symbol);
7511 emit_string (acfg, name);
7514 /* Emit the globals table */
7515 sprintf (symbol, "globals");
7516 emit_section_change (acfg, ".data", 0);
7517 /* This is not a global, since it is accessed by the init function */
7518 emit_alignment (acfg, 8);
7519 emit_label (acfg, symbol);
7521 sprintf (symbol, "%sglobals_hash", acfg->temp_prefix);
7522 emit_pointer (acfg, symbol);
7524 for (i = 0; i < acfg->globals->len; ++i) {
7525 char *name = g_ptr_array_index (acfg->globals, i);
7527 sprintf (symbol, "name_%d", i);
7528 emit_pointer (acfg, symbol);
7530 sprintf (symbol, "%s", name);
7531 emit_pointer (acfg, symbol);
7533 /* Null terminate the table */
7534 emit_int32 (acfg, 0);
7535 emit_int32 (acfg, 0);
7539 emit_autoreg (MonoAotCompile *acfg)
7544 * Emit a function into the .ctor section which will be called by the ELF
7545 * loader to register this module with the runtime.
7547 if (! (!acfg->use_bin_writer && acfg->aot_opts.static_link && acfg->aot_opts.autoreg))
7550 symbol = g_strdup_printf ("_%s_autoreg", acfg->static_linking_symbol);
7552 arch_emit_autoreg (acfg, symbol);
7558 emit_mem_end (MonoAotCompile *acfg)
7562 sprintf (symbol, "mem_end");
7563 emit_section_change (acfg, ".text", 1);
7564 emit_alignment (acfg, 8);
7565 emit_label (acfg, symbol);
7569 * Emit a structure containing all the information not stored elsewhere.
7572 emit_file_info (MonoAotCompile *acfg)
7577 const char *gc_name;
7580 emit_string_symbol (acfg, "assembly_guid" , acfg->image->guid);
7582 if (acfg->aot_opts.bind_to_runtime_version) {
7583 build_info = mono_get_runtime_build_info ();
7584 emit_string_symbol (acfg, "runtime_version", build_info);
7585 g_free (build_info);
7587 emit_string_symbol (acfg, "runtime_version", "");
7590 /* Emit a string holding the assembly name */
7591 emit_string_symbol (acfg, "assembly_name", acfg->image->assembly->aname.name);
7594 * The managed allocators are GC specific, so can't use an AOT image created by one GC
7597 gc_name = mono_gc_get_gc_name ();
7598 gc_name_offset = add_to_blob (acfg, (guint8*)gc_name, strlen (gc_name) + 1);
7600 sprintf (symbol, "%smono_aot_file_info", acfg->user_symbol_prefix);
7601 emit_section_change (acfg, ".data", 0);
7602 emit_alignment (acfg, 8);
7603 emit_label (acfg, symbol);
7604 if (!acfg->aot_opts.static_link)
7605 emit_global (acfg, symbol, FALSE);
7607 /* The data emitted here must match MonoAotFileInfo. */
7609 emit_int32 (acfg, MONO_AOT_FILE_VERSION);
7610 emit_int32 (acfg, 0);
7613 * We emit pointers to our data structures instead of emitting global symbols which
7614 * point to them, to reduce the number of globals, and because using globals leads to
7615 * various problems (i.e. arm/thumb).
7617 emit_pointer (acfg, acfg->got_symbol);
7618 emit_pointer (acfg, "methods");
7621 * Emit a reference to the mono_eh_frame table created by our modified LLVM compiler.
7623 emit_pointer (acfg, "mono_eh_frame");
7625 emit_pointer (acfg, NULL);
7627 emit_pointer (acfg, "blob");
7628 emit_pointer (acfg, "class_name_table");
7629 emit_pointer (acfg, "class_info_offsets");
7630 emit_pointer (acfg, "method_info_offsets");
7631 emit_pointer (acfg, "ex_info_offsets");
7632 emit_pointer (acfg, "code_offsets");
7633 if (acfg->direct_method_addresses)
7634 emit_pointer (acfg, "method_addresses");
7636 emit_pointer (acfg, NULL);
7637 emit_pointer (acfg, "extra_method_info_offsets");
7638 emit_pointer (acfg, "extra_method_table");
7639 emit_pointer (acfg, "got_info_offsets");
7640 emit_pointer (acfg, "methods_end");
7641 emit_pointer (acfg, "unwind_info");
7642 emit_pointer (acfg, "mem_end");
7643 emit_pointer (acfg, "image_table");
7644 emit_pointer (acfg, "plt");
7645 emit_pointer (acfg, "plt_end");
7646 emit_pointer (acfg, "assembly_guid");
7647 emit_pointer (acfg, "runtime_version");
7648 if (acfg->num_trampoline_got_entries) {
7649 emit_pointer (acfg, "specific_trampolines");
7650 emit_pointer (acfg, "static_rgctx_trampolines");
7651 emit_pointer (acfg, "imt_thunks");
7652 emit_pointer (acfg, "gsharedvt_arg_trampolines");
7654 emit_pointer (acfg, NULL);
7655 emit_pointer (acfg, NULL);
7656 emit_pointer (acfg, NULL);
7657 emit_pointer (acfg, NULL);
7659 if (acfg->thumb_mixed) {
7660 emit_pointer (acfg, "thumb_end");
7662 emit_pointer (acfg, NULL);
7664 if (acfg->aot_opts.static_link) {
7665 emit_pointer (acfg, "globals");
7667 emit_pointer (acfg, NULL);
7669 emit_pointer (acfg, "assembly_name");
7670 emit_pointer (acfg, "unbox_trampolines");
7671 emit_pointer (acfg, "unbox_trampolines_end");
7673 emit_int32 (acfg, acfg->plt_got_offset_base);
7674 emit_int32 (acfg, (int)(acfg->got_offset * sizeof (gpointer)));
7675 emit_int32 (acfg, acfg->plt_offset);
7676 emit_int32 (acfg, acfg->nmethods);
7677 emit_int32 (acfg, acfg->flags);
7678 emit_int32 (acfg, acfg->opts);
7679 emit_int32 (acfg, acfg->simd_opts);
7680 emit_int32 (acfg, gc_name_offset);
7682 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7683 emit_int32 (acfg, acfg->num_trampolines [i]);
7684 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7685 emit_int32 (acfg, acfg->trampoline_got_offset_base [i]);
7686 for (i = 0; i < MONO_AOT_TRAMP_NUM; ++i)
7687 emit_int32 (acfg, acfg->trampoline_size [i]);
7688 emit_int32 (acfg, acfg->aot_opts.nrgctx_fetch_trampolines);
7690 #if defined (TARGET_ARM) && defined (TARGET_MACH)
7695 memset (&t, 0, sizeof (MonoType));
7696 t.type = MONO_TYPE_R8;
7697 mono_type_size (&t, &align);
7699 emit_int32 (acfg, align);
7701 memset (&t, 0, sizeof (MonoType));
7702 t.type = MONO_TYPE_I8;
7703 mono_type_size (&t, &align);
7705 emit_int32 (acfg, align);
7708 emit_int32 (acfg, __alignof__ (double));
7709 emit_int32 (acfg, __alignof__ (gint64));
7712 if (acfg->aot_opts.static_link) {
7716 * Emit a global symbol which can be passed by an embedding app to
7717 * mono_aot_register_module (). The symbol points to a pointer to the the file info
7720 sprintf (symbol, "%smono_aot_module_%s_info", acfg->user_symbol_prefix, acfg->image->assembly->aname.name);
7722 /* Get rid of characters which cannot occur in symbols */
7724 for (p = symbol; *p; ++p) {
7725 if (!(isalnum (*p) || *p == '_'))
7728 acfg->static_linking_symbol = g_strdup (symbol);
7729 emit_global_inner (acfg, symbol, FALSE);
7730 emit_label (acfg, symbol);
7731 emit_pointer_2 (acfg, acfg->user_symbol_prefix, "mono_aot_file_info");
7736 emit_blob (MonoAotCompile *acfg)
7740 sprintf (symbol, "blob");
7741 emit_section_change (acfg, RODATA_SECT, 1);
7742 emit_alignment (acfg, 8);
7743 emit_label (acfg, symbol);
7745 emit_bytes (acfg, (guint8*)acfg->blob.data, acfg->blob.index);
7749 emit_dwarf_info (MonoAotCompile *acfg)
7751 #ifdef EMIT_DWARF_INFO
7755 /* DIEs for methods */
7756 for (i = 0; i < acfg->nmethods; ++i) {
7757 MonoCompile *cfg = acfg->cfgs [i];
7762 // FIXME: LLVM doesn't define .Lme_...
7763 if (cfg->compile_llvm)
7766 sprintf (symbol2, "%sme_%x", acfg->temp_prefix, i);
7768 mono_dwarf_writer_emit_method (acfg->dwarf, cfg, cfg->method, cfg->asm_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 ()));
7774 collect_methods (MonoAotCompile *acfg)
7777 MonoImage *image = acfg->image;
7779 /* Collect methods */
7780 for (i = 0; i < image->tables [MONO_TABLE_METHOD].rows; ++i) {
7782 guint32 token = MONO_TOKEN_METHOD_DEF | (i + 1);
7784 method = mono_get_method (acfg->image, token, NULL);
7787 printf ("Failed to load method 0x%x from '%s'.\n", token, image->name);
7791 /* Load all methods eagerly to skip the slower lazy loading code */
7792 mono_class_setup_methods (method->klass);
7794 if (acfg->aot_opts.full_aot && method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL) {
7795 /* Compile the wrapper instead */
7796 /* We do this here instead of add_wrappers () because it is easy to do it here */
7797 MonoMethod *wrapper = mono_marshal_get_native_wrapper (method, check_for_pending_exc, TRUE);
7801 /* FIXME: Some mscorlib methods don't have debug info */
7803 if (acfg->aot_opts.soft_debug && !method->wrapper_type) {
7804 if (!((method->flags & METHOD_ATTRIBUTE_PINVOKE_IMPL) ||
7805 (method->iflags & METHOD_IMPL_ATTRIBUTE_RUNTIME) ||
7806 (method->flags & METHOD_ATTRIBUTE_ABSTRACT) ||
7807 (method->iflags & METHOD_IMPL_ATTRIBUTE_INTERNAL_CALL))) {
7808 if (!mono_debug_lookup_method (method)) {
7809 fprintf (stderr, "Method %s has no debug info, probably the .mdb file for the assembly is missing.\n", mono_method_full_name (method, TRUE));
7816 /* Since we add the normal methods first, their index will be equal to their zero based token index */
7817 add_method_with_index (acfg, method, i, FALSE);
7818 acfg->method_index ++;
7821 /* gsharedvt methods */
7822 for (mindex = 0; mindex < image->tables [MONO_TABLE_METHOD].rows; ++mindex) {
7824 guint32 token = MONO_TOKEN_METHOD_DEF | (mindex + 1);
7826 if (!(acfg->opts & MONO_OPT_GSHAREDVT))
7829 method = mono_get_method (acfg->image, token, NULL);
7832 if (method->is_generic || method->klass->generic_container) {
7833 MonoMethod *gshared;
7835 gshared = mini_get_shared_method_full (method, TRUE, TRUE);
7836 add_extra_method (acfg, gshared);
7840 add_generic_instances (acfg);
7842 if (acfg->aot_opts.full_aot)
7843 add_wrappers (acfg);
7847 compile_methods (MonoAotCompile *acfg)
7851 if (acfg->aot_opts.nthreads > 0) {
7856 gpointer *user_data;
7857 MonoMethod **methods;
7859 methods_len = acfg->methods->len;
7861 len = acfg->methods->len / acfg->aot_opts.nthreads;
7864 * Partition the list of methods into fragments, and hand it to threads to
7867 threads = g_ptr_array_new ();
7868 /* Make a copy since acfg->methods is modified by compile_method () */
7869 methods = g_new0 (MonoMethod*, methods_len);
7870 //memcpy (methods, g_ptr_array_index (acfg->methods, 0), sizeof (MonoMethod*) * methods_len);
7871 for (i = 0; i < methods_len; ++i)
7872 methods [i] = g_ptr_array_index (acfg->methods, i);
7874 while (i < methods_len) {
7875 frag = g_ptr_array_new ();
7876 for (j = 0; j < len; ++j) {
7877 if (i < methods_len) {
7878 g_ptr_array_add (frag, methods [i]);
7883 user_data = g_new0 (gpointer, 3);
7884 user_data [0] = mono_domain_get ();
7885 user_data [1] = acfg;
7886 user_data [2] = frag;
7888 handle = mono_create_thread (NULL, 0, (gpointer)compile_thread_main, user_data, 0, NULL);
7889 g_ptr_array_add (threads, handle);
7893 for (i = 0; i < threads->len; ++i) {
7894 WaitForSingleObjectEx (g_ptr_array_index (threads, i), INFINITE, FALSE);
7900 /* Compile methods added by compile_method () or all methods if nthreads == 0 */
7901 for (i = methods_len; i < acfg->methods->len; ++i) {
7902 /* This can new methods to acfg->methods */
7903 compile_method (acfg, g_ptr_array_index (acfg->methods, i));
7908 compile_asm (MonoAotCompile *acfg)
7910 char *command, *objfile;
7911 char *outfile_name, *tmp_outfile_name;
7912 const char *tool_prefix = acfg->aot_opts.tool_prefix ? acfg->aot_opts.tool_prefix : "";
7914 #if defined(TARGET_AMD64) && !defined(TARGET_MACH)
7915 #define AS_OPTIONS "--64"
7916 #elif defined(TARGET_POWERPC64)
7917 #define AS_OPTIONS "-a64 -mppc64"
7918 #define LD_OPTIONS "-m elf64ppc"
7919 #elif defined(sparc) && SIZEOF_VOID_P == 8
7920 #define AS_OPTIONS "-xarch=v9"
7921 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
7922 #define AS_OPTIONS "-arch i386 -W"
7924 #define AS_OPTIONS ""
7927 #ifdef __native_client_codegen__
7928 #if defined(TARGET_AMD64)
7929 #define AS_NAME "nacl64-as"
7931 #define AS_NAME "nacl-as"
7934 #define AS_NAME "as"
7938 #define LD_OPTIONS ""
7941 #define EH_LD_OPTIONS ""
7943 if (acfg->aot_opts.asm_only) {
7944 printf ("Output file: '%s'.\n", acfg->tmpfname);
7945 if (acfg->aot_opts.static_link)
7946 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7950 if (acfg->aot_opts.static_link) {
7951 if (acfg->aot_opts.outfile)
7952 objfile = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7954 objfile = g_strdup_printf ("%s.o", acfg->image->name);
7956 objfile = g_strdup_printf ("%s.o", acfg->tmpfname);
7958 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);
7959 printf ("Executing the native assembler: %s\n", command);
7960 if (system (command) != 0) {
7968 if (acfg->aot_opts.static_link) {
7969 printf ("Output file: '%s'.\n", objfile);
7970 printf ("Linking symbol: '%s'.\n", acfg->static_linking_symbol);
7975 if (acfg->aot_opts.outfile)
7976 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
7978 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
7980 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
7983 command = g_strdup_printf ("ld -shared -G -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7984 #elif defined(__ppc__) && defined(TARGET_MACH)
7985 command = g_strdup_printf ("gcc -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7986 #elif defined(TARGET_AMD64) && defined(TARGET_MACH)
7987 command = g_strdup_printf ("gcc --shared -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7988 #elif defined(HOST_WIN32)
7989 command = g_strdup_printf ("gcc -shared --dll -mno-cygwin -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7990 #elif defined(TARGET_X86) && defined(TARGET_MACH) && !defined(__native_client_codegen__)
7991 command = g_strdup_printf ("gcc -m32 -dynamiclib -o %s %s.o", tmp_outfile_name, acfg->tmpfname);
7993 command = g_strdup_printf ("%sld %s %s -shared -o %s %s.o", tool_prefix, EH_LD_OPTIONS, LD_OPTIONS, tmp_outfile_name, acfg->tmpfname);
7995 printf ("Executing the native linker: %s\n", command);
7996 if (system (command) != 0) {
7997 g_free (tmp_outfile_name);
7998 g_free (outfile_name);
8006 /*com = g_strdup_printf ("strip --strip-unneeded %s%s", acfg->image->name, SHARED_EXT);
8007 printf ("Stripping the binary: %s\n", com);
8011 #if defined(TARGET_ARM) && !defined(TARGET_MACH)
8013 * gas generates 'mapping symbols' each time code and data is mixed, which
8014 * happens a lot in emit_and_reloc_code (), so we need to get rid of them.
8016 command = g_strdup_printf ("%sstrip --strip-symbol=\\$a --strip-symbol=\\$d %s", tool_prefix, tmp_outfile_name);
8017 printf ("Stripping the binary: %s\n", command);
8018 if (system (command) != 0) {
8019 g_free (tmp_outfile_name);
8020 g_free (outfile_name);
8027 rename (tmp_outfile_name, outfile_name);
8029 #if defined(TARGET_MACH)
8030 command = g_strdup_printf ("dsymutil %s", outfile_name);
8031 printf ("Generating debug symbols: %s\n", command);
8032 if (system (command) != 0) {
8037 if (!acfg->aot_opts.save_temps)
8040 g_free (tmp_outfile_name);
8041 g_free (outfile_name);
8044 if (acfg->aot_opts.save_temps)
8045 printf ("Retained input file.\n");
8047 unlink (acfg->tmpfname);
8052 static MonoAotCompile*
8053 acfg_create (MonoAssembly *ass, guint32 opts)
8055 MonoImage *image = ass->image;
8056 MonoAotCompile *acfg;
8059 acfg = g_new0 (MonoAotCompile, 1);
8060 acfg->methods = g_ptr_array_new ();
8061 acfg->method_indexes = g_hash_table_new (NULL, NULL);
8062 acfg->method_depth = g_hash_table_new (NULL, NULL);
8063 acfg->plt_offset_to_entry = g_hash_table_new (NULL, NULL);
8064 acfg->patch_to_plt_entry = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8065 acfg->patch_to_got_offset = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8066 acfg->patch_to_got_offset_by_type = g_new0 (GHashTable*, MONO_PATCH_INFO_NUM);
8067 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8068 acfg->patch_to_got_offset_by_type [i] = g_hash_table_new (mono_patch_info_hash, mono_patch_info_equal);
8069 acfg->got_patches = g_ptr_array_new ();
8070 acfg->method_to_cfg = g_hash_table_new (NULL, NULL);
8071 acfg->token_info_hash = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8072 acfg->method_to_pinvoke_import = g_hash_table_new_full (NULL, NULL, NULL, g_free);
8073 acfg->image_hash = g_hash_table_new (NULL, NULL);
8074 acfg->image_table = g_ptr_array_new ();
8075 acfg->globals = g_ptr_array_new ();
8076 acfg->image = image;
8078 /* TODO: Write out set of SIMD instructions used, rather than just those available */
8079 acfg->simd_opts = mono_arch_cpu_enumerate_simd_versions ();
8080 acfg->mempool = mono_mempool_new ();
8081 acfg->extra_methods = g_ptr_array_new ();
8082 acfg->unwind_info_offsets = g_hash_table_new (NULL, NULL);
8083 acfg->unwind_ops = g_ptr_array_new ();
8084 acfg->method_label_hash = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
8085 acfg->method_order = g_ptr_array_new ();
8086 acfg->export_names = g_hash_table_new (NULL, NULL);
8087 acfg->klass_blob_hash = g_hash_table_new (NULL, NULL);
8088 acfg->method_blob_hash = g_hash_table_new (NULL, NULL);
8089 acfg->plt_entry_debug_sym_cache = g_hash_table_new (g_str_hash, g_str_equal);
8090 InitializeCriticalSection (&acfg->mutex);
8096 acfg_free (MonoAotCompile *acfg)
8100 img_writer_destroy (acfg->w);
8101 for (i = 0; i < acfg->nmethods; ++i)
8103 g_free (acfg->cfgs [i]);
8104 g_free (acfg->cfgs);
8105 g_free (acfg->static_linking_symbol);
8106 g_free (acfg->got_symbol);
8107 g_free (acfg->plt_symbol);
8108 g_ptr_array_free (acfg->methods, TRUE);
8109 g_ptr_array_free (acfg->got_patches, TRUE);
8110 g_ptr_array_free (acfg->image_table, TRUE);
8111 g_ptr_array_free (acfg->globals, TRUE);
8112 g_ptr_array_free (acfg->unwind_ops, TRUE);
8113 g_hash_table_destroy (acfg->method_indexes);
8114 g_hash_table_destroy (acfg->method_depth);
8115 g_hash_table_destroy (acfg->plt_offset_to_entry);
8116 g_hash_table_destroy (acfg->patch_to_plt_entry);
8117 g_hash_table_destroy (acfg->patch_to_got_offset);
8118 g_hash_table_destroy (acfg->method_to_cfg);
8119 g_hash_table_destroy (acfg->token_info_hash);
8120 g_hash_table_destroy (acfg->method_to_pinvoke_import);
8121 g_hash_table_destroy (acfg->image_hash);
8122 g_hash_table_destroy (acfg->unwind_info_offsets);
8123 g_hash_table_destroy (acfg->method_label_hash);
8124 g_hash_table_destroy (acfg->export_names);
8125 g_hash_table_destroy (acfg->plt_entry_debug_sym_cache);
8126 g_hash_table_destroy (acfg->klass_blob_hash);
8127 g_hash_table_destroy (acfg->method_blob_hash);
8128 for (i = 0; i < MONO_PATCH_INFO_NUM; ++i)
8129 g_hash_table_destroy (acfg->patch_to_got_offset_by_type [i]);
8130 g_free (acfg->patch_to_got_offset_by_type);
8131 mono_mempool_destroy (acfg->mempool);
8136 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)
8138 MonoImage *image = ass->image;
8140 MonoAotCompile *acfg;
8141 char *outfile_name, *tmp_outfile_name, *p;
8145 #ifndef MONO_ARCH_GSHAREDVT_SUPPORTED
8146 opts &= ~MONO_OPT_GSHAREDVT;
8149 printf ("Mono Ahead of Time compiler - compiling assembly %s\n", image->name);
8151 acfg = acfg_create (ass, opts);
8153 memset (&acfg->aot_opts, 0, sizeof (acfg->aot_opts));
8154 acfg->aot_opts.write_symbols = TRUE;
8155 acfg->aot_opts.ntrampolines = 1024;
8156 acfg->aot_opts.nrgctx_trampolines = 1024;
8157 acfg->aot_opts.nimt_trampolines = 128;
8158 acfg->aot_opts.nrgctx_fetch_trampolines = 128;
8159 acfg->aot_opts.ngsharedvt_arg_trampolines = 128;
8160 acfg->aot_opts.llvm_path = g_strdup ("");
8162 acfg->aot_opts.use_trampolines_page = TRUE;
8165 mono_aot_parse_options (aot_options, &acfg->aot_opts);
8167 if (acfg->aot_opts.static_link)
8168 acfg->aot_opts.autoreg = TRUE;
8170 //acfg->aot_opts.print_skipped_methods = TRUE;
8172 #ifndef MONO_ARCH_HAVE_FULL_AOT_TRAMPOLINES
8173 if (acfg->aot_opts.full_aot) {
8174 printf ("--aot=full is not supported on this platform.\n");
8179 if (acfg->aot_opts.direct_pinvoke && !acfg->aot_opts.static_link) {
8180 fprintf (stderr, "The 'direct-pinvoke' AOT option also requires the 'static' AOT option.\n");
8184 if (acfg->aot_opts.static_link)
8185 acfg->aot_opts.asm_writer = TRUE;
8187 if (acfg->aot_opts.soft_debug) {
8188 MonoDebugOptions *opt = mini_get_debug_options ();
8190 opt->mdb_optimizations = TRUE;
8191 opt->gen_seq_points = TRUE;
8193 if (mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
8194 fprintf (stderr, "The soft-debug AOT option requires the --debug option.\n");
8197 acfg->flags |= MONO_AOT_FILE_FLAG_DEBUG;
8200 if (mono_use_llvm) {
8202 acfg->aot_opts.asm_writer = TRUE;
8203 acfg->flags |= MONO_AOT_FILE_FLAG_WITH_LLVM;
8205 if (acfg->aot_opts.soft_debug) {
8206 fprintf (stderr, "The 'soft-debug' option is not supported when compiling with LLVM.\n");
8211 if (acfg->aot_opts.full_aot)
8212 acfg->flags |= MONO_AOT_FILE_FLAG_FULL_AOT;
8214 load_profile_files (acfg);
8216 acfg->num_trampolines [MONO_AOT_TRAMP_SPECIFIC] = acfg->aot_opts.full_aot ? acfg->aot_opts.ntrampolines : 0;
8217 #ifdef MONO_ARCH_GSHARED_SUPPORTED
8218 acfg->num_trampolines [MONO_AOT_TRAMP_STATIC_RGCTX] = acfg->aot_opts.full_aot ? acfg->aot_opts.nrgctx_trampolines : 0;
8220 acfg->num_trampolines [MONO_AOT_TRAMP_IMT_THUNK] = acfg->aot_opts.full_aot ? acfg->aot_opts.nimt_trampolines : 0;
8221 #ifdef MONO_ARCH_GSHAREDVT_SUPPORTED
8222 if (acfg->opts & MONO_OPT_GSHAREDVT)
8223 acfg->num_trampolines [MONO_AOT_TRAMP_GSHAREDVT_ARG] = acfg->aot_opts.full_aot ? acfg->aot_opts.ngsharedvt_arg_trampolines : 0;
8226 acfg->temp_prefix = img_writer_get_temp_label_prefix (NULL);
8230 acfg->got_symbol_base = g_strdup_printf ("mono_aot_%s_got", acfg->image->assembly->aname.name);
8231 acfg->plt_symbol = g_strdup_printf ("%smono_aot_%s_plt", acfg->llvm_label_prefix, acfg->image->assembly->aname.name);
8232 acfg->assembly_name_sym = g_strdup (acfg->image->assembly->aname.name);
8234 /* Get rid of characters which cannot occur in symbols */
8235 for (p = acfg->got_symbol_base; *p; ++p) {
8236 if (!(isalnum (*p) || *p == '_'))
8239 for (p = acfg->plt_symbol; *p; ++p) {
8240 if (!(isalnum (*p) || *p == '_'))
8243 for (p = acfg->assembly_name_sym; *p; ++p) {
8244 if (!(isalnum (*p) || *p == '_'))
8248 acfg->method_index = 1;
8250 collect_methods (acfg);
8252 acfg->cfgs_size = acfg->methods->len + 32;
8253 acfg->cfgs = g_new0 (MonoCompile*, acfg->cfgs_size);
8255 /* PLT offset 0 is reserved for the PLT trampoline */
8256 acfg->plt_offset = 1;
8261 mono_llvm_create_aot_module (acfg->got_symbol_base);
8265 /* GOT offset 0 is reserved for the address of the current assembly */
8269 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8270 ji->type = MONO_PATCH_INFO_IMAGE;
8271 ji->data.image = acfg->image;
8273 get_got_offset (acfg, ji);
8275 /* Slot 1 is reserved for the mscorlib got addr */
8276 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8277 ji->type = MONO_PATCH_INFO_MSCORLIB_GOT_ADDR;
8278 get_got_offset (acfg, ji);
8280 /* This is very common */
8281 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8282 ji->type = MONO_PATCH_INFO_GC_CARD_TABLE_ADDR;
8283 get_got_offset (acfg, ji);
8285 ji = mono_mempool_alloc0 (acfg->mempool, sizeof (MonoAotCompile));
8286 ji->type = MONO_PATCH_INFO_JIT_TLS_ID;
8287 get_got_offset (acfg, ji);
8292 compile_methods (acfg);
8296 acfg->stats.jit_time = TV_ELAPSED (atv, btv);
8302 if (acfg->aot_opts.asm_only) {
8303 if (acfg->aot_opts.outfile)
8304 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8306 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8308 acfg->tmpfname = g_strdup ("temp.s");
8311 emit_llvm_file (acfg);
8315 if (!acfg->aot_opts.asm_only && !acfg->aot_opts.asm_writer && bin_writer_supported ()) {
8316 if (acfg->aot_opts.outfile)
8317 outfile_name = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8319 outfile_name = g_strdup_printf ("%s%s", acfg->image->name, SHARED_EXT);
8322 * Can't use g_file_open_tmp () as it will be deleted at exit, and
8323 * it might be in another file system so the rename () won't work.
8325 tmp_outfile_name = g_strdup_printf ("%s.tmp", outfile_name);
8327 acfg->fp = fopen (tmp_outfile_name, "w");
8329 printf ("Unable to create temporary file '%s': %s\n", tmp_outfile_name, strerror (errno));
8333 acfg->w = img_writer_create (acfg->fp, TRUE);
8334 acfg->use_bin_writer = TRUE;
8337 /* Append to the .s file created by llvm */
8338 /* FIXME: Use multiple files instead */
8339 acfg->fp = fopen (acfg->tmpfname, "a+");
8341 if (acfg->aot_opts.asm_only) {
8342 if (acfg->aot_opts.outfile)
8343 acfg->tmpfname = g_strdup_printf ("%s", acfg->aot_opts.outfile);
8345 acfg->tmpfname = g_strdup_printf ("%s.s", acfg->image->name);
8346 acfg->fp = fopen (acfg->tmpfname, "w+");
8348 int i = g_file_open_tmp ("mono_aot_XXXXXX", &acfg->tmpfname, NULL);
8349 acfg->fp = fdopen (i, "w+");
8351 if (acfg->fp == 0) {
8352 fprintf (stderr, "Unable to open file '%s': %s\n", acfg->tmpfname, strerror (errno));
8356 acfg->w = img_writer_create (acfg->fp, FALSE);
8358 tmp_outfile_name = NULL;
8359 outfile_name = NULL;
8362 acfg->got_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, acfg->got_symbol_base);
8364 /* Compute symbols for methods */
8365 for (i = 0; i < acfg->nmethods; ++i) {
8366 if (acfg->cfgs [i]) {
8367 MonoCompile *cfg = acfg->cfgs [i];
8368 int method_index = get_method_index (acfg, cfg->orig_method);
8370 if (COMPILE_LLVM (cfg))
8371 cfg->asm_symbol = g_strdup_printf ("%s%s", acfg->llvm_label_prefix, cfg->llvm_method_name);
8372 else if (acfg->global_symbols)
8373 cfg->asm_symbol = get_debug_sym (cfg->method, "", acfg->method_label_hash);
8375 cfg->asm_symbol = g_strdup_printf ("%s%sm_%x", acfg->temp_prefix, acfg->llvm_label_prefix, method_index);
8379 if (!acfg->aot_opts.nodebug || acfg->aot_opts.dwarf_debug) {
8380 if (acfg->aot_opts.dwarf_debug && mono_debug_format == MONO_DEBUG_FORMAT_NONE) {
8381 fprintf (stderr, "The dwarf AOT option requires the --debug option.\n");
8384 acfg->dwarf = mono_dwarf_writer_create (acfg->w, NULL, 0, FALSE);
8387 img_writer_emit_start (acfg->w);
8390 mono_dwarf_writer_emit_base_info (acfg->dwarf, mono_unwind_get_cie_program ());
8392 if (acfg->thumb_mixed) {
8395 * This global symbol marks the end of THUMB code, and the beginning of ARM
8396 * code generated by our JIT.
8398 sprintf (symbol, "thumb_end");
8399 emit_section_change (acfg, ".text", 0);
8400 emit_alignment (acfg, 8);
8401 emit_label (acfg, symbol);
8402 emit_zero_bytes (acfg, 16);
8404 fprintf (acfg->fp, ".arm\n");
8411 emit_extra_methods (acfg);
8413 emit_trampolines (acfg);
8415 emit_class_name_table (acfg);
8417 emit_got_info (acfg);
8419 emit_exception_info (acfg);
8421 emit_unwind_info (acfg);
8423 emit_class_info (acfg);
8427 emit_image_table (acfg);
8431 emit_file_info (acfg);
8435 emit_globals (acfg);
8437 emit_autoreg (acfg);
8440 emit_dwarf_info (acfg);
8441 mono_dwarf_writer_close (acfg->dwarf);
8444 emit_mem_end (acfg);
8446 if (acfg->need_pt_gnu_stack) {
8447 /* This is required so the .so doesn't have an executable stack */
8448 /* The bin writer already emits this */
8449 if (!acfg->use_bin_writer)
8450 fprintf (acfg->fp, "\n.section .note.GNU-stack,\"\",@progbits\n");
8455 acfg->stats.gen_time = TV_ELAPSED (atv, btv);
8458 g_assert (acfg->got_offset <= acfg->final_got_size);
8460 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);
8461 printf ("Compiled: %d/%d (%d%%), No GOT slots: %d (%d%%), Direct calls: %d (%d%%)\n",
8462 acfg->stats.ccount, acfg->stats.mcount, acfg->stats.mcount ? (acfg->stats.ccount * 100) / acfg->stats.mcount : 100,
8463 acfg->stats.methods_without_got_slots, acfg->stats.mcount ? (acfg->stats.methods_without_got_slots * 100) / acfg->stats.mcount : 100,
8464 acfg->stats.direct_calls, acfg->stats.all_calls ? (acfg->stats.direct_calls * 100) / acfg->stats.all_calls : 100);
8465 if (acfg->stats.genericcount)
8466 printf ("%d methods are generic (%d%%)\n", acfg->stats.genericcount, acfg->stats.mcount ? (acfg->stats.genericcount * 100) / acfg->stats.mcount : 100);
8467 if (acfg->stats.abscount)
8468 printf ("%d methods contain absolute addresses (%d%%)\n", acfg->stats.abscount, acfg->stats.mcount ? (acfg->stats.abscount * 100) / acfg->stats.mcount : 100);
8469 if (acfg->stats.lmfcount)
8470 printf ("%d methods contain lmf pointers (%d%%)\n", acfg->stats.lmfcount, acfg->stats.mcount ? (acfg->stats.lmfcount * 100) / acfg->stats.mcount : 100);
8471 if (acfg->stats.ocount)
8472 printf ("%d methods have other problems (%d%%)\n", acfg->stats.ocount, acfg->stats.mcount ? (acfg->stats.ocount * 100) / acfg->stats.mcount : 100);
8474 printf ("Methods compiled with LLVM: %d (%d%%)\n", acfg->stats.llvm_count, acfg->stats.mcount ? (acfg->stats.llvm_count * 100) / acfg->stats.mcount : 100);
8477 res = img_writer_emit_writeout (acfg->w);
8482 if (acfg->use_bin_writer) {
8483 int err = rename (tmp_outfile_name, outfile_name);
8486 printf ("Unable to rename '%s' to '%s': %s\n", tmp_outfile_name, outfile_name, strerror (errno));
8490 res = compile_asm (acfg);
8497 acfg->stats.link_time = TV_ELAPSED (atv, btv);
8499 if (acfg->aot_opts.stats) {
8502 printf ("GOT slot distribution:\n");
8503 for (i = 0; i < MONO_PATCH_INFO_NONE; ++i)
8504 if (acfg->stats.got_slot_types [i])
8505 printf ("\t%s: %d (%d)\n", get_patch_name (i), acfg->stats.got_slot_types [i], acfg->stats.got_slot_info_sizes [i]);
8508 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);
8520 mono_aot_readonly_field_override (MonoClassField *field)
8526 mono_compile_assembly (MonoAssembly *ass, guint32 opts, const char *aot_options)